Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1431
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1431 ! raeburn 4: # $Id: lonnet.pm,v 1.1430 2020/10/20 01:38:12 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.807 albertel 99: use LONCAPA qw(:DEFAULT :match);
1.740 www 100: use LONCAPA::Configuration;
1.1160 www 101: use LONCAPA::lonmetadata;
1.1167 droeschl 102: use LONCAPA::Lond;
1.1345 raeburn 103: use LONCAPA::LWPReq;
1.1406 raeburn 104: use LONCAPA::transliterate;
1.1117 foxr 105:
1.1090 raeburn 106: use File::Copy;
1.676 albertel 107:
1.195 www 108: my $readit;
1.1288 damieng 109: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 110:
1.619 albertel 111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
1.449 matthew 116:
1.1187 raeburn 117: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 118: {
119: my $logid;
1.1187 raeburn 120: sub write_log {
1.1188 raeburn 121: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 122: if ($context eq 'course') {
123: if (($cnum eq '') || ($cdom eq '')) {
124: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
125: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
126: }
1.957 raeburn 127: }
1.1184 raeburn 128: $logid ++;
1.957 raeburn 129: my $now = time();
130: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
136: 'exe_ip' => $ENV{'REMOTE_ADDR'},
137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 144: }
145: }
1.1 albertel 146:
1.163 harris41 147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 149: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 150: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
1.1 albertel 157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
1.1359 raeburn 162: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
1.448 albertel 165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
1.1359 raeburn 175: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
1.1 albertel 179: return 1;
180: }
181:
1.850 albertel 182: sub create_connection {
1.853 albertel 183: my ($hostname,$lonid) = @_;
1.851 albertel 184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
1.1399 raeburn 188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850 albertel 189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
1.983 raeburn 195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
1.850 albertel 209:
1.1106 raeburn 210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
1.1315 raeburn 233: sub get_servercerts_info {
1.1383 raeburn 234: my ($lonhost,$hostname,$context) = @_;
235: return if ($lonhost eq '');
236: if ($hostname eq '') {
237: $hostname = &hostname($lonhost);
238: }
239: return if ($hostname eq '');
1.1315 raeburn 240: my ($rep,$uselocal);
1.1388 raeburn 241: if ($context eq 'install') {
1.1387 raeburn 242: $uselocal = 1;
243: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 244: $uselocal = 1;
245: }
1.1387 raeburn 246: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 247: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 248: if ($distro eq '') {
249: $uselocal = 0;
250: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 251: if ($1 < 6) {
252: $uselocal = 0;
253: }
1.1346 raeburn 254: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
255: if ($1 < 12) {
256: $uselocal = 0;
257: }
1.1315 raeburn 258: }
259: }
260: if ($uselocal) {
1.1383 raeburn 261: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 262: } else {
263: $rep=&reply('servercerts',$lonhost);
264: }
265: my ($result,%returnhash);
266: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
267: ($rep eq 'unknown_cmd')) {
268: $result = $rep;
269: } else {
270: $result = 'ok';
271: my @pairs=split(/\&/,$rep);
272: foreach my $item (@pairs) {
273: my ($key,$value)=split(/=/,$item,2);
274: my $what = &unescape($key);
275: $returnhash{$what}=&thaw_unescape($value);
276: }
277: }
278: return ($result,\%returnhash);
279: }
280:
1.993 raeburn 281: sub get_server_loncaparev {
1.1073 raeburn 282: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 283: if (defined($lonhost)) {
284: if (!defined(&hostname($lonhost))) {
285: undef($lonhost);
286: }
287: }
288: if (!defined($lonhost)) {
289: if (defined(&domain($dom,'primary'))) {
290: $lonhost=&domain($dom,'primary');
291: if ($lonhost eq 'no_host') {
292: undef($lonhost);
293: }
294: }
295: }
296: if (defined($lonhost)) {
1.1073 raeburn 297: my $cachetime = 12*3600;
298: if (!$ignore_cache) {
299: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
300: if (defined($cached)) {
301: return $loncaparev;
302: }
303: }
304: my ($answer,$loncaparev);
305: my @ids=¤t_machine_ids();
306: if (grep(/^\Q$lonhost\E$/,@ids)) {
307: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 308: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 309: $loncaparev = $1;
310: }
311: } else {
312: $answer = &reply('serverloncaparev',$lonhost);
313: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
314: if ($caller eq 'loncron') {
1.1397 raeburn 315: my $hostname = &hostname($lonhost);
1.1073 raeburn 316: my $protocol = $protocol{$lonhost};
317: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 318: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 319: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 320: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 321: unless ($response->is_error()) {
322: my $content = $response->content;
1.1081 raeburn 323: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 324: $loncaparev = $1;
325: }
326: }
327: } else {
328: $loncaparev = $loncaparevs{$lonhost};
329: }
1.1081 raeburn 330: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 331: $loncaparev = $1;
332: }
1.993 raeburn 333: }
1.1073 raeburn 334: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 335: }
336: }
337:
1.1074 raeburn 338: sub get_server_homeID {
339: my ($hostname,$ignore_cache,$caller) = @_;
340: unless ($ignore_cache) {
341: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
342: if (defined($cached)) {
343: return $serverhomeID;
344: }
345: }
346: my $cachetime = 12*3600;
347: my $serverhomeID;
348: if ($caller eq 'loncron') {
349: my @machine_ids = &machine_ids($hostname);
350: foreach my $id (@machine_ids) {
351: my $response = &reply('serverhomeID',$id);
352: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
353: $serverhomeID = $response;
354: last;
355: }
356: }
357: if ($serverhomeID eq '') {
358: $serverhomeID = $machine_ids[-1];
359: }
360: } else {
361: $serverhomeID = $serverhomeIDs{$hostname};
362: }
363: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
364: }
365:
1.1121 raeburn 366: sub get_remote_globals {
367: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 368: my ($result,%returnhash,%whatneeded);
369: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 370: foreach my $what (sort(keys(%{$whathash}))) {
371: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 372: my ($response,$cached);
1.1121 raeburn 373: unless ($ignore_cache) {
1.1125 raeburn 374: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 375: }
376: if (defined($cached)) {
1.1125 raeburn 377: $returnhash{$what} = $response;
1.1121 raeburn 378: } else {
1.1125 raeburn 379: $whatneeded{$what} = 1;
1.1121 raeburn 380: }
381: }
1.1125 raeburn 382: if (keys(%whatneeded) == 0) {
383: $result = 'ok';
384: } else {
1.1121 raeburn 385: my $requested = &freeze_escape(\%whatneeded);
386: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 387: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
388: ($rep eq 'unknown_cmd')) {
389: $result = $rep;
390: } else {
391: $result = 'ok';
1.1121 raeburn 392: my @pairs=split(/\&/,$rep);
1.1125 raeburn 393: foreach my $item (@pairs) {
394: my ($key,$value)=split(/=/,$item,2);
395: my $what = &unescape($key);
396: my $hashid = $lonhost.'-'.$what;
397: $returnhash{$what}=&thaw_unescape($value);
398: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 399: }
400: }
401: }
402: }
1.1125 raeburn 403: return ($result,\%returnhash);
1.1121 raeburn 404: }
405:
1.1124 raeburn 406: sub remote_devalidate_cache {
1.1241 raeburn 407: my ($lonhost,$cachekeys) = @_;
408: my $items;
409: return unless (ref($cachekeys) eq 'ARRAY');
410: my $cachestr = join('&',@{$cachekeys});
411: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 412: return $response;
413: }
414:
1.1 albertel 415: # -------------------------------------------------- Non-critical communication
416: sub subreply {
417: my ($cmd,$server)=@_;
1.838 albertel 418: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 419: #
420: # With loncnew process trimming, there's a timing hole between lonc server
421: # process exit and the master server picking up the listen on the AF_UNIX
422: # socket. In that time interval, a lock file will exist:
423:
424: my $lockfile=$peerfile.".lock";
425: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 426: sleep(0.1);
1.549 foxr 427: }
428: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 429: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 430: #
1.550 foxr 431: # We'll give the connection a few tries before abandoning it. If
432: # connection is not possible, we'll con_lost back to the client.
433: #
434: my $client;
435: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
436: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
437: Type => SOCK_STREAM,
438: Timeout => 10);
1.869 albertel 439: if ($client) {
1.550 foxr 440: last; # Connected!
1.850 albertel 441: } else {
1.853 albertel 442: &create_connection(&hostname($server),$server);
1.550 foxr 443: }
1.1289 damieng 444: sleep(0.1); # Try again later if failed connection.
1.550 foxr 445: }
446: my $answer;
447: if ($client) {
1.704 albertel 448: print $client "sethost:$server:$cmd\n";
1.550 foxr 449: $answer=<$client>;
450: if (!$answer) { $answer="con_lost"; }
451: chomp($answer);
452: } else {
453: $answer = 'con_lost'; # Failed connection.
454: }
1.1 albertel 455: return $answer;
456: }
457:
458: sub reply {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 461: my $answer=subreply($cmd,$server);
1.65 www 462: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 463: my $logged = $cmd;
464: if ($cmd =~ /^encrypt:([^:]+):/) {
465: my $subcmd = $1;
466: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
467: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
468: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
469: (undef,undef,my @rest) = split(/:/,$cmd);
470: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
471: splice(@rest,2,1,'Hidden');
472: } elsif ($subcmd eq 'passwd') {
473: splice(@rest,2,2,('Hidden','Hidden'));
474: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
475: ($subcmd eq 'autoexportgrades')) {
476: splice(@rest,3,1,'Hidden');
477: }
478: $logged = join(':',('encrypt:'.$subcmd,@rest));
479: }
480: }
481: &logthis("<font color=\"blue\">WARNING:".
482: " $logged to $server returned $answer</font>");
1.12 www 483: }
1.1 albertel 484: return $answer;
485: }
486:
487: # ----------------------------------------------------------- Send USR1 to lonc
488:
489: sub reconlonc {
1.891 albertel 490: my ($lonid) = @_;
491: if ($lonid) {
1.1295 raeburn 492: my $hostname = &hostname($lonid);
1.891 albertel 493: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
494: if ($hostname && -e $peerfile) {
495: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
496: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
497: Type => SOCK_STREAM,
498: Timeout => 10);
499: if ($client) {
500: print $client ("reset_retries\n");
501: my $answer=<$client>;
502: #reset just this one.
503: }
504: }
505: return;
506: }
507:
1.836 www 508: &logthis("Trying to reconnect lonc");
1.1 albertel 509: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 510: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 511: my $loncpid=<$fh>;
512: chomp($loncpid);
513: if (kill 0 => $loncpid) {
514: &logthis("lonc at pid $loncpid responding, sending USR1");
515: kill USR1 => $loncpid;
516: sleep 1;
1.1295 raeburn 517: } else {
1.12 www 518: &logthis(
1.672 albertel 519: "<font color=\"blue\">WARNING:".
1.12 www 520: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 521: }
522: } else {
1.836 www 523: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 524: }
525: }
526:
527: # ------------------------------------------------------ Critical communication
1.12 www 528:
1.1 albertel 529: sub critical {
530: my ($cmd,$server)=@_;
1.838 albertel 531: unless (&hostname($server)) {
1.672 albertel 532: &logthis("<font color=\"blue\">WARNING:".
1.89 www 533: " Critical message to unknown server ($server)</font>");
534: return 'no_such_host';
535: }
1.1 albertel 536: my $answer=reply($cmd,$server);
537: if ($answer eq 'con_lost') {
1.1295 raeburn 538: &reconlonc($server);
1.589 albertel 539: my $answer=reply($cmd,$server);
1.1 albertel 540: if ($answer eq 'con_lost') {
541: my $now=time;
542: my $middlename=$cmd;
1.5 www 543: $middlename=substr($middlename,0,16);
1.1 albertel 544: $middlename=~s/\W//g;
545: my $dfilename=
1.305 www 546: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
547: $dumpcount++;
1.1 albertel 548: {
1.448 albertel 549: my $dfh;
1.1359 raeburn 550: if (open($dfh,">",$dfilename)) {
1.448 albertel 551: print $dfh "$cmd\n";
552: close($dfh);
553: }
1.1 albertel 554: }
1.1288 damieng 555: sleep 1;
1.1 albertel 556: my $wcmd='';
557: {
1.448 albertel 558: my $dfh;
1.1359 raeburn 559: if (open($dfh,"<",$dfilename)) {
1.448 albertel 560: $wcmd=<$dfh>;
561: close($dfh);
562: }
1.1 albertel 563: }
564: chomp($wcmd);
1.7 www 565: if ($wcmd eq $cmd) {
1.672 albertel 566: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 567: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 568: &logperm("D:$server:$cmd");
569: return 'con_delayed';
570: } else {
1.672 albertel 571: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 572: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 573: &logperm("F:$server:$cmd");
574: return 'con_failed';
575: }
576: }
577: }
578: return $answer;
1.405 albertel 579: }
580:
1.755 albertel 581: # ------------------------------------------- check if return value is an error
582:
583: sub error {
584: my ($result) = @_;
1.756 albertel 585: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 586: if ($2 == 2) { return undef; }
587: return $1;
588: }
589: return undef;
590: }
591:
1.783 albertel 592: sub convert_and_load_session_env {
593: my ($lonidsdir,$handle)=@_;
594: my @profile;
595: {
1.917 albertel 596: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
597: if (!$opened) {
1.915 albertel 598: return 0;
599: }
1.783 albertel 600: flock($idf,LOCK_SH);
601: @profile=<$idf>;
602: close($idf);
603: }
604: my %temp_env;
605: foreach my $line (@profile) {
1.786 albertel 606: if ($line !~ m/=/) {
607: return 0;
608: }
1.783 albertel 609: chomp($line);
610: my ($envname,$envvalue)=split(/=/,$line,2);
611: $temp_env{&unescape($envname)} = &unescape($envvalue);
612: }
613: unlink("$lonidsdir/$handle.id");
614: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
615: 0640)) {
616: %disk_env = %temp_env;
617: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
618: untie(%disk_env);
619: }
1.786 albertel 620: return 1;
1.783 albertel 621: }
622:
1.374 www 623: # ------------------------------------------- Transfer profile into environment
1.780 albertel 624: my $env_loaded;
625: sub transfer_profile_to_env {
1.788 albertel 626: my ($lonidsdir,$handle,$force_transfer) = @_;
627: if (!$force_transfer && $env_loaded) { return; }
1.374 www 628:
1.720 albertel 629: if (!defined($lonidsdir)) {
630: $lonidsdir = $perlvar{'lonIDsDir'};
631: }
632: if (!defined($handle)) {
633: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
634: }
635:
1.786 albertel 636: my $convert;
637: {
1.917 albertel 638: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
639: if (!$opened) {
1.915 albertel 640: return;
641: }
1.786 albertel 642: flock($idf,LOCK_SH);
643: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
644: &GDBM_READER(),0640)) {
645: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
646: untie(%disk_env);
647: } else {
648: $convert = 1;
649: }
650: }
651: if ($convert) {
652: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
653: &logthis("Failed to load session, or convert session.");
654: }
1.374 www 655: }
1.783 albertel 656:
1.786 albertel 657: my %remove;
1.783 albertel 658: while ( my $envname = each(%env) ) {
1.433 matthew 659: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
660: if ($time < time-300) {
1.783 albertel 661: $remove{$key}++;
1.433 matthew 662: }
663: }
664: }
1.783 albertel 665:
1.619 albertel 666: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 667: $env_loaded=1;
1.783 albertel 668: foreach my $expired_key (keys(%remove)) {
1.433 matthew 669: &delenv($expired_key);
1.374 www 670: }
1.1 albertel 671: }
672:
1.916 albertel 673: # ---------------------------------------------------- Check for valid session
674: sub check_for_valid_session {
1.1355 raeburn 675: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 676: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 677: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
678: if ($name eq 'lonDAV') {
679: $lonidsdir=$r->dir_config('lonDAVsessDir');
680: } else {
681: $lonidsdir=$r->dir_config('lonIDsDir');
682: if ($name eq '') {
683: $name = 'lonID';
684: }
685: }
686: if ($name eq 'lonID') {
687: $secure = 'lonSID';
1.1337 raeburn 688: $linkname = 'lonLinkID';
689: $pubname = 'lonPubID';
1.1378 raeburn 690: if (exists($cookies{$secure})) {
691: $lonid=$cookies{$secure};
692: } elsif (exists($cookies{$name})) {
693: $lonid=$cookies{$name};
1.1400 raeburn 694: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 695: $lonid=$cookies{$linkname};
1.1378 raeburn 696: } elsif (exists($cookies{$pubname})) {
697: $lonid=$cookies{$pubname};
1.1337 raeburn 698: }
1.1378 raeburn 699: } else {
700: $lonid=$cookies{$name};
1.1337 raeburn 701: }
1.916 albertel 702: return undef if (!$lonid);
703:
704: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 705: if (-l "$lonidsdir/$handle.id") {
706: my $link = readlink("$lonidsdir/$handle.id");
707: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
708: $handle = $1;
709: }
1.1155 raeburn 710: }
1.1355 raeburn 711: if (!-e "$lonidsdir/$handle.id") {
712: if ((ref($domref)) && ($name eq 'lonID') &&
713: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
714: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
715: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
716: $$domref = $possudom;
717: }
718: }
719: return undef;
720: }
1.916 albertel 721:
1.917 albertel 722: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
723: return undef if (!$opened);
1.916 albertel 724:
725: flock($idf,LOCK_SH);
726: my %disk_env;
727: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
728: &GDBM_READER(),0640)) {
729: return undef;
730: }
731:
732: if (!defined($disk_env{'user.name'})
733: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 734: untie(%disk_env);
1.916 albertel 735: return undef;
736: }
1.1245 raeburn 737:
738: if (ref($userhashref) eq 'HASH') {
739: $userhashref->{'name'} = $disk_env{'user.name'};
740: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361 raeburn 741: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 742: if ($userhashref->{'lti'}) {
743: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
744: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
745: }
1.1212 raeburn 746: }
1.1394 raeburn 747: untie(%disk_env);
1.1245 raeburn 748:
1.916 albertel 749: return $handle;
750: }
751:
1.830 albertel 752: sub timed_flock {
753: my ($file,$lock_type) = @_;
754: my $failed=0;
755: eval {
756: local $SIG{__DIE__}='DEFAULT';
757: local $SIG{ALRM}=sub {
758: $failed=1;
759: die("failed lock");
760: };
761: alarm(13);
762: flock($file,$lock_type);
763: alarm(0);
764: };
765: if ($failed) {
766: return undef;
767: } else {
768: return 1;
769: }
770: }
771:
1.1392 raeburn 772: sub get_sessionfile_vars {
773: my ($handle,$lonidsdir,$storearr) = @_;
774: my %returnhash;
775: unless (ref($storearr) eq 'ARRAY') {
776: return %returnhash;
777: }
778: if (-l "$lonidsdir/$handle.id") {
779: my $link = readlink("$lonidsdir/$handle.id");
780: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
781: $handle = $1;
782: }
783: }
784: if ((-e "$lonidsdir/$handle.id") &&
785: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
786: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
787: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
788: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
789: flock($idf,LOCK_SH);
790: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
791: &GDBM_READER(),0640)) {
792: foreach my $item (@{$storearr}) {
793: $returnhash{$item} = $disk_env{$item};
794: }
795: untie(%disk_env);
796: }
797: }
798: }
799: }
800: return %returnhash;
801: }
802:
1.5 www 803: # ---------------------------------------------------------- Append Environment
804:
805: sub appenv {
1.949 raeburn 806: my ($newenv,$roles) = @_;
807: if (ref($newenv) eq 'HASH') {
808: foreach my $key (keys(%{$newenv})) {
809: my $refused = 0;
810: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
811: $refused = 1;
812: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 813: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 814: if (grep(/^\Q$role\E$/,@{$roles})) {
815: $refused = 0;
816: }
817: }
818: }
819: if ($refused) {
820: &logthis("<font color=\"blue\">WARNING: ".
821: "Attempt to modify environment ".$key." to ".$newenv->{$key}
822: .'</font>');
823: delete($newenv->{$key});
824: } else {
825: $env{$key}=$newenv->{$key};
826: }
827: }
1.1376 raeburn 828: my $lonids = $perlvar{'lonIDsDir'};
829: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
830: my $opened = open(my $env_file,'+<',$env{'user.environment'});
831: if ($opened
832: && &timed_flock($env_file,LOCK_EX)
833: &&
834: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
835: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
836: while (my ($key,$value) = each(%{$newenv})) {
837: $disk_env{$key} = $value;
838: }
839: untie(%disk_env);
840: }
1.35 www 841: }
1.191 harris41 842: }
1.56 www 843: return 'ok';
844: }
845: # ----------------------------------------------------- Delete from Environment
846:
847: sub delenv {
1.1104 raeburn 848: my ($delthis,$regexp,$roles) = @_;
849: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
850: my $refused = 1;
851: if (ref($roles) eq 'ARRAY') {
852: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
853: if (grep(/^\Q$role\E$/,@{$roles})) {
854: $refused = 0;
855: }
856: }
857: if ($refused) {
858: &logthis("<font color=\"blue\">WARNING: ".
859: "Attempt to delete from environment ".$delthis);
860: return 'error';
861: }
1.56 www 862: }
1.917 albertel 863: my $opened = open(my $env_file,'+<',$env{'user.environment'});
864: if ($opened
1.915 albertel 865: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 866: &&
867: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
868: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 869: foreach my $key (keys(%disk_env)) {
1.987 raeburn 870: if ($regexp) {
871: if ($key=~/^$delthis/) {
872: delete($env{$key});
873: delete($disk_env{$key});
874: }
875: } else {
876: if ($key=~/^\Q$delthis\E/) {
877: delete($env{$key});
878: delete($disk_env{$key});
879: }
880: }
1.448 albertel 881: }
1.783 albertel 882: untie(%disk_env);
1.5 www 883: }
884: return 'ok';
1.369 albertel 885: }
886:
1.790 albertel 887: sub get_env_multiple {
888: my ($name) = @_;
889: my @values;
890: if (defined($env{$name})) {
891: # exists is it an array
892: if (ref($env{$name})) {
893: @values=@{ $env{$name} };
894: } else {
895: $values[0]=$env{$name};
896: }
897: }
898: return(@values);
899: }
900:
1.958 www 901: # ------------------------------------------------------------------- Locking
902:
903: sub set_lock {
904: my ($text)=@_;
905: $locknum++;
906: my $id=$$.'-'.$locknum;
907: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
908: 'session.lock.'.$id => $text});
909: return $id;
910: }
911:
912: sub get_locks {
913: my $num=0;
914: my %texts=();
915: foreach my $lock (split(/\,/,$env{'session.locks'})) {
916: if ($lock=~/\w/) {
917: $num++;
918: $texts{$lock}=$env{'session.lock.'.$lock};
919: }
920: }
921: return ($num,%texts);
922: }
923:
924: sub remove_lock {
925: my ($id)=@_;
926: my $newlocks='';
927: foreach my $lock (split(/\,/,$env{'session.locks'})) {
928: if (($lock=~/\w/) && ($lock ne $id)) {
929: $newlocks.=','.$lock;
930: }
931: }
932: &appenv({'session.locks' => $newlocks});
933: &delenv('session.lock.'.$id);
934: }
935:
936: sub remove_all_locks {
937: my $activelocks=$env{'session.locks'};
938: foreach my $lock (split(/\,/,$env{'session.locks'})) {
939: if ($lock=~/\w/) {
940: &remove_lock($lock);
941: }
942: }
943: }
944:
945:
1.369 albertel 946: # ------------------------------------------ Find out current server userload
947: sub userload {
948: my $numusers=0;
949: {
950: opendir(LONIDS,$perlvar{'lonIDsDir'});
951: my $filename;
952: my $curtime=time;
953: while ($filename=readdir(LONIDS)) {
1.925 albertel 954: next if ($filename eq '.' || $filename eq '..');
955: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 956: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 957: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 958: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 959: }
960: closedir(LONIDS);
961: }
962: my $userloadpercent=0;
963: my $maxuserload=$perlvar{'lonUserLoadLim'};
964: if ($maxuserload) {
1.371 albertel 965: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 966: }
1.372 albertel 967: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 968: return $userloadpercent;
1.283 www 969: }
970:
1.1 albertel 971: # ------------------------------ Find server with least workload from spare.tab
1.11 www 972:
1.1 albertel 973: sub spareserver {
1.1083 raeburn 974: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 975: my $spare_server;
1.370 albertel 976: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 977: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
978: : $userloadpercent;
1.1083 raeburn 979: my ($uint_dom,$remotesessions);
980: if (($udom ne '') && (&domain($udom) ne '')) {
981: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
982: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
983: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
984: $remotesessions = $udomdefaults{'remotesessions'};
985: }
1.1123 raeburn 986: my $spareshash = &this_host_spares($udom);
987: if (ref($spareshash) eq 'HASH') {
988: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
989: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 990: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
991: $try_server));
1.1123 raeburn 992: ($spare_server, $lowest_load) =
993: &compare_server_load($try_server, $spare_server, $lowest_load);
994: }
1.1083 raeburn 995: }
1.784 albertel 996:
1.1123 raeburn 997: my $found_server = ($spare_server ne '' && $lowest_load < 100);
998:
999: if (!$found_server) {
1000: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1001: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1002: next unless (&spare_can_host($udom,$uint_dom,
1003: $remotesessions,$try_server));
1.1123 raeburn 1004: ($spare_server, $lowest_load) =
1005: &compare_server_load($try_server, $spare_server, $lowest_load);
1006: }
1007: }
1008: }
1.784 albertel 1009: }
1010:
1011: if (!$want_server_name) {
1.1001 raeburn 1012: if (defined($spare_server)) {
1013: my $hostname = &hostname($spare_server);
1.1083 raeburn 1014: if (defined($hostname)) {
1.1397 raeburn 1015: my $protocol = 'http';
1016: if ($protocol{$spare_server} eq 'https') {
1017: $protocol = $protocol{$spare_server};
1018: }
1.1001 raeburn 1019: $spare_server = $protocol.'://'.$hostname;
1020: }
1021: }
1.784 albertel 1022: }
1023: return $spare_server;
1024: }
1025:
1026: sub compare_server_load {
1.1253 raeburn 1027: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1028:
1029: if ($required) {
1030: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1031: my $remoterev = &get_server_loncaparev(undef,$try_server);
1032: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1033: if (($major eq '' && $minor eq '') ||
1034: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1035: return ($spare_server,$lowest_load);
1036: }
1037: }
1.784 albertel 1038:
1039: my $loadans = &reply('load', $try_server);
1040: my $userloadans = &reply('userload',$try_server);
1041:
1042: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1043: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1044: }
1045:
1046: my $load;
1047: if ($loadans =~ /\d/) {
1048: if ($userloadans =~ /\d/) {
1049: #both are numbers, pick the bigger one
1050: $load = ($loadans > $userloadans) ? $loadans
1051: : $userloadans;
1.411 albertel 1052: } else {
1.784 albertel 1053: $load = $loadans;
1.411 albertel 1054: }
1.784 albertel 1055: } else {
1056: $load = $userloadans;
1057: }
1058:
1059: if (($load =~ /\d/) && ($load < $lowest_load)) {
1060: $spare_server = $try_server;
1061: $lowest_load = $load;
1.370 albertel 1062: }
1.784 albertel 1063: return ($spare_server,$lowest_load);
1.202 matthew 1064: }
1.914 albertel 1065:
1066: # --------------------------- ask offload servers if user already has a session
1067: sub find_existing_session {
1068: my ($udom,$uname) = @_;
1.1123 raeburn 1069: my $spareshash = &this_host_spares($udom);
1070: if (ref($spareshash) eq 'HASH') {
1071: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1072: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1073: return $try_server if (&has_user_session($try_server, $udom, $uname));
1074: }
1075: }
1076: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1077: foreach my $try_server (@{ $spareshash->{'default'} }) {
1078: return $try_server if (&has_user_session($try_server, $udom, $uname));
1079: }
1080: }
1.914 albertel 1081: }
1082: return;
1083: }
1084:
1.1411 raeburn 1085: sub delusersession {
1086: my ($lonid,$udom,$uname) = @_;
1087: my $uprimary_id = &domain($udom,'primary');
1088: my $uintdom = &internet_dom($uprimary_id);
1089: my $intdom = &internet_dom($lonid);
1090: my $serverhomedom = &host_domain($lonid);
1091: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1092: return &reply(join(':','delusersession',
1093: map {&escape($_)} ($udom,$uname)),$lonid);
1094: }
1095: return;
1096: }
1097:
1.1389 raeburn 1098: # check if user's browser sent load balancer cookie and server still has session
1099: # and is not overloaded.
1100: sub check_for_balancer_cookie {
1101: my ($r,$update_mtime) = @_;
1102: my ($otherserver,$cookie);
1103: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1104: if (exists($cookies{'balanceID'})) {
1105: my $balid = $cookies{'balanceID'};
1106: $cookie=&LONCAPA::clean_handle($balid->value);
1107: my $balancedir=$r->dir_config('lonBalanceDir');
1108: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1109: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1110: my ($possudom,$possuname) = ($1,$2);
1111: my $has_session = 0;
1112: if ((&domain($possudom) ne '') &&
1113: (&homeserver($possuname,$possudom) ne 'no_host')) {
1114: my $try_server;
1115: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1116: if ($opened) {
1117: flock($idf,LOCK_SH);
1118: while (my $line = <$idf>) {
1119: chomp($line);
1120: if (&hostname($line) ne '') {
1121: $try_server = $line;
1122: last;
1123: }
1124: }
1125: close($idf);
1126: if (($try_server) &&
1127: (&has_user_session($try_server,$possudom,$possuname))) {
1128: my $lowest_load = 30000;
1129: ($otherserver,$lowest_load) =
1130: &compare_server_load($try_server,undef,$lowest_load);
1131: if ($otherserver ne '' && $lowest_load < 100) {
1132: $has_session = 1;
1133: } else {
1134: undef($otherserver);
1135: }
1136: }
1137: }
1138: }
1139: if ($has_session) {
1140: if ($update_mtime) {
1141: my $atime = my $mtime = time;
1142: utime($atime,$mtime,"$balancedir/$cookie.id");
1143: }
1144: } else {
1145: unlink("$balancedir/$cookie.id");
1146: }
1147: }
1148: }
1149: }
1150: return ($otherserver,$cookie);
1151: }
1152:
1.1431 ! raeburn 1153: sub updatebalcookie {
! 1154: my ($cookie,$balancer,$lastentry)=@_;
! 1155: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
! 1156: my ($udom,$uname) = ($1,$2);
! 1157: my $uprimary_id = &domain($udom,'primary');
! 1158: my $uintdom = &internet_dom($uprimary_id);
! 1159: my $intdom = &internet_dom($balancer);
! 1160: my $serverhomedom = &host_domain($balancer);
! 1161: if (($uintdom ne '') && ($uintdom eq $intdom)) {
! 1162: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
! 1163: }
! 1164: }
! 1165: return;
! 1166: }
! 1167:
1.1389 raeburn 1168: sub delbalcookie {
1169: my ($cookie,$balancer) =@_;
1170: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1171: my ($udom,$uname) = ($1,$2);
1172: my $uprimary_id = &domain($udom,'primary');
1173: my $uintdom = &internet_dom($uprimary_id);
1174: my $intdom = &internet_dom($balancer);
1175: my $serverhomedom = &host_domain($balancer);
1176: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 ! raeburn 1177: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1178: }
1179: }
1180: }
1181:
1.914 albertel 1182: # -------------------------------- ask if server already has a session for user
1183: sub has_user_session {
1184: my ($lonid,$udom,$uname) = @_;
1185: my $result = &reply(join(':','userhassession',
1186: map {&escape($_)} ($udom,$uname)),$lonid);
1187: return 1 if ($result eq 'ok');
1188:
1189: return 0;
1190: }
1191:
1.1076 raeburn 1192: # --------- determine least loaded server in a user's domain which allows login
1193:
1194: sub choose_server {
1.1259 raeburn 1195: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1196: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1197: my %servers = &get_servers($udom);
1.1076 raeburn 1198: my $lowest_load = 30000;
1.1259 raeburn 1199: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1200: if ($skiploadbal) {
1201: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1202: unless (defined($cached)) {
1203: my $cachetime = 60*60*24;
1204: my %domconfig =
1205: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1206: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1207: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1208: $cachetime);
1209: }
1210: }
1211: }
1.1076 raeburn 1212: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1213: if ($skiploadbal) {
1214: if (ref($balancers) eq 'HASH') {
1215: next if (exists($balancers->{$lonhost}));
1216: }
1.1389 raeburn 1217: }
1.1115 raeburn 1218: my $loginvia;
1219: if ($checkloginvia) {
1220: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1221: if ($loginvia) {
1222: my ($server,$path) = split(/:/,$loginvia);
1223: ($login_host, $lowest_load) =
1.1253 raeburn 1224: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1225: if ($login_host eq $server) {
1226: $portal_path = $path;
1.1151 raeburn 1227: $isredirect = 1;
1.1116 raeburn 1228: }
1229: } else {
1230: ($login_host, $lowest_load) =
1.1253 raeburn 1231: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1232: if ($login_host eq $lonhost) {
1233: $portal_path = '';
1.1151 raeburn 1234: $isredirect = '';
1.1116 raeburn 1235: }
1236: }
1237: } else {
1.1076 raeburn 1238: ($login_host, $lowest_load) =
1.1253 raeburn 1239: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1240: }
1241: }
1242: if ($login_host ne '') {
1.1116 raeburn 1243: $hostname = &hostname($login_host);
1.1076 raeburn 1244: }
1.1331 raeburn 1245: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1246: }
1247:
1.1420 raeburn 1248: sub get_course_sessions {
1249: my ($cnum,$cdom,$lastactivity) = @_;
1250: my %servers = &internet_dom_servers($cdom);
1251: my %returnhash;
1252: foreach my $server (sort(keys(%servers))) {
1253: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1254: my @pairs=split(/\&/,$rep);
1255: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1256: foreach my $item (@pairs) {
1257: my ($key,$value)=split(/=/,$item,2);
1258: $key = &unescape($key);
1259: next if ($key =~ /^error: 2 /);
1260: if (exists($returnhash{$key})) {
1261: next if ($value < $returnhash{$key});
1262: }
1263: $returnhash{$key}=$value;
1264: }
1265: }
1266: }
1267: return %returnhash;
1268: }
1269:
1.202 matthew 1270: # --------------------------------------------- Try to change a user's password
1271:
1272: sub changepass {
1.799 raeburn 1273: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1274: $currentpass = &escape($currentpass);
1275: $newpass = &escape($newpass);
1.1030 raeburn 1276: my $lonhost = $perlvar{'lonHostID'};
1277: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1278: $server);
1279: if (! $answer) {
1280: &logthis("No reply on password change request to $server ".
1281: "by $uname in domain $udom.");
1282: } elsif ($answer =~ "^ok") {
1283: &logthis("$uname in $udom successfully changed their password ".
1284: "on $server.");
1285: } elsif ($answer =~ "^pwchange_failure") {
1286: &logthis("$uname in $udom was unable to change their password ".
1287: "on $server. The action was blocked by either lcpasswd ".
1288: "or pwchange");
1289: } elsif ($answer =~ "^non_authorized") {
1290: &logthis("$uname in $udom did not get their password correct when ".
1291: "attempting to change it on $server.");
1292: } elsif ($answer =~ "^auth_mode_error") {
1293: &logthis("$uname in $udom attempted to change their password despite ".
1294: "not being locally or internally authenticated on $server.");
1295: } elsif ($answer =~ "^unknown_user") {
1296: &logthis("$uname in $udom attempted to change their password ".
1297: "on $server but were unable to because $server is not ".
1298: "their home server.");
1299: } elsif ($answer =~ "^refused") {
1300: &logthis("$server refused to change $uname in $udom password because ".
1301: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1302: } elsif ($answer =~ "invalid_client") {
1303: &logthis("$server refused to change $uname in $udom password because ".
1304: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1305: } elsif ($answer =~ "^prioruse") {
1306: &logthis("$server refused to change $uname in $udom password because ".
1307: "the password had been used before");
1.202 matthew 1308: }
1309: return $answer;
1.1 albertel 1310: }
1311:
1.169 harris41 1312: # ----------------------- Try to determine user's current authentication scheme
1313:
1314: sub queryauthenticate {
1315: my ($uname,$udom)=@_;
1.456 albertel 1316: my $uhome=&homeserver($uname,$udom);
1317: if (!$uhome) {
1318: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1319: return 'no_host';
1320: }
1321: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1322: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1323: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1324: }
1.456 albertel 1325: return $answer;
1.169 harris41 1326: }
1327:
1.1 albertel 1328: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1329:
1.1 albertel 1330: sub authenticate {
1.1073 raeburn 1331: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1332: $upass=&escape($upass);
1333: $uname= &LONCAPA::clean_username($uname);
1.836 www 1334: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1335: my $newhome;
1.836 www 1336: if ((!$uhome) || ($uhome eq 'no_host')) {
1337: # Maybe the machine was offline and only re-appeared again recently?
1338: &reconlonc();
1339: # One more
1.952 raeburn 1340: $uhome=&homeserver($uname,$udom,1);
1341: if (($uhome eq 'no_host') && $checkdefauth) {
1342: if (defined(&domain($udom,'primary'))) {
1343: $newhome=&domain($udom,'primary');
1344: }
1345: if ($newhome ne '') {
1346: $uhome = $newhome;
1347: }
1348: }
1.836 www 1349: if ((!$uhome) || ($uhome eq 'no_host')) {
1350: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1351: return 'no_host';
1352: }
1.1 albertel 1353: }
1.1073 raeburn 1354: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1355: if ($answer eq 'authorized') {
1.952 raeburn 1356: if ($newhome) {
1357: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1358: return 'no_account_on_host';
1359: } else {
1360: &logthis("User $uname at $udom authorized by $uhome");
1361: return $uhome;
1362: }
1.471 albertel 1363: }
1364: if ($answer eq 'non_authorized') {
1365: &logthis("User $uname at $udom rejected by $uhome");
1366: return 'no_host';
1.9 www 1367: }
1.471 albertel 1368: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1369: return 'no_host';
1370: }
1371:
1.1073 raeburn 1372: sub can_host_session {
1.1074 raeburn 1373: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1374: my $canhost = 1;
1.1074 raeburn 1375: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1376: if (ref($remotesessions) eq 'HASH') {
1377: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1378: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1379: $canhost = 0;
1380: } else {
1381: $canhost = 1;
1382: }
1383: }
1384: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1385: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1386: $canhost = 1;
1387: } else {
1388: $canhost = 0;
1389: }
1390: }
1391: if ($canhost) {
1392: if ($remotesessions->{'version'} ne '') {
1393: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1394: if ($reqmajor ne '' && $reqminor ne '') {
1395: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1396: my $major = $1;
1397: my $minor = $2;
1398: if (($major < $reqmajor ) ||
1399: (($major == $reqmajor) && ($minor < $reqminor))) {
1400: $canhost = 0;
1401: }
1402: } else {
1403: $canhost = 0;
1404: }
1405: }
1406: }
1407: }
1408: }
1409: if ($canhost) {
1410: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1411: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1412: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1413: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1414: if (($uint_dom ne '') &&
1415: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1416: $canhost = 0;
1417: } else {
1418: $canhost = 1;
1419: }
1420: }
1421: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1422: if (($uint_dom ne '') &&
1423: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1424: $canhost = 1;
1425: } else {
1426: $canhost = 0;
1427: }
1428: }
1429: }
1430: }
1431: return $canhost;
1432: }
1433:
1.1083 raeburn 1434: sub spare_can_host {
1435: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1436: my $canhost=1;
1.1279 raeburn 1437: my $try_server_hostname = &hostname($try_server);
1438: my $serverhomeID = &get_server_homeID($try_server_hostname);
1439: my $serverhomedom = &host_domain($serverhomeID);
1440: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1441: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1442: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1443: $canhost = 0;
1444: }
1445: }
1446: if (($canhost) && ($uint_dom)) {
1447: my @intdoms;
1448: my $internet_names = &get_internet_names($try_server);
1449: if (ref($internet_names) eq 'ARRAY') {
1450: @intdoms = @{$internet_names};
1451: }
1452: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1453: my $remoterev = &get_server_loncaparev(undef,$try_server);
1454: $canhost = &can_host_session($udom,$try_server,$remoterev,
1455: $remotesessions,
1456: $defdomdefaults{'hostedsessions'});
1457: }
1.1083 raeburn 1458: }
1459: return $canhost;
1460: }
1461:
1.1123 raeburn 1462: sub this_host_spares {
1463: my ($dom) = @_;
1.1126 raeburn 1464: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1465: my @hosts = ¤t_machine_ids();
1466: foreach my $lonhost (@hosts) {
1467: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1468: $dom_in_use = $dom;
1469: $lonhost_in_use = $lonhost;
1.1123 raeburn 1470: last;
1471: }
1472: }
1.1126 raeburn 1473: if ($dom_in_use ne '') {
1474: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1475: }
1476: if (ref($result) ne 'HASH') {
1477: $lonhost_in_use = $perlvar{'lonHostID'};
1478: $dom_in_use = &host_domain($lonhost_in_use);
1479: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1480: if (ref($result) ne 'HASH') {
1481: $result = \%spareid;
1482: }
1483: }
1484: return $result;
1485: }
1486:
1487: sub spares_for_offload {
1488: my ($dom_in_use,$lonhost_in_use) = @_;
1489: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1490: if (defined($cached)) {
1491: return $result;
1492: } else {
1.1126 raeburn 1493: my $cachetime = 60*60*24;
1494: my %domconfig =
1495: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1496: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1497: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1498: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1499: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1500: }
1501: }
1502: }
1503: }
1.1126 raeburn 1504: return;
1.1123 raeburn 1505: }
1506:
1.1129 raeburn 1507: sub get_lonbalancer_config {
1508: my ($servers) = @_;
1509: my ($currbalancer,$currtargets);
1510: if (ref($servers) eq 'HASH') {
1511: foreach my $server (keys(%{$servers})) {
1512: my %what = (
1513: spareid => 1,
1514: perlvar => 1,
1515: );
1516: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1517: if ($result eq 'ok') {
1518: if (ref($returnhash) eq 'HASH') {
1519: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1520: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1521: $currbalancer = $server;
1522: $currtargets = {};
1523: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1524: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1525: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1526: }
1527: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1528: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1529: }
1530: }
1531: last;
1532: }
1533: }
1534: }
1535: }
1536: }
1537: }
1538: return ($currbalancer,$currtargets);
1539: }
1540:
1541: sub check_loadbalancing {
1.1331 raeburn 1542: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1543: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1544: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1545: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1546: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1547: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1548: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1549: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1550: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1551: my $domneedscache;
1.1129 raeburn 1552: my $cachetime = 60*60*24;
1553:
1554: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1555: $dom_in_use = $udom;
1556: $homeintdom = 1;
1557: } else {
1558: $dom_in_use = $serverhomedom;
1559: }
1560: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1561: unless (defined($cached)) {
1562: my %domconfig =
1563: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1564: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1565: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1566: } else {
1567: $domneedscache = $dom_in_use;
1.1129 raeburn 1568: }
1569: }
1570: if (ref($result) eq 'HASH') {
1.1391 raeburn 1571: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1572: &check_balancer_result($result,@hosts);
1.1129 raeburn 1573: if ($is_balancer) {
1574: if (ref($currrules) eq 'HASH') {
1575: if ($homeintdom) {
1576: if ($uname ne '') {
1577: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1578: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1579: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1580: $rule_in_effect = $currrules->{'_LC_author'};
1581: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1582: $rule_in_effect = $currrules->{'_LC_adv'}
1583: }
1584: }
1585: if ($rule_in_effect eq '') {
1586: my %userenv = &userenvironment($udom,$uname,'inststatus');
1587: if ($userenv{'inststatus'} ne '') {
1588: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1589: my ($othertitle,$usertypes,$types) =
1590: &Apache::loncommon::sorted_inst_types($udom);
1591: if (ref($types) eq 'ARRAY') {
1592: foreach my $type (@{$types}) {
1593: if (grep(/^\Q$type\E$/,@statuses)) {
1594: if (exists($currrules->{$type})) {
1595: $rule_in_effect = $currrules->{$type};
1596: }
1597: }
1598: }
1599: }
1600: } else {
1601: if (exists($currrules->{'default'})) {
1602: $rule_in_effect = $currrules->{'default'};
1603: }
1604: }
1605: }
1606: } else {
1607: if (exists($currrules->{'default'})) {
1608: $rule_in_effect = $currrules->{'default'};
1609: }
1610: }
1611: } else {
1612: if ($currrules->{'_LC_external'} ne '') {
1613: $rule_in_effect = $currrules->{'_LC_external'};
1614: }
1615: }
1616: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1617: $uname,$udom);
1618: }
1619: }
1620: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1621: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1622: unless (defined($cached)) {
1623: my %domconfig =
1624: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1625: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1626: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1627: } else {
1628: $domneedscache = $serverhomedom;
1.1129 raeburn 1629: }
1630: }
1631: if (ref($result) eq 'HASH') {
1.1391 raeburn 1632: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1633: &check_balancer_result($result,@hosts);
1634: if ($is_balancer) {
1.1129 raeburn 1635: if (ref($currrules) eq 'HASH') {
1636: if ($currrules->{'_LC_internetdom'} ne '') {
1637: $rule_in_effect = $currrules->{'_LC_internetdom'};
1638: }
1639: }
1640: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1641: $uname,$udom);
1642: }
1643: } else {
1644: if ($perlvar{'lonBalancer'} eq 'yes') {
1645: $is_balancer = 1;
1646: $offloadto = &this_host_spares($dom_in_use);
1647: }
1.1307 raeburn 1648: unless (defined($cached)) {
1649: $domneedscache = $serverhomedom;
1650: }
1.1129 raeburn 1651: }
1652: } else {
1653: if ($perlvar{'lonBalancer'} eq 'yes') {
1654: $is_balancer = 1;
1655: $offloadto = &this_host_spares($dom_in_use);
1656: }
1.1307 raeburn 1657: unless (defined($cached)) {
1658: $domneedscache = $serverhomedom;
1659: }
1660: }
1661: if ($domneedscache) {
1662: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1663: }
1.1430 raeburn 1664: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1665: my $lowest_load = 30000;
1666: if (ref($offloadto) eq 'HASH') {
1667: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1668: foreach my $try_server (@{$offloadto->{'primary'}}) {
1669: ($otherserver,$lowest_load) =
1670: &compare_server_load($try_server,$otherserver,$lowest_load);
1671: }
1.1129 raeburn 1672: }
1.1176 raeburn 1673: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1674:
1.1176 raeburn 1675: if (!$found_server) {
1676: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1677: foreach my $try_server (@{$offloadto->{'default'}}) {
1678: ($otherserver,$lowest_load) =
1679: &compare_server_load($try_server,$otherserver,$lowest_load);
1680: }
1681: }
1682: }
1683: } elsif (ref($offloadto) eq 'ARRAY') {
1684: if (@{$offloadto} == 1) {
1685: $otherserver = $offloadto->[0];
1686: } elsif (@{$offloadto} > 1) {
1687: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1688: ($otherserver,$lowest_load) =
1689: &compare_server_load($try_server,$otherserver,$lowest_load);
1690: }
1691: }
1692: }
1.1331 raeburn 1693: unless ($caller eq 'login') {
1694: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1695: $is_balancer = 0;
1696: if ($uname ne '' && $udom ne '') {
1697: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1698: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1699: 'user.loadbalcheck.time' => time});
1700: }
1.1176 raeburn 1701: }
1.1129 raeburn 1702: }
1703: }
1.1430 raeburn 1704: }
1705: if (($is_balancer) && (!$homeintdom)) {
1706: undef($setcookie);
1.1129 raeburn 1707: }
1.1391 raeburn 1708: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1709: }
1710:
1.1191 raeburn 1711: sub check_balancer_result {
1712: my ($result,@hosts) = @_;
1.1391 raeburn 1713: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1714: if (ref($result) eq 'HASH') {
1715: if ($result->{'lonhost'} ne '') {
1716: my $currbalancer = $result->{'lonhost'};
1717: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1718: $is_balancer = 1;
1719: $currtargets = $result->{'targets'};
1720: $currrules = $result->{'rules'};
1721: }
1.1391 raeburn 1722: $dom_balancers = $currbalancer;
1.1191 raeburn 1723: } else {
1.1391 raeburn 1724: if (keys(%{$result})) {
1725: foreach my $key (keys(%{$result})) {
1726: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1727: (ref($result->{$key}) eq 'HASH')) {
1728: $is_balancer = 1;
1729: $currrules = $result->{$key}{'rules'};
1730: $currtargets = $result->{$key}{'targets'};
1731: $setcookie = $result->{$key}{'cookie'};
1732: last;
1733: }
1.1191 raeburn 1734: }
1.1391 raeburn 1735: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1736: }
1737: }
1738: }
1.1391 raeburn 1739: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1740: }
1741:
1.1129 raeburn 1742: sub get_loadbalancer_targets {
1743: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1744: my $offloadto;
1.1175 raeburn 1745: if ($rule_in_effect eq 'none') {
1746: return [$perlvar{'lonHostID'}];
1747: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1748: $offloadto = $currtargets;
1749: } else {
1750: if ($rule_in_effect eq 'homeserver') {
1751: my $homeserver = &homeserver($uname,$udom);
1752: if ($homeserver ne 'no_host') {
1753: $offloadto = [$homeserver];
1754: }
1755: } elsif ($rule_in_effect eq 'externalbalancer') {
1756: my %domconfig =
1757: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1758: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1759: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1760: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1761: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1762: }
1763: }
1764: } else {
1.1178 raeburn 1765: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1766: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1767: if (&hostname($remotebalancer) ne '') {
1768: $offloadto = [$remotebalancer];
1769: }
1770: }
1771: } elsif (&hostname($rule_in_effect) ne '') {
1772: $offloadto = [$rule_in_effect];
1773: }
1774: }
1775: return $offloadto;
1776: }
1777:
1.1127 raeburn 1778: sub internet_dom_servers {
1779: my ($dom) = @_;
1780: my (%uniqservers,%servers);
1781: my $primaryserver = &hostname(&domain($dom,'primary'));
1782: my @machinedoms = &machine_domains($primaryserver);
1783: foreach my $mdom (@machinedoms) {
1784: my %currservers = %servers;
1785: my %server = &get_servers($mdom);
1786: %servers = (%currservers,%server);
1787: }
1788: my %by_hostname;
1789: foreach my $id (keys(%servers)) {
1790: push(@{$by_hostname{$servers{$id}}},$id);
1791: }
1792: foreach my $hostname (sort(keys(%by_hostname))) {
1793: if (@{$by_hostname{$hostname}} > 1) {
1794: my $match = 0;
1795: foreach my $id (@{$by_hostname{$hostname}}) {
1796: if (&host_domain($id) eq $dom) {
1797: $uniqservers{$id} = $hostname;
1798: $match = 1;
1799: }
1800: }
1801: unless ($match) {
1802: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1803: }
1804: } else {
1805: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1806: }
1807: }
1808: return %uniqservers;
1809: }
1810:
1.1347 raeburn 1811: sub trusted_domains {
1812: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1813: my ($trusted,$untrusted);
1.1347 raeburn 1814: if (&domain($calldom) eq '') {
1.1349 raeburn 1815: return ($trusted,$untrusted);
1.1347 raeburn 1816: }
1.1395 raeburn 1817: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1818: return ($trusted,$untrusted);
1.1347 raeburn 1819: }
1820: my $callprimary = &domain($calldom,'primary');
1821: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1822: if ($intcalldom eq '') {
1.1349 raeburn 1823: return ($trusted,$untrusted);
1.1347 raeburn 1824: }
1825:
1826: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1827: unless (defined($cached)) {
1828: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1829: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1830: $trustconfig = $domconfig{'trust'};
1831: }
1832: if (ref($trustconfig)) {
1833: my (%possexc,%possinc,@allexc,@allinc);
1834: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1835: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1836: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1837: }
1838: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1839: $possinc{$intcalldom} = 1;
1.1347 raeburn 1840: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1841: }
1842: }
1843: if (keys(%possexc)) {
1844: if (keys(%possinc)) {
1845: foreach my $key (sort(keys(%possexc))) {
1846: next if ($key eq $intcalldom);
1847: unless ($possinc{$key}) {
1848: push(@allexc,$key);
1849: }
1850: }
1851: } else {
1852: @allexc = sort(keys(%possexc));
1853: }
1854: }
1855: if (keys(%possinc)) {
1856: $possinc{$intcalldom} = 1;
1857: @allinc = sort(keys(%possinc));
1858: }
1859: if ((@allexc > 0) || (@allinc > 0)) {
1860: my %doms_by_intdom;
1861: my %allintdoms = &all_host_intdom();
1862: my %alldoms = &all_host_domain();
1863: foreach my $key (%allintdoms) {
1864: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1865: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1866: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1867: }
1868: } else {
1869: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1870: }
1871: }
1872: foreach my $exc (@allexc) {
1873: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1874: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1875: }
1876: }
1877: foreach my $inc (@allinc) {
1878: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1879: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1880: }
1881: }
1882: }
1883: }
1.1349 raeburn 1884: return ($trusted,$untrusted);
1.1347 raeburn 1885: }
1886:
1887: sub will_trust {
1888: my ($cmdtype,$domain,$possdom) = @_;
1889: return 1 if ($domain eq $possdom);
1890: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1891: my $willtrust;
1892: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1893: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1894: $willtrust = 1;
1895: }
1896: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1897: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1898: $willtrust = 1;
1899: }
1900: } else {
1901: $willtrust = 1;
1902: }
1903: return $willtrust;
1904: }
1905:
1.1 albertel 1906: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1907:
1.599 albertel 1908: my %homecache;
1.1 albertel 1909: sub homeserver {
1.230 stredwic 1910: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1911: my $index="$uname:$udom";
1.426 albertel 1912:
1.599 albertel 1913: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1914:
1915: my %servers = &get_servers($udom,'library');
1916: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1917: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1918: exists($badServerCache{$tryserver}));
1.841 albertel 1919:
1920: my $answer=reply("home:$udom:$uname",$tryserver);
1921: if ($answer eq 'found') {
1922: delete($badServerCache{$tryserver});
1923: return $homecache{$index}=$tryserver;
1924: } elsif ($answer eq 'no_host') {
1925: $badServerCache{$tryserver}=1;
1926: }
1.1 albertel 1927: }
1928: return 'no_host';
1.70 www 1929: }
1930:
1.1300 raeburn 1931: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1932:
1933: sub idget {
1.1300 raeburn 1934: my ($udom,$idsref,$namespace)=@_;
1.70 www 1935: my %returnhash=();
1.1300 raeburn 1936: my @ids=();
1937: if (ref($idsref) eq 'ARRAY') {
1938: @ids = @{$idsref};
1939: } else {
1940: return %returnhash;
1941: }
1942: if ($namespace eq '') {
1943: $namespace = 'ids';
1944: }
1.70 www 1945:
1.841 albertel 1946: my %servers = &get_servers($udom,'library');
1947: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1948: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1949: if ($namespace eq 'ids') {
1950: $idlist=~tr/A-Z/a-z/;
1951: }
1952: my $reply;
1953: if ($namespace eq 'ids') {
1954: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1955: } else {
1956: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1957: }
1.841 albertel 1958: my @answer=();
1959: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1960: @answer=split(/\&/,$reply);
1961: } ;
1962: my $i;
1963: for ($i=0;$i<=$#ids;$i++) {
1964: if ($answer[$i]) {
1.1299 raeburn 1965: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1966: }
1.841 albertel 1967: }
1.1300 raeburn 1968: }
1.70 www 1969: return %returnhash;
1970: }
1971:
1972: # ------------------------------------- Find the IDs behind a list of usernames
1973:
1974: sub idrget {
1975: my ($udom,@unames)=@_;
1976: my %returnhash=();
1.800 albertel 1977: foreach my $uname (@unames) {
1978: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1979: }
1.70 www 1980: return %returnhash;
1981: }
1982:
1.1300 raeburn 1983: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1984:
1985: sub idput {
1.1300 raeburn 1986: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1987: my %servers=();
1.1300 raeburn 1988: my %ids=();
1989: my %byid = ();
1990: if (ref($idsref) eq 'HASH') {
1991: %ids=%{$idsref};
1992: }
1993: if ($namespace eq '') {
1994: $namespace = 'ids';
1995: }
1.800 albertel 1996: foreach my $uname (keys(%ids)) {
1997: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1998: if ($uhom eq '') {
1999: $uhom=&homeserver($uname,$udom);
2000: }
1.70 www 2001: if ($uhom ne 'no_host') {
1.800 albertel 2002: my $esc_unam=&escape($uname);
1.1300 raeburn 2003: if ($namespace eq 'ids') {
2004: my $id=&escape($ids{$uname});
2005: $id=~tr/A-Z/a-z/;
2006: my $esc_unam=&escape($uname);
2007: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2008: } else {
1.1300 raeburn 2009: my @currids = split(/,/,$ids{$uname});
2010: foreach my $id (@currids) {
2011: $byid{$uhom}{$id} .= $uname.',';
2012: }
2013: }
2014: }
2015: }
2016: if ($namespace eq 'clickers') {
2017: foreach my $server (keys(%byid)) {
2018: if (ref($byid{$server}) eq 'HASH') {
2019: foreach my $id (keys(%{$byid{$server}})) {
2020: $byid{$server} =~ s/,$//;
2021: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2022: }
1.70 www 2023: }
2024: }
1.191 harris41 2025: }
1.800 albertel 2026: foreach my $server (keys(%servers)) {
1.1300 raeburn 2027: $servers{$server} =~ s/\&$//;
2028: if ($namespace eq 'ids') {
2029: &critical('idput:'.$udom.':'.$servers{$server},$server);
2030: } else {
2031: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2032: }
1.191 harris41 2033: }
1.344 www 2034: }
2035:
1.1300 raeburn 2036: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2037:
2038: sub iddel {
1.1300 raeburn 2039: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2040: my %result=();
1.1300 raeburn 2041: my %ids=();
2042: my %byid = ();
2043: if (ref($idshashref) eq 'HASH') {
2044: %ids=%{$idshashref};
2045: } else {
1.1231 raeburn 2046: return %result;
2047: }
1.1300 raeburn 2048: if ($namespace eq '') {
2049: $namespace = 'ids';
2050: }
1.1231 raeburn 2051: my %servers=();
1.1300 raeburn 2052: while (my ($id,$unamestr) = each(%ids)) {
2053: if ($namespace eq 'ids') {
2054: my $uhom = $uhome;
2055: if ($uhom eq '') {
2056: $uhom=&homeserver($unamestr,$udom);
2057: }
2058: if ($uhom ne 'no_host') {
2059: $servers{$uhom}.='&'.&escape($id);
2060: }
2061: } else {
2062: my @curritems = split(/,/,$ids{$id});
2063: foreach my $uname (@curritems) {
2064: my $uhom = $uhome;
2065: if ($uhom eq '') {
2066: $uhom=&homeserver($uname,$udom);
2067: }
2068: if ($uhom ne 'no_host') {
2069: $byid{$uhom}{$id} .= $uname.',';
2070: }
2071: }
1.1231 raeburn 2072: }
1.1300 raeburn 2073: }
2074: if ($namespace eq 'clickers') {
2075: foreach my $server (keys(%byid)) {
2076: if (ref($byid{$server}) eq 'HASH') {
2077: foreach my $id (keys(%{$byid{$server}})) {
2078: $byid{$server}{$id} =~ s/,$//;
2079: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2080: }
1.1231 raeburn 2081: }
2082: }
2083: }
2084: foreach my $server (keys(%servers)) {
1.1300 raeburn 2085: $servers{$server} =~ s/\&$//;
2086: if ($namespace eq 'ids') {
2087: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2088: } elsif ($namespace eq 'clickers') {
2089: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2090: }
1.1231 raeburn 2091: }
2092: return %result;
2093: }
2094:
1.1300 raeburn 2095: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2096:
2097: sub updateclickers {
2098: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2099: my %clickers;
2100: if (ref($idshashref) eq 'HASH') {
2101: %clickers=%{$idshashref};
2102: } else {
2103: return;
2104: }
2105: my $items='';
2106: foreach my $item (keys(%clickers)) {
2107: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2108: }
2109: $items=~s/\&$//;
2110: my $request = "updateclickers:$udom:$action:$items";
2111: if ($critical) {
2112: return &critical($request,$uhome);
2113: } else {
2114: return &reply($request,$uhome);
2115: }
2116: }
2117:
1.1023 raeburn 2118: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2119: sub dump_dom {
1.1165 droeschl 2120: my ($namespace, $udom, $regexp) = @_;
2121:
2122: $udom ||= $env{'user.domain'};
2123:
2124: return () unless $udom;
2125:
2126: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2127: }
2128:
1.1023 raeburn 2129: # ------------------------------------------ get items from domain db files
1.806 raeburn 2130:
2131: sub get_dom {
1.860 raeburn 2132: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 2133: return if ($udom eq 'public');
1.806 raeburn 2134: my $items='';
2135: foreach my $item (@$storearr) {
2136: $items.=&escape($item).'&';
2137: }
2138: $items=~s/\&$//;
1.860 raeburn 2139: if (!$udom) {
2140: $udom=$env{'user.domain'};
1.1267 raeburn 2141: return if ($udom eq 'public');
1.860 raeburn 2142: if (defined(&domain($udom,'primary'))) {
2143: $uhome=&domain($udom,'primary');
2144: } else {
1.874 albertel 2145: undef($uhome);
1.860 raeburn 2146: }
2147: } else {
2148: if (!$uhome) {
2149: if (defined(&domain($udom,'primary'))) {
2150: $uhome=&domain($udom,'primary');
2151: }
2152: }
2153: }
2154: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2155: my $rep;
2156: if ($namespace =~ /^enc/) {
2157: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2158: } else {
2159: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2160: }
1.866 raeburn 2161: my %returnhash;
1.875 albertel 2162: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2163: return %returnhash;
2164: }
1.806 raeburn 2165: my @pairs=split(/\&/,$rep);
2166: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2167: return @pairs;
2168: }
2169: my $i=0;
2170: foreach my $item (@$storearr) {
2171: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2172: $i++;
2173: }
2174: return %returnhash;
2175: } else {
1.880 banghart 2176: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2177: }
2178: }
2179:
2180: # -------------------------------------------- put items in domain db files
2181:
2182: sub put_dom {
1.860 raeburn 2183: my ($namespace,$storehash,$udom,$uhome)=@_;
2184: if (!$udom) {
2185: $udom=$env{'user.domain'};
2186: if (defined(&domain($udom,'primary'))) {
2187: $uhome=&domain($udom,'primary');
2188: } else {
1.874 albertel 2189: undef($uhome);
1.860 raeburn 2190: }
2191: } else {
2192: if (!$uhome) {
2193: if (defined(&domain($udom,'primary'))) {
2194: $uhome=&domain($udom,'primary');
2195: }
2196: }
2197: }
2198: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2199: my $items='';
2200: foreach my $item (keys(%$storehash)) {
2201: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2202: }
2203: $items=~s/\&$//;
1.1344 raeburn 2204: if ($namespace =~ /^enc/) {
2205: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2206: } else {
2207: return &reply("putdom:$udom:$namespace:$items",$uhome);
2208: }
1.806 raeburn 2209: } else {
1.860 raeburn 2210: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2211: }
2212: }
2213:
1.1023 raeburn 2214: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2215: sub newput_dom {
1.1023 raeburn 2216: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2217: my $result;
2218: if (!$udom) {
2219: $udom=$env{'user.domain'};
2220: }
1.1023 raeburn 2221: if ($udom) {
2222: my $uname = &get_domainconfiguser($udom);
2223: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2224: }
2225: return $result;
2226: }
2227:
1.1023 raeburn 2228: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2229: sub del_dom {
1.1023 raeburn 2230: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2231: if (ref($storearr) eq 'ARRAY') {
2232: if (!$udom) {
2233: $udom=$env{'user.domain'};
2234: }
1.1023 raeburn 2235: if ($udom) {
2236: my $uname = &get_domainconfiguser($udom);
2237: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2238: }
2239: }
2240: }
2241:
1.1023 raeburn 2242: # ----------------------------------construct domainconfig user for a domain
2243: sub get_domainconfiguser {
2244: my ($udom) = @_;
2245: return $udom.'-domainconfig';
2246: }
2247:
1.837 raeburn 2248: sub retrieve_inst_usertypes {
2249: my ($udom) = @_;
2250: my (%returnhash,@order);
1.989 raeburn 2251: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2252: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2253: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2254: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2255: } else {
2256: if (defined(&domain($udom,'primary'))) {
2257: my $uhome=&domain($udom,'primary');
2258: my $rep=&reply("inst_usertypes:$udom",$uhome);
2259: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2260: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2261: return (\%returnhash,\@order);
2262: }
2263: my ($hashitems,$orderitems) = split(/:/,$rep);
2264: my @pairs=split(/\&/,$hashitems);
2265: foreach my $item (@pairs) {
2266: my ($key,$value)=split(/=/,$item,2);
2267: $key = &unescape($key);
2268: next if ($key =~ /^error: 2 /);
2269: $returnhash{$key}=&thaw_unescape($value);
2270: }
2271: my @esc_order = split(/\&/,$orderitems);
2272: foreach my $item (@esc_order) {
2273: push(@order,&unescape($item));
2274: }
2275: } else {
1.1256 raeburn 2276: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2277: }
1.1256 raeburn 2278: return (\%returnhash,\@order);
1.837 raeburn 2279: }
2280: }
2281:
1.868 raeburn 2282: sub is_domainimage {
2283: my ($url) = @_;
1.1306 raeburn 2284: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2285: if (&domain($1) ne '') {
2286: return '1';
2287: }
2288: }
2289: return;
2290: }
2291:
1.899 raeburn 2292: sub inst_directory_query {
2293: my ($srch) = @_;
2294: my $udom = $srch->{'srchdomain'};
2295: my %results;
2296: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2297: my $outcome;
1.899 raeburn 2298: if ($homeserver ne '') {
1.1357 raeburn 2299: unless ($homeserver eq $perlvar{'lonHostID'}) {
2300: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2301: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2302: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2303: if (($major eq '' && $minor eq '') || ($major < 2) ||
2304: (($major == 2) && ($minor < 12))) {
2305: return;
2306: }
2307: }
2308: }
1.904 albertel 2309: my $queryid=&reply("querysend:instdirsearch:".
2310: &escape($srch->{'srchby'}).':'.
2311: &escape($srch->{'srchterm'}).':'.
2312: &escape($srch->{'srchtype'}),$homeserver);
2313: my $host=&hostname($homeserver);
2314: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2315: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2316: return;
2317: }
2318: my $response = &get_query_reply($queryid);
2319: my $maxtries = 5;
2320: my $tries = 1;
2321: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2322: $response = &get_query_reply($queryid);
2323: $tries ++;
2324: }
2325:
2326: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2327: if ($response eq 'unavailable') {
2328: $outcome = $response;
2329: } else {
2330: $outcome = 'ok';
2331: my @matches = split(/\n/,$response);
2332: foreach my $match (@matches) {
2333: my ($key,$value) = split(/=/,$match);
2334: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2335: }
1.899 raeburn 2336: }
2337: }
2338: }
1.909 raeburn 2339: return ($outcome,%results);
1.899 raeburn 2340: }
2341:
2342: sub usersearch {
2343: my ($srch) = @_;
2344: my $dom = $srch->{'srchdomain'};
2345: my %results;
2346: my %libserv = &all_library();
2347: my $query = 'usersearch';
2348: foreach my $tryserver (keys(%libserv)) {
2349: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2350: unless ($tryserver eq $perlvar{'lonHostID'}) {
2351: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2352: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2353: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2354: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2355: (($major == 2) && ($minor < 12)));
2356: }
2357: }
1.899 raeburn 2358: my $host=&hostname($tryserver);
2359: my $queryid=
1.911 raeburn 2360: &reply("querysend:".&escape($query).':'.
2361: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2362: &escape($srch->{'srchtype'}).':'.
2363: &escape($srch->{'srchterm'}),$tryserver);
2364: if ($queryid !~/^\Q$host\E\_/) {
2365: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2366: next;
1.899 raeburn 2367: }
2368: my $reply = &get_query_reply($queryid);
2369: my $maxtries = 1;
2370: my $tries = 1;
2371: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2372: $reply = &get_query_reply($queryid);
2373: $tries ++;
2374: }
2375: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2376: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2377: } else {
1.911 raeburn 2378: my @matches;
2379: if ($reply =~ /\n/) {
2380: @matches = split(/\n/,$reply);
2381: } else {
2382: @matches = split(/\&/,$reply);
2383: }
1.899 raeburn 2384: foreach my $match (@matches) {
2385: my ($uname,$udom,%userhash);
1.911 raeburn 2386: foreach my $entry (split(/:/,$match)) {
2387: my ($key,$value) =
2388: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2389: $userhash{$key} = $value;
2390: if ($key eq 'username') {
2391: $uname = $value;
2392: } elsif ($key eq 'domain') {
2393: $udom = $value;
1.911 raeburn 2394: }
1.899 raeburn 2395: }
2396: $results{$uname.':'.$udom} = \%userhash;
2397: }
2398: }
2399: }
2400: }
2401: return %results;
2402: }
2403:
1.912 raeburn 2404: sub get_instuser {
2405: my ($udom,$uname,$id) = @_;
2406: my $homeserver = &domain($udom,'primary');
2407: my ($outcome,%results);
2408: if ($homeserver ne '') {
2409: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2410: &escape($id).':'.&escape($udom),$homeserver);
2411: my $host=&hostname($homeserver);
2412: if ($queryid !~/^\Q$host\E\_/) {
2413: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2414: return;
2415: }
2416: my $response = &get_query_reply($queryid);
2417: my $maxtries = 5;
2418: my $tries = 1;
2419: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2420: $response = &get_query_reply($queryid);
2421: $tries ++;
2422: }
2423: if (!&error($response) && $response ne 'refused') {
2424: if ($response eq 'unavailable') {
2425: $outcome = $response;
2426: } else {
2427: $outcome = 'ok';
2428: my @matches = split(/\n/,$response);
2429: foreach my $match (@matches) {
2430: my ($key,$value) = split(/=/,$match);
2431: $results{&unescape($key)} = &thaw_unescape($value);
2432: }
2433: }
2434: }
2435: }
2436: my %userinfo;
2437: if (ref($results{$uname}) eq 'HASH') {
2438: %userinfo = %{$results{$uname}};
2439: }
2440: return ($outcome,%userinfo);
2441: }
2442:
1.1290 raeburn 2443: sub get_multiple_instusers {
2444: my ($udom,$users,$caller) = @_;
2445: my ($outcome,$results);
2446: if (ref($users) eq 'HASH') {
2447: my $count = keys(%{$users});
2448: my $requested = &freeze_escape($users);
2449: my $homeserver = &domain($udom,'primary');
2450: if ($homeserver ne '') {
2451: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2452: my $host=&hostname($homeserver);
2453: if ($queryid !~/^\Q$host\E\_/) {
2454: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2455: ' for host: '.$homeserver.'in domain '.$udom);
2456: return ($outcome,$results);
2457: }
2458: my $response = &get_query_reply($queryid);
2459: my $maxtries = 5;
2460: if ($count > 100) {
2461: $maxtries = 1+int($count/20);
2462: }
2463: my $tries = 1;
2464: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2465: $response = &get_query_reply($queryid);
2466: $tries ++;
2467: }
2468: if ($response eq '') {
2469: $results = {};
2470: foreach my $key (keys(%{$users})) {
2471: my ($uname,$id);
2472: if ($caller eq 'id') {
2473: $id = $key;
2474: } else {
2475: $uname = $key;
2476: }
2477: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2478: $outcome = $resp;
1.1290 raeburn 2479: if ($resp eq 'ok') {
2480: %{$results} = (%{$results}, %info);
2481: } else {
2482: last;
2483: }
2484: }
2485: } elsif(!&error($response) && ($response ne 'refused')) {
2486: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2487: $outcome = $response;
2488: } else {
1.1291 raeburn 2489: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2490: if ($outcome eq 'ok') {
2491: $results = &thaw_unescape($userdata);
2492: }
2493: }
2494: }
2495: }
2496: }
2497: return ($outcome,$results);
2498: }
2499:
1.912 raeburn 2500: sub inst_rulecheck {
1.923 raeburn 2501: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2502: my %returnhash;
2503: if ($udom ne '') {
2504: if (ref($rules) eq 'ARRAY') {
2505: @{$rules} = map {&escape($_);} (@{$rules});
2506: my $rulestr = join(':',@{$rules});
2507: my $homeserver=&domain($udom,'primary');
2508: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2509: my $response;
2510: if ($item eq 'username') {
2511: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2512: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2513: $homeserver));
1.923 raeburn 2514: } elsif ($item eq 'id') {
2515: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2516: ':'.&escape($id).':'.$rulestr,
2517: $homeserver));
1.945 raeburn 2518: } elsif ($item eq 'selfcreate') {
2519: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2520: &escape($udom).':'.&escape($uname).
2521: ':'.$rulestr,$homeserver));
1.923 raeburn 2522: }
1.912 raeburn 2523: if ($response ne 'refused') {
2524: my @pairs=split(/\&/,$response);
2525: foreach my $item (@pairs) {
2526: my ($key,$value)=split(/=/,$item,2);
2527: $key = &unescape($key);
2528: next if ($key =~ /^error: 2 /);
2529: $returnhash{$key}=&thaw_unescape($value);
2530: }
2531: }
2532: }
2533: }
2534: }
2535: return %returnhash;
2536: }
2537:
2538: sub inst_userrules {
1.923 raeburn 2539: my ($udom,$check) = @_;
1.912 raeburn 2540: my (%ruleshash,@ruleorder);
2541: if ($udom ne '') {
2542: my $homeserver=&domain($udom,'primary');
2543: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2544: my $response;
2545: if ($check eq 'id') {
2546: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2547: $homeserver);
1.943 raeburn 2548: } elsif ($check eq 'email') {
2549: $response=&reply('instemailrules:'.&escape($udom),
2550: $homeserver);
1.923 raeburn 2551: } else {
2552: $response=&reply('instuserrules:'.&escape($udom),
2553: $homeserver);
2554: }
1.912 raeburn 2555: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2556: ($response ne 'unknown_cmd') &&
1.912 raeburn 2557: ($response ne 'no_such_host')) {
2558: my ($hashitems,$orderitems) = split(/:/,$response);
2559: my @pairs=split(/\&/,$hashitems);
2560: foreach my $item (@pairs) {
2561: my ($key,$value)=split(/=/,$item,2);
2562: $key = &unescape($key);
2563: next if ($key =~ /^error: 2 /);
2564: $ruleshash{$key}=&thaw_unescape($value);
2565: }
2566: my @esc_order = split(/\&/,$orderitems);
2567: foreach my $item (@esc_order) {
2568: push(@ruleorder,&unescape($item));
2569: }
2570: }
2571: }
2572: }
2573: return (\%ruleshash,\@ruleorder);
2574: }
2575:
1.976 raeburn 2576: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2577:
2578: sub get_domain_defaults {
1.1240 raeburn 2579: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2580: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2581: my $cachetime = 60*60*24;
1.1240 raeburn 2582: unless ($ignore_cache) {
2583: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2584: if (defined($cached)) {
2585: if (ref($result) eq 'HASH') {
2586: return %{$result};
2587: }
1.943 raeburn 2588: }
2589: }
2590: my %domdefaults;
2591: my %domconfig =
1.989 raeburn 2592: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2593: 'requestcourses','inststatus',
1.1183 raeburn 2594: 'coursedefaults','usersessions',
1.1258 raeburn 2595: 'requestauthor','selfenrollment',
1.1320 raeburn 2596: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2597: 'trust','helpsettings'],$domain);
1.1305 raeburn 2598: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2599: if (ref($domconfig{'defaults'}) eq 'HASH') {
2600: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2601: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2602: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2603: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2604: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2605: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2606: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2607: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2608: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2609: } else {
2610: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2611: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2612: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2613: }
1.976 raeburn 2614: if (ref($domconfig{'quotas'}) eq 'HASH') {
2615: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2616: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2617: } else {
2618: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2619: }
1.1177 raeburn 2620: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2621: foreach my $item (@usertools) {
2622: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2623: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2624: }
2625: }
1.1229 raeburn 2626: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2627: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2628: }
1.976 raeburn 2629: }
1.985 raeburn 2630: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2631: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2632: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2633: }
2634: }
1.1183 raeburn 2635: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2636: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2637: }
1.989 raeburn 2638: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2639: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2640: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2641: }
2642: }
1.1047 raeburn 2643: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2644: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2645: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2646: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2647: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2648: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2649: }
1.1254 raeburn 2650: foreach my $type (@coursetypes) {
2651: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2652: unless ($type eq 'community') {
2653: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2654: }
2655: }
2656: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2657: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2658: }
1.1277 raeburn 2659: if ($domdefaults{'postsubmit'} eq 'on') {
2660: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2661: $domdefaults{$type.'postsubtimeout'} =
2662: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2663: }
2664: }
1.1230 raeburn 2665: }
1.1286 raeburn 2666: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2667: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2668: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2669: if (@clonecodes) {
2670: $domdefaults{'canclone'} = join('+',@clonecodes);
2671: }
2672: }
2673: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2674: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2675: }
1.1356 raeburn 2676: if ($domconfig{'coursedefaults'}{'texengine'}) {
2677: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2678: }
1.1047 raeburn 2679: }
1.1073 raeburn 2680: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2681: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2682: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2683: }
2684: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2685: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2686: }
1.1279 raeburn 2687: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2688: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2689: }
1.1073 raeburn 2690: }
1.1254 raeburn 2691: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2692: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2693: my @settings = ('types','registered','enroll_dates','access_dates','section',
2694: 'approval','limit');
2695: foreach my $type (@coursetypes) {
2696: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2697: my @mgrdc = ();
2698: foreach my $item (@settings) {
2699: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2700: push(@mgrdc,$item);
2701: }
2702: }
2703: if (@mgrdc) {
2704: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2705: }
2706: }
2707: }
2708: }
2709: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2710: foreach my $type (@coursetypes) {
2711: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2712: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2713: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2714: }
2715: }
2716: }
2717: }
2718: }
1.1258 raeburn 2719: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2720: $domdefaults{'catauth'} = 'std';
2721: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2722: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2723: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2724: }
2725: if ($domconfig{'coursecategories'}{'unauth'}) {
2726: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2727: }
2728: }
1.1315 raeburn 2729: if (ref($domconfig{'ssl'}) eq 'HASH') {
2730: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2731: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2732: }
1.1338 raeburn 2733: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2734: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2735: }
2736: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2737: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2738: }
2739: }
1.1320 raeburn 2740: if (ref($domconfig{'trust'}) eq 'HASH') {
2741: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2742: foreach my $prefix (@prefixes) {
2743: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2744: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2745: }
2746: }
2747: }
1.1314 raeburn 2748: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2749: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2750: }
1.1332 raeburn 2751: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2752: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2753: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2754: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2755: }
2756: }
1.1219 raeburn 2757: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2758: return %domdefaults;
2759: }
2760:
1.1412 raeburn 2761: sub get_dom_cats {
2762: my ($dom) = @_;
2763: return unless (&domain($dom));
2764: my ($cats,$cached)=&is_cached_new('cats',$dom);
2765: unless (defined($cached)) {
2766: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2767: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2768: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2769: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2770: } else {
2771: $cats = {};
2772: }
2773: } else {
2774: $cats = {};
2775: }
2776: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2777: }
1.1413 raeburn 2778: return $cats;
2779: }
2780:
2781: sub get_dom_instcats {
2782: my ($dom) = @_;
2783: return unless (&domain($dom));
2784: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2785: unless (defined($cached)) {
2786: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2787: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2788: if ($totcodes > 0) {
2789: my $caller = 'global';
2790: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2791: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2792: $instcats = {
2793: codes => \%codes,
2794: codetitles => \@codetitles,
2795: cat_titles => \%cat_titles,
2796: cat_order => \%cat_order,
2797: };
2798: &do_cache_new('instcats',$dom,$instcats,3600);
2799: }
2800: }
2801: }
2802: return $instcats;
2803: }
2804:
2805: sub retrieve_instcodes {
2806: my ($coursecodes,$dom) = @_;
2807: my $totcodes;
2808: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2809: foreach my $course (keys(%courses)) {
2810: if (ref($courses{$course}) eq 'HASH') {
2811: if ($courses{$course}{'inst_code'} ne '') {
2812: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2813: $totcodes ++;
2814: }
2815: }
2816: }
2817: return $totcodes;
1.1412 raeburn 2818: }
2819:
1.1311 raeburn 2820: sub course_portal_url {
2821: my ($cnum,$cdom) = @_;
2822: my $chome = &homeserver($cnum,$cdom);
2823: my $hostname = &hostname($chome);
2824: my $protocol = $protocol{$chome};
2825: $protocol = 'http' if ($protocol ne 'https');
2826: my %domdefaults = &get_domain_defaults($cdom);
2827: my $firsturl;
2828: if ($domdefaults{'portal_def'}) {
2829: $firsturl = $domdefaults{'portal_def'};
2830: } else {
2831: $firsturl = $protocol.'://'.$hostname;
2832: }
2833: return $firsturl;
2834: }
2835:
1.1407 raeburn 2836: # --------------------------------------------- Get domain config for passwords
2837:
2838: sub get_passwdconf {
2839: my ($dom) = @_;
2840: my (%passwdconf,$gotconf,$lookup);
2841: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2842: if (defined($cached)) {
2843: if (ref($result) eq 'HASH') {
2844: %passwdconf = %{$result};
2845: $gotconf = 1;
2846: }
2847: }
2848: unless ($gotconf) {
2849: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2850: if (ref($domconfig{'passwords'}) eq 'HASH') {
2851: %passwdconf = %{$domconfig{'passwords'}};
2852: }
2853: my $cachetime = 24*60*60;
2854: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2855: }
2856: return %passwdconf;
2857: }
2858:
1.344 www 2859: # --------------------------------------------------- Assign a key to a student
2860:
2861: sub assign_access_key {
1.364 www 2862: #
2863: # a valid key looks like uname:udom#comments
2864: # comments are being appended
2865: #
1.498 www 2866: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2867: $kdom=
1.620 albertel 2868: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2869: $knum=
1.620 albertel 2870: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2871: $cdom=
1.620 albertel 2872: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2873: $cnum=
1.620 albertel 2874: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2875: $udom=$env{'user.name'} unless (defined($udom));
2876: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2877: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2878: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2879: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2880: # assigned to this person
2881: # - this should not happen,
1.345 www 2882: # unless something went wrong
2883: # the first time around
2884: # ready to assign
1.364 www 2885: $logentry=$1.'; '.$logentry;
1.496 www 2886: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2887: $kdom,$knum) eq 'ok') {
1.345 www 2888: # key now belongs to user
1.346 www 2889: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2890: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2891: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2892: return 'ok';
2893: } else {
2894: return
2895: 'error: Count not permanently assign key, will need to be re-entered later.';
2896: }
2897: } else {
2898: return 'error: Could not assign key, try again later.';
2899: }
1.364 www 2900: } elsif (!$existing{$ckey}) {
1.345 www 2901: # the key does not exist
2902: return 'error: The key does not exist';
2903: } else {
2904: # the key is somebody else's
2905: return 'error: The key is already in use';
2906: }
1.344 www 2907: }
2908:
1.364 www 2909: # ------------------------------------------ put an additional comment on a key
2910:
2911: sub comment_access_key {
2912: #
2913: # a valid key looks like uname:udom#comments
2914: # comments are being appended
2915: #
2916: my ($ckey,$cdom,$cnum,$logentry)=@_;
2917: $cdom=
1.620 albertel 2918: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2919: $cnum=
1.620 albertel 2920: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2921: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2922: if ($existing{$ckey}) {
2923: $existing{$ckey}.='; '.$logentry;
2924: # ready to assign
1.367 www 2925: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2926: $cdom,$cnum) eq 'ok') {
2927: return 'ok';
2928: } else {
2929: return 'error: Count not store comment.';
2930: }
2931: } else {
2932: # the key does not exist
2933: return 'error: The key does not exist';
2934: }
2935: }
2936:
1.344 www 2937: # ------------------------------------------------------ Generate a set of keys
2938:
2939: sub generate_access_keys {
1.364 www 2940: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2941: $cdom=
1.620 albertel 2942: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2943: $cnum=
1.620 albertel 2944: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2945: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2946: unless (($cdom) && ($cnum)) { return 0; }
2947: if ($number>10000) { return 0; }
2948: sleep(2); # make sure don't get same seed twice
2949: srand(time()^($$+($$<<15))); # from "Programming Perl"
2950: my $total=0;
2951: for (my $i=1;$i<=$number;$i++) {
2952: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2953: sprintf("%lx",int(100000*rand)).'-'.
2954: sprintf("%lx",int(100000*rand));
2955: $newkey=~s/1/g/g; # folks mix up 1 and l
2956: $newkey=~s/0/h/g; # and also 0 and O
2957: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2958: if ($existing{$newkey}) {
2959: $i--;
2960: } else {
1.364 www 2961: if (&put('accesskeys',
2962: { $newkey => '# generated '.localtime().
1.620 albertel 2963: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2964: '; '.$logentry },
2965: $cdom,$cnum) eq 'ok') {
1.344 www 2966: $total++;
2967: }
2968: }
2969: }
1.620 albertel 2970: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2971: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2972: return $total;
2973: }
2974:
2975: # ------------------------------------------------------- Validate an accesskey
2976:
2977: sub validate_access_key {
2978: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2979: $cdom=
1.620 albertel 2980: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2981: $cnum=
1.620 albertel 2982: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2983: $udom=$env{'user.domain'} unless (defined($udom));
2984: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2985: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2986: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2987: }
2988:
2989: # ------------------------------------- Find the section of student in a course
1.652 albertel 2990: sub devalidate_getsection_cache {
2991: my ($udom,$unam,$courseid)=@_;
2992: my $hashid="$udom:$unam:$courseid";
2993: &devalidate_cache_new('getsection',$hashid);
2994: }
1.298 matthew 2995:
1.815 albertel 2996: sub courseid_to_courseurl {
2997: my ($courseid) = @_;
2998: #already url style courseid
2999: return $courseid if ($courseid =~ m{^/});
3000:
3001: if (exists($env{'course.'.$courseid.'.num'})) {
3002: my $cnum = $env{'course.'.$courseid.'.num'};
3003: my $cdom = $env{'course.'.$courseid.'.domain'};
3004: return "/$cdom/$cnum";
3005: }
3006:
3007: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3008: if (exists($courseinfo{'num'})) {
3009: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3010: }
3011:
3012: return undef;
3013: }
3014:
1.298 matthew 3015: sub getsection {
3016: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3017: my $cachetime=1800;
1.551 albertel 3018:
3019: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3020: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3021: if (defined($cached)) { return $result; }
3022:
1.298 matthew 3023: my %Pending;
3024: my %Expired;
3025: #
3026: # Each role can either have not started yet (pending), be active,
3027: # or have expired.
3028: #
3029: # If there is an active role, we are done.
3030: #
3031: # If there is more than one role which has not started yet,
3032: # choose the one which will start sooner
3033: # If there is one role which has not started yet, return it.
3034: #
3035: # If there is more than one expired role, choose the one which ended last.
3036: # If there is a role which has expired, return it.
3037: #
1.815 albertel 3038: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3039: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3040: foreach my $key (keys(%roleshash)) {
1.479 albertel 3041: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3042: my $section=$1;
3043: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3044: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3045: my $now=time;
1.548 albertel 3046: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3047: $Expired{$end}=$section;
3048: next;
3049: }
1.548 albertel 3050: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3051: $Pending{$start}=$section;
3052: next;
3053: }
1.599 albertel 3054: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3055: }
3056: #
3057: # Presumedly there will be few matching roles from the above
3058: # loop and the sorting time will be negligible.
3059: if (scalar(keys(%Pending))) {
3060: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3061: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3062: }
3063: if (scalar(keys(%Expired))) {
3064: my @sorted = sort {$a <=> $b} keys(%Expired);
3065: my $time = pop(@sorted);
1.599 albertel 3066: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3067: }
1.599 albertel 3068: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3069: }
1.70 www 3070:
1.599 albertel 3071: sub save_cache {
3072: &purge_remembered();
1.722 albertel 3073: #&Apache::loncommon::validate_page();
1.620 albertel 3074: undef(%env);
1.780 albertel 3075: undef($env_loaded);
1.599 albertel 3076: }
1.452 albertel 3077:
1.599 albertel 3078: my $to_remember=-1;
3079: my %remembered;
3080: my %accessed;
3081: my $kicks=0;
3082: my $hits=0;
1.849 albertel 3083: sub make_key {
3084: my ($name,$id) = @_;
1.872 albertel 3085: if (length($id) > 65
3086: && length(&escape($id)) > 200) {
3087: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3088: }
1.849 albertel 3089: return &escape($name.':'.$id);
3090: }
3091:
1.599 albertel 3092: sub devalidate_cache_new {
3093: my ($name,$id,$debug) = @_;
3094: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3095: my $remembered_id=$name.':'.$id;
1.849 albertel 3096: $id=&make_key($name,$id);
1.599 albertel 3097: $memcache->delete($id);
1.1319 damieng 3098: delete($remembered{$remembered_id});
3099: delete($accessed{$remembered_id});
1.599 albertel 3100: }
3101:
3102: sub is_cached_new {
3103: my ($name,$id,$debug) = @_;
1.1319 damieng 3104: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3105: if (exists($remembered{$remembered_id})) {
3106: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3107: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3108: $hits++;
1.1319 damieng 3109: return ($remembered{$remembered_id},1);
1.599 albertel 3110: }
1.1319 damieng 3111: $id=&make_key($name,$id);
1.599 albertel 3112: my $value = $memcache->get($id);
3113: if (!(defined($value))) {
3114: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3115: return (undef,undef);
1.416 albertel 3116: }
1.599 albertel 3117: if ($value eq '__undef__') {
3118: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3119: $value=undef;
3120: }
1.1319 damieng 3121: &make_room($remembered_id,$value,$debug);
1.599 albertel 3122: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3123: return ($value,1);
3124: }
3125:
3126: sub do_cache_new {
3127: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3128: my $remembered_id=$name.':'.$id;
1.849 albertel 3129: $id=&make_key($name,$id);
1.599 albertel 3130: my $setvalue=$value;
3131: if (!defined($setvalue)) {
3132: $setvalue='__undef__';
3133: }
1.623 albertel 3134: if (!defined($time) ) {
3135: $time=600;
3136: }
1.599 albertel 3137: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3138: my $result = $memcache->set($id,$setvalue,$time);
3139: if (! $result) {
1.872 albertel 3140: &logthis("caching of id -> $id failed");
1.910 albertel 3141: $memcache->disconnect_all();
1.872 albertel 3142: }
1.600 albertel 3143: # need to make a copy of $value
1.1319 damieng 3144: &make_room($remembered_id,$value,$debug);
1.599 albertel 3145: return $value;
3146: }
3147:
3148: sub make_room {
1.1319 damieng 3149: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3150:
1.1319 damieng 3151: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3152: : $value;
1.599 albertel 3153: if ($to_remember<0) { return; }
1.1319 damieng 3154: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3155: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3156: my $to_kick;
3157: my $max_time=0;
3158: foreach my $other (keys(%accessed)) {
3159: if (&tv_interval($accessed{$other}) > $max_time) {
3160: $to_kick=$other;
3161: $max_time=&tv_interval($accessed{$other});
3162: }
3163: }
3164: delete($remembered{$to_kick});
3165: delete($accessed{$to_kick});
3166: $kicks++;
3167: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3168: return;
3169: }
3170:
1.599 albertel 3171: sub purge_remembered {
1.604 albertel 3172: #&logthis("Tossing ".scalar(keys(%remembered)));
3173: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3174: undef(%remembered);
3175: undef(%accessed);
1.428 albertel 3176: }
1.70 www 3177: # ------------------------------------- Read an entry from a user's environment
3178:
3179: sub userenvironment {
3180: my ($udom,$unam,@what)=@_;
1.976 raeburn 3181: my $items;
3182: foreach my $item (@what) {
3183: $items.=&escape($item).'&';
3184: }
3185: $items=~s/\&$//;
1.70 www 3186: my %returnhash=();
1.1009 raeburn 3187: my $uhome = &homeserver($unam,$udom);
3188: unless ($uhome eq 'no_host') {
3189: my @answer=split(/\&/,
3190: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3191: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3192: return %returnhash;
3193: }
1.1009 raeburn 3194: my $i;
3195: for ($i=0;$i<=$#what;$i++) {
3196: $returnhash{$what[$i]}=&unescape($answer[$i]);
3197: }
1.70 www 3198: }
3199: return %returnhash;
1.1 albertel 3200: }
3201:
1.617 albertel 3202: # ---------------------------------------------------------- Get a studentphoto
3203: sub studentphoto {
3204: my ($udom,$unam,$ext) = @_;
3205: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3206: if (defined($env{'request.course.id'})) {
1.708 raeburn 3207: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3208: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3209: return(&retrievestudentphoto($udom,$unam,$ext));
3210: } else {
3211: my ($result,$perm_reqd)=
1.707 albertel 3212: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3213: if ($result eq 'ok') {
3214: if (!($perm_reqd eq 'yes')) {
3215: return(&retrievestudentphoto($udom,$unam,$ext));
3216: }
3217: }
3218: }
3219: }
3220: } else {
3221: my ($result,$perm_reqd) =
1.707 albertel 3222: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3223: if ($result eq 'ok') {
3224: if (!($perm_reqd eq 'yes')) {
3225: return(&retrievestudentphoto($udom,$unam,$ext));
3226: }
3227: }
3228: }
3229: return '/adm/lonKaputt/lonlogo_broken.gif';
3230: }
3231:
3232: sub retrievestudentphoto {
3233: my ($udom,$unam,$ext,$type) = @_;
3234: my $home=&Apache::lonnet::homeserver($unam,$udom);
3235: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3236: if ($ret eq 'ok') {
3237: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3238: if ($type eq 'thumbnail') {
3239: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3240: }
3241: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3242: return $tokenurl;
3243: } else {
3244: if ($type eq 'thumbnail') {
3245: return '/adm/lonKaputt/genericstudent_tn.gif';
3246: } else {
3247: return '/adm/lonKaputt/lonlogo_broken.gif';
3248: }
1.617 albertel 3249: }
3250: }
3251:
1.263 www 3252: # -------------------------------------------------------------------- New chat
3253:
3254: sub chatsend {
1.724 raeburn 3255: my ($newentry,$anon,$group)=@_;
1.620 albertel 3256: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3257: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3258: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3259: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3260: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3261: &escape($newentry)).':'.$group,$chome);
1.292 www 3262: }
3263:
3264: # ------------------------------------------ Find current version of a resource
3265:
3266: sub getversion {
3267: my $fname=&clutter(shift);
1.1189 raeburn 3268: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3269: return ¤tversion(&filelocation('',$fname));
3270: }
3271:
3272: sub currentversion {
3273: my $fname=shift;
3274: my $author=$fname;
3275: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3276: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3277: my $home=&homeserver($uname,$udom);
1.292 www 3278: if ($home eq 'no_host') {
3279: return -1;
3280: }
1.1112 www 3281: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3282: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3283: return -1;
3284: }
1.1112 www 3285: return $answer;
1.263 www 3286: }
3287:
1.1111 www 3288: #
3289: # Return special version number of resource if set by override, empty otherwise
3290: #
3291: sub usedversion {
3292: my $fname=shift;
3293: unless ($fname) { $fname=$env{'request.uri'}; }
3294: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3295: if ($urlversion) { return $urlversion; }
3296: return '';
3297: }
3298:
1.1 albertel 3299: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3300:
1.1 albertel 3301: sub subscribe {
3302: my $fname=shift;
1.761 raeburn 3303: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3304: $fname=~s/[\n\r]//g;
1.1 albertel 3305: my $author=$fname;
3306: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3307: my ($udom,$uname)=split(/\//,$author);
3308: my $home=homeserver($uname,$udom);
1.335 albertel 3309: if ($home eq 'no_host') {
3310: return 'not_found';
1.1 albertel 3311: }
3312: my $answer=reply("sub:$fname",$home);
1.64 www 3313: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3314: $answer.=' by '.$home;
3315: }
1.1 albertel 3316: return $answer;
3317: }
3318:
1.8 www 3319: # -------------------------------------------------------------- Replicate file
3320:
3321: sub repcopy {
3322: my $filename=shift;
1.23 www 3323: $filename=~s/\/+/\//g;
1.1142 raeburn 3324: my $londocroot = $perlvar{'lonDocRoot'};
3325: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3326: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3327: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3328: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3329: return &repcopy_userfile($filename);
3330: }
1.532 albertel 3331: $filename=~s/[\n\r]//g;
1.8 www 3332: my $transname="$filename.in.transfer";
1.828 www 3333: # FIXME: this should flock
1.607 raeburn 3334: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3335: my $remoteurl=subscribe($filename);
1.64 www 3336: if ($remoteurl =~ /^con_lost by/) {
3337: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3338: return 'unavailable';
1.8 www 3339: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3340: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3341: return 'not_found';
1.64 www 3342: } elsif ($remoteurl =~ /^rejected by/) {
3343: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3344: return 'forbidden';
1.20 www 3345: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3346: return 'ok';
1.8 www 3347: } else {
1.290 www 3348: my $author=$filename;
3349: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3350: my ($udom,$uname)=split(/\//,$author);
3351: my $home=homeserver($uname,$udom);
3352: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3353: my @parts=split(/\//,$filename);
3354: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3355: if ($path ne "$londocroot/res") {
1.8 www 3356: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3357: return 'bad_request';
1.8 www 3358: }
3359: my $count;
3360: for ($count=5;$count<$#parts;$count++) {
3361: $path.="/$parts[$count]";
3362: if ((-e $path)!=1) {
3363: mkdir($path,0777);
3364: }
3365: }
3366: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3367: my $response;
3368: if ($remoteurl =~ m{/raw/}) {
3369: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3370: } else {
3371: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3372: }
1.8 www 3373: if ($response->is_error()) {
3374: unlink($transname);
3375: my $message=$response->status_line;
1.672 albertel 3376: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3377: ." LWP get: $message: $filename</font>");
1.607 raeburn 3378: return 'unavailable';
1.8 www 3379: } else {
1.16 www 3380: if ($remoteurl!~/\.meta$/) {
3381: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3382: my $mresponse;
3383: if ($remoteurl =~ m{/raw/}) {
3384: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3385: } else {
3386: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3387: }
1.16 www 3388: if ($mresponse->is_error()) {
3389: unlink($filename.'.meta');
3390: &logthis(
1.672 albertel 3391: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3392: }
3393: }
1.8 www 3394: rename($transname,$filename);
1.607 raeburn 3395: return 'ok';
1.8 www 3396: }
1.290 www 3397: }
1.8 www 3398: }
1.330 www 3399: }
3400:
1.1422 raeburn 3401: # ------------------------------------------------- Unsubscribe from a resource
3402:
3403: sub unsubscribe {
3404: my ($fname) = @_;
3405: my $answer;
3406: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3407: $fname=~s/[\n\r]//g;
3408: my $author=$fname;
3409: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3410: my ($udom,$uname)=split(/\//,$author);
3411: my $home=homeserver($uname,$udom);
3412: if ($home eq 'no_host') {
3413: $answer = 'no_host';
3414: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3415: $answer = 'home';
3416: } else {
3417: my $defdom = $perlvar{'lonDefDomain'};
3418: if (&will_trust('content',$defdom,$udom)) {
3419: $answer = reply("unsub:$fname",$home);
3420: } else {
3421: $answer = 'untrusted';
3422: }
3423: }
3424: return $answer;
3425: }
3426:
1.330 www 3427: # ------------------------------------------------ Get server side include body
3428: sub ssi_body {
1.381 albertel 3429: my ($filelink,%form)=@_;
1.606 matthew 3430: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3431: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3432: }
1.953 www 3433: my $output='';
3434: my $response;
1.980 raeburn 3435: if ($filelink=~/^https?\:/) {
1.954 raeburn 3436: ($output,$response)=&externalssi($filelink);
1.953 www 3437: } else {
1.1004 droeschl 3438: $filelink .= $filelink=~/\?/ ? '&' : '?';
3439: $filelink .= 'inhibitmenu=yes';
1.953 www 3440: ($output,$response)=&ssi($filelink,%form);
3441: }
1.778 albertel 3442: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3443: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3444: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3445: if (wantarray) {
3446: return ($output, $response);
3447: } else {
3448: return $output;
3449: }
1.8 www 3450: }
3451:
1.15 www 3452: # --------------------------------------------------------- Server Side Include
3453:
1.782 albertel 3454: sub absolute_url {
3455: my ($host_name) = @_;
3456: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3457: if ($host_name eq '') {
3458: $host_name = $ENV{'SERVER_NAME'};
3459: }
3460: return $protocol.$host_name;
3461: }
3462:
1.942 foxr 3463: #
3464: # Server side include.
3465: # Parameters:
3466: # fn Possibly encrypted resource name/id.
3467: # form Hash that describes how the rendering should be done
3468: # and other things.
1.944 foxr 3469: # Returns:
1.950 raeburn 3470: # Scalar context: The content of the response.
3471: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3472: #
1.15 www 3473: sub ssi {
3474:
1.944 foxr 3475: my ($fn,%form)=@_;
1.23 www 3476: my $request;
1.711 albertel 3477:
3478: $form{'no_update_last_known'}=1;
1.895 albertel 3479: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3480: if (%form) {
1.782 albertel 3481: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3482: $request->content(join('&',map {
3483: my $name = escape($_);
3484: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3485: ? join("&$name=", map {escape($_) } @{$form{$_}})
3486: : &escape($form{$_}) );
3487: } keys(%form)));
1.23 www 3488: } else {
1.782 albertel 3489: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3490: }
3491:
1.15 www 3492: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3493: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3494: my $islocal;
3495: if (($env{'request.course.id'}) &&
3496: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3497: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3498: ($form{'grade_symb'} ne '') &&
3499: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3500: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3501: $islocal = 1;
3502: }
1.1384 raeburn 3503: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385 raeburn 3504: '','','',$islocal);
1.1182 foxr 3505:
1.944 foxr 3506: if (wantarray) {
1.1345 raeburn 3507: return ($response->content, $response);
1.944 foxr 3508: } else {
1.1345 raeburn 3509: return $response->content;
1.942 foxr 3510: }
1.324 www 3511: }
3512:
3513: sub externalssi {
3514: my ($url)=@_;
3515: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3516: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3517: if (wantarray) {
3518: return ($response->content, $response);
3519: } else {
3520: return $response->content;
3521: }
1.15 www 3522: }
1.254 www 3523:
1.1354 raeburn 3524:
3525: # If the local copy of a replicated resource is outdated, trigger a
3526: # connection from the homeserver to flush the delayed queue. If no update
3527: # happens, remove local copies of outdated resource (and corresponding
3528: # metadata file).
3529:
1.1352 raeburn 3530: sub remove_stale_resfile {
3531: my ($url) = @_;
1.1354 raeburn 3532: my $removed;
1.1352 raeburn 3533: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3534: my $audom = $1;
3535: my $auname = $2;
1.1353 raeburn 3536: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3537: my $homeserver = &homeserver($auname,$audom);
3538: unless (($homeserver eq 'no_host') ||
3539: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3540: my $fname = &filelocation('',$url);
3541: if (-e $fname) {
3542: my $hostname = &hostname($homeserver);
3543: if ($hostname) {
1.1397 raeburn 3544: my $protocol = $protocol{$homeserver};
3545: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3546: my $uri = &declutter($url);
3547: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3548: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3549: if ($response->is_success()) {
3550: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3551: my $locmodtime = (stat($fname))[9];
3552: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3553: my $stale;
3554: my $answer = &reply('pong',$homeserver);
3555: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3556: sleep(0.2);
3557: $locmodtime = (stat($fname))[9];
3558: if ($locmodtime < $remmodtime) {
3559: my $posstransfer = $fname.'.in.transfer';
3560: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3561: $removed = 1;
3562: } else {
3563: $stale = 1;
3564: }
3565: } else {
3566: $removed = 1;
3567: }
3568: } else {
3569: $stale = 1;
3570: }
3571: if ($stale) {
1.1421 raeburn 3572: if (unlink($fname)) {
3573: if ($uri!~/\.meta$/) {
3574: if (-e $fname.'.meta') {
3575: unlink($fname.'.meta');
3576: }
3577: }
1.1422 raeburn 3578: my $unsubresult = &unsubscribe($fname);
3579: unless ($unsubresult eq 'ok') {
3580: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3581: }
1.1421 raeburn 3582: $removed = 1;
1.1354 raeburn 3583: }
1.1352 raeburn 3584: }
3585: }
3586: }
3587: }
3588: }
3589: }
3590: }
3591: }
1.1354 raeburn 3592: return $removed;
1.1352 raeburn 3593: }
3594:
1.492 albertel 3595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3596:
3597: sub allowuploaded {
3598: my ($srcurl,$url)=@_;
3599: $url=&clutter(&declutter($url));
3600: my $dir=$url;
3601: $dir=~s/\/[^\/]+$//;
3602: my %httpref=();
3603: my $httpurl=&hreflocation('',$url);
3604: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3605: &Apache::lonnet::appenv(\%httpref);
1.254 www 3606: }
1.477 raeburn 3607:
1.1193 raeburn 3608: #
3609: # Determine if the current user should be able to edit a particular resource,
3610: # when viewing in course context.
3611: # (a) When viewing resource used to determine if "Edit" item is included in
3612: # Functions.
3613: # (b) When displaying folder contents in course editor, used to determine if
3614: # "Edit" link will be displayed alongside resource.
3615: #
1.1196 raeburn 3616: # input: six args -- filename (decluttered), course number, course domain,
3617: # url, symb (if registered) and group (if this is a group
3618: # item -- e.g., bulletin board, group page etc.).
3619: # output: array of five scalars --
1.1193 raeburn 3620: # $cfile -- url for file editing if editable on current server
3621: # $home -- homeserver of resource (i.e., for author if published,
3622: # or course if uploaded.).
3623: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3624: # $forceedit -- 1 if icon/link should be to go to edit mode
3625: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3626: #
3627:
3628: sub can_edit_resource {
1.1194 raeburn 3629: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3630: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3631: #
3632: # For aboutme pages user can only edit his/her own.
3633: #
1.1199 raeburn 3634: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3635: my ($sdom,$sname) = ($1,$2);
3636: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3637: $home = $env{'user.home'};
3638: $cfile = $resurl;
3639: if ($env{'form.forceedit'}) {
3640: $forceview = 1;
3641: } else {
3642: $forceedit = 1;
3643: }
3644: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3645: } else {
3646: return;
3647: }
3648: }
3649:
3650: if ($env{'request.course.id'}) {
3651: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3652: if ($group ne '') {
3653: # if this is a group homepage or group bulletin board, check group privs
3654: my $allowed = 0;
1.1197 raeburn 3655: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3656: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3657: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3658: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3659: $allowed = 1;
3660: }
1.1197 raeburn 3661: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3662: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3663: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3664: $allowed = 1;
3665: }
3666: }
3667: if ($allowed) {
3668: $home=&homeserver($cnum,$cdom);
3669: if ($env{'form.forceedit'}) {
3670: $forceview = 1;
3671: } else {
3672: $forceedit = 1;
3673: }
3674: $cfile = $resurl;
3675: } else {
3676: return;
3677: }
3678: } else {
1.1208 raeburn 3679: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3680: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3681: return;
3682: }
3683: } elsif (!$crsedit) {
1.1194 raeburn 3684: #
3685: # No edit allowed where CC has switched to student role.
3686: #
3687: return;
3688: }
3689: }
3690: }
3691:
1.1193 raeburn 3692: if ($file ne '') {
3693: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3694: if (&is_course_upload($file,$cnum,$cdom)) {
3695: $uploaded = 1;
3696: $incourse = 1;
1.1193 raeburn 3697: if ($file =~/\.(htm|html|css|js|txt)$/) {
3698: $cfile = &hreflocation('',$file);
1.1201 raeburn 3699: if ($env{'form.forceedit'}) {
3700: $forceview = 1;
3701: } else {
3702: $forceedit = 1;
3703: }
1.1194 raeburn 3704: }
3705: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3706: $incourse = 1;
3707: if ($env{'form.forceedit'}) {
3708: $forceview = 1;
3709: } else {
3710: $forceedit = 1;
3711: }
3712: $cfile = $resurl;
3713: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3714: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3715: $incourse = 1;
3716: if ($env{'form.forceedit'}) {
3717: $forceview = 1;
3718: } else {
3719: $forceedit = 1;
3720: }
3721: $cfile = $resurl;
1.1199 raeburn 3722: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3723: $incourse = 1;
3724: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3725: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3726: $incourse = 1;
1.1199 raeburn 3727: if ($env{'form.forceedit'}) {
3728: $forceview = 1;
3729: } else {
3730: $forceedit = 1;
3731: }
3732: $cfile = $resurl;
1.1419 raeburn 3733: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3734: my ($map,$id,$res) = &decode_symb($symb);
3735: if ($map =~ /\.page$/) {
3736: $incourse = 1;
3737: if ($env{'form.forceedit'}) {
3738: $forceview = 1;
3739: $cfile = $map;
3740: } else {
3741: $forceedit = 1;
3742: $cfile = '/adm/wrapper'.$resurl;
3743: }
3744: }
1.1343 raeburn 3745: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3746: $incourse = 1;
3747: if ($env{'form.forceedit'}) {
3748: $forceview = 1;
3749: } else {
3750: $forceedit = 1;
3751: }
3752: $cfile = $resurl;
1.1208 raeburn 3753: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3754: $incourse = 1;
3755: if ($env{'form.forceedit'}) {
3756: $forceview = 1;
3757: } else {
3758: $forceedit = 1;
3759: }
3760: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3761: }
3762: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3763: my $template = '/res/lib/templates/simpleproblem.problem';
3764: if (&is_on_map($template)) {
3765: $incourse = 1;
3766: $forceview = 1;
3767: $cfile = $template;
1.1193 raeburn 3768: }
1.1199 raeburn 3769: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3770: $incourse = 1;
3771: if ($env{'form.forceedit'}) {
3772: $forceview = 1;
3773: } else {
3774: $forceedit = 1;
3775: }
3776: $cfile = $resurl;
1.1343 raeburn 3777: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3778: $incourse = 1;
3779: if ($env{'form.forceedit'}) {
3780: $forceview = 1;
3781: } else {
3782: $forceedit = 1;
3783: }
3784: $cfile = $resurl;
1.1199 raeburn 3785: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3786: $incourse = 1;
3787: $forceview = 1;
3788: if ($symb) {
3789: my ($map,$id,$res)=&decode_symb($symb);
3790: $env{'request.symb'} = $symb;
3791: $cfile = &clutter($res);
3792: } else {
3793: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3794: my $escfile = &unescape($cfile);
1.1343 raeburn 3795: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3796: $cfile = '/adm/wrapper'.$escfile;
3797: } else {
3798: $escfile =~ s{^http://}{};
3799: $cfile = &escape("/adm/wrapper/ext/$escfile");
3800: }
1.1199 raeburn 3801: }
1.1234 raeburn 3802: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3803: if ($env{'form.forceedit'}) {
3804: $forceview = 1;
3805: } else {
3806: $forceedit = 1;
3807: }
3808: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3809: }
3810: }
1.1194 raeburn 3811: if ($uploaded || $incourse) {
3812: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3813: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3814: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3815: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3816: # Check that the user has permission to edit this resource
3817: my $setpriv = 1;
3818: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3819: if (defined($cfudom)) {
3820: $home=&homeserver($cfuname,$cfudom);
3821: $cfile=$file;
3822: }
3823: }
1.1194 raeburn 3824: if (($cfile ne '') && (!$incourse || $uploaded) &&
3825: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3826: my @ids=¤t_machine_ids();
3827: unless (grep(/^\Q$home\E$/,@ids)) {
3828: $switchserver=1;
3829: }
3830: }
3831: }
1.1194 raeburn 3832: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3833: }
3834:
3835: sub is_course_upload {
3836: my ($file,$cnum,$cdom) = @_;
3837: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3838: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3839: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3840: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3841: return 1;
3842: }
3843: return;
3844: }
3845:
1.1194 raeburn 3846: sub in_course {
1.1195 raeburn 3847: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3848: if ($hideprivileged) {
3849: my $skipuser;
1.1219 raeburn 3850: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3851: my @possdoms = ($cdom);
3852: if ($coursehash{'checkforpriv'}) {
3853: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3854: }
3855: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3856: $skipuser = 1;
3857: if ($coursehash{'nothideprivileged'}) {
3858: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3859: my $user;
3860: if ($item =~ /:/) {
3861: $user = $item;
3862: } else {
3863: $user = join(':',split(/[\@]/,$item));
3864: }
3865: if ($user eq $uname.':'.$udom) {
3866: undef($skipuser);
3867: last;
3868: }
3869: }
3870: }
3871: if ($skipuser) {
3872: return 0;
3873: }
3874: }
3875: }
1.1194 raeburn 3876: $type ||= 'any';
3877: if (!defined($cdom) || !defined($cnum)) {
3878: my $cid = $env{'request.course.id'};
3879: $cdom = $env{'course.'.$cid.'.domain'};
3880: $cnum = $env{'course.'.$cid.'.num'};
3881: }
3882: my $typesref;
1.1195 raeburn 3883: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3884: $typesref = ['active','previous','future'];
3885: } elsif ($type eq 'previous' || $type eq 'future') {
3886: $typesref = [$type];
3887: }
3888: my %roles = &get_my_roles($uname,$udom,'userroles',
3889: $typesref,undef,[$cdom]);
3890: my ($tmp) = keys(%roles);
3891: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3892: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3893: if (@course_roles > 0) {
3894: return 1;
3895: }
3896: return 0;
3897: }
3898:
1.478 albertel 3899: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3900: # input: action, courseID, current domain, intended
1.637 raeburn 3901: # path to file, source of file, instruction to parse file for objects,
3902: # ref to hash for embedded objects,
3903: # ref to hash for codebase of java objects.
1.1095 raeburn 3904: # reference to scalar to accommodate mime type determined
3905: # from File::MMagic if $parser = parse.
1.637 raeburn 3906: #
1.485 raeburn 3907: # output: url to file (if action was uploaddoc),
3908: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3909: #
1.478 albertel 3910: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3911: # course.
1.477 raeburn 3912: #
1.478 albertel 3913: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3914: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3915: # course's home server.
1.477 raeburn 3916: #
1.478 albertel 3917: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3918: # be copied from $source (current location) to
3919: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3920: # and will then be copied to
3921: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3922: # course's home server.
1.485 raeburn 3923: #
1.481 raeburn 3924: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3925: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3926: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3927: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3928: # in course's home server.
1.637 raeburn 3929: #
1.477 raeburn 3930:
3931: sub process_coursefile {
1.1095 raeburn 3932: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3933: $mimetype)=@_;
1.477 raeburn 3934: my $fetchresult;
1.638 albertel 3935: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3936: if ($action eq 'propagate') {
1.638 albertel 3937: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3938: $home);
1.481 raeburn 3939: } else {
1.477 raeburn 3940: my $fpath = '';
3941: my $fname = $file;
1.478 albertel 3942: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3943: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3944: my $filepath = &build_filepath($fpath);
1.481 raeburn 3945: if ($action eq 'copy') {
3946: if ($source eq '') {
3947: $fetchresult = 'no source file';
3948: return $fetchresult;
3949: } else {
3950: my $destination = $filepath.'/'.$fname;
3951: rename($source,$destination);
3952: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3953: $home);
1.481 raeburn 3954: }
3955: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 3956: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3957: print $fh $env{'form.'.$source};
1.481 raeburn 3958: close($fh);
1.637 raeburn 3959: if ($parser eq 'parse') {
1.1024 raeburn 3960: my $mm = new File::MMagic;
1.1095 raeburn 3961: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3962: if ($type eq 'text/html') {
1.1024 raeburn 3963: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3964: unless ($parse_result eq 'ok') {
3965: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3966: }
1.637 raeburn 3967: }
1.1095 raeburn 3968: if (ref($mimetype)) {
3969: $$mimetype = $type;
3970: }
1.637 raeburn 3971: }
1.477 raeburn 3972: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3973: $home);
1.481 raeburn 3974: if ($fetchresult eq 'ok') {
3975: return '/uploaded/'.$fpath.'/'.$fname;
3976: } else {
3977: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3978: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3979: return '/adm/notfound.html';
3980: }
1.477 raeburn 3981: }
3982: }
1.485 raeburn 3983: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3984: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3985: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3986: }
3987: return $fetchresult;
3988: }
3989:
1.637 raeburn 3990: sub build_filepath {
3991: my ($fpath) = @_;
3992: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3993: unless ($fpath eq '') {
3994: my @parts=split('/',$fpath);
3995: foreach my $part (@parts) {
3996: $filepath.= '/'.$part;
3997: if ((-e $filepath)!=1) {
3998: mkdir($filepath,0777);
3999: }
4000: }
4001: }
4002: return $filepath;
4003: }
4004:
4005: sub store_edited_file {
1.638 albertel 4006: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4007: my $file = $primary_url;
4008: $file =~ s#^/uploaded/$docudom/$docuname/##;
4009: my $fpath = '';
4010: my $fname = $file;
4011: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4012: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4013: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4014: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4015: print $fh $content;
4016: close($fh);
1.638 albertel 4017: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4018: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4019: $home);
1.637 raeburn 4020: if ($$fetchresult eq 'ok') {
4021: return '/uploaded/'.$fpath.'/'.$fname;
4022: } else {
1.638 albertel 4023: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4024: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4025: return '/adm/notfound.html';
4026: }
4027: }
4028:
1.531 albertel 4029: sub clean_filename {
1.831 albertel 4030: my ($fname,$args)=@_;
1.315 www 4031: # Replace Windows backslashes by forward slashes
1.257 www 4032: $fname=~s/\\/\//g;
1.831 albertel 4033: if (!$args->{'keep_path'}) {
4034: # Get rid of everything but the actual filename
4035: $fname=~s/^.*\/([^\/]+)$/$1/;
4036: }
1.315 www 4037: # Replace spaces by underscores
4038: $fname=~s/\s+/\_/g;
1.1406 raeburn 4039: # Transliterate non-ascii text to ascii
4040: my $lang = &Apache::lonlocal::current_language();
4041: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4042: # Replace all other weird characters by nothing
1.831 albertel 4043: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4044: # Replace all .\d. sequences with _\d. so they no longer look like version
4045: # numbers
4046: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 4047: return $fname;
4048: }
1.1406 raeburn 4049:
1.1051 raeburn 4050: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4051: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4052: # image with the same aspect ratio as the original, but with dimensions which do
4053: # not exceed $resizewidth and $resizeheight.
4054:
1.984 neumanie 4055: sub resizeImage {
1.1051 raeburn 4056: my ($img_path,$resizewidth,$resizeheight) = @_;
4057: my $ima = Image::Magick->new;
4058: my $resized;
4059: if (-e $img_path) {
4060: $ima->Read($img_path);
4061: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4062: my $width = $ima->Get('width');
4063: my $height = $ima->Get('height');
4064: if ($width > $resizewidth) {
4065: my $factor = $width/$resizewidth;
4066: my $newheight = $height/$factor;
4067: $ima->Scale(width=>$resizewidth,height=>$newheight);
4068: $resized = 1;
4069: }
4070: }
4071: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4072: my $width = $ima->Get('width');
4073: my $height = $ima->Get('height');
4074: if ($height > $resizeheight) {
4075: my $factor = $height/$resizeheight;
4076: my $newwidth = $width/$factor;
4077: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4078: $resized = 1;
4079: }
4080: }
4081: if ($resized) {
4082: $ima->Write($img_path);
4083: }
4084: }
4085: return;
1.977 amueller 4086: }
4087:
1.608 albertel 4088: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4089: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4090: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4091: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4092: # canceloverwrite, scantron or ''.
1.1090 raeburn 4093: # if 'coursedoc': upload to the current course
4094: # if 'existingfile': write file to tmp/overwrites directory
4095: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4096: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4097: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4098: # $parser - instruction to parse file for objects ($parser = parse) or
4099: # if context is 'scantron', $parser is hashref of csv column mapping
4100: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4101: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4102: # $allfiles - reference to hash for embedded objects
4103: # $codebase - reference to hash for codebase of java objects
4104: # $desuname - username for permanent storage of uploaded file
4105: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4106: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4107: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4108: # $resizewidth - width (pixels) to which to resize uploaded image
4109: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4110: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4111: # from File::MMagic.
1.858 raeburn 4112: #
1.686 albertel 4113: # output: url of file in userspace, or error: <message>
4114: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4115:
1.531 albertel 4116: sub userfileupload {
1.1090 raeburn 4117: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4118: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4119: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4120: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4121: $fname=&clean_filename($fname);
1.1090 raeburn 4122: # See if there is anything left
1.257 www 4123: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4124: # If filename now begins with a . prepend unix timestamp _ milliseconds
4125: if ($fname =~ /^\./) {
4126: my ($s,$usec) = &gettimeofday();
4127: while (length($usec) < 6) {
4128: $usec = '0'.$usec;
4129: }
4130: $fname = $s.'_'.substr($usec,0,3).$fname;
4131: }
1.1090 raeburn 4132: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4133: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4134: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4135: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4136: my $now = time;
1.1090 raeburn 4137: my $filepath;
1.1095 raeburn 4138: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4139: $filepath = 'tmp/helprequests/'.$now;
4140: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4141: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4142: '_'.$env{'user.domain'}.'/pending';
4143: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4144: my ($docuname,$docudom);
1.1350 raeburn 4145: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4146: $docudom = $destudom;
4147: } else {
4148: $docudom = $env{'user.domain'};
4149: }
1.1350 raeburn 4150: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4151: $docuname = $destuname;
4152: } else {
4153: $docuname = $env{'user.name'};
4154: }
4155: if (exists($env{'form.group'})) {
4156: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4157: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4158: }
4159: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4160: if ($context eq 'canceloverwrite') {
4161: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4162: if (-e $tempfile) {
4163: my @info = stat($tempfile);
4164: if ($info[9] eq $env{'form.timestamp'}) {
4165: unlink($tempfile);
4166: }
4167: }
4168: return;
1.523 raeburn 4169: }
4170: }
1.1090 raeburn 4171: # Create the directory if not present
1.741 raeburn 4172: my @parts=split(/\//,$filepath);
4173: my $fullpath = $perlvar{'lonDaemons'};
4174: for (my $i=0;$i<@parts;$i++) {
4175: $fullpath .= '/'.$parts[$i];
4176: if ((-e $fullpath)!=1) {
4177: mkdir($fullpath,0777);
4178: }
4179: }
1.1359 raeburn 4180: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4181: print $fh $env{'form.'.$formname};
4182: close($fh);
1.1090 raeburn 4183: if ($context eq 'existingfile') {
4184: my @info = stat($fullpath.'/'.$fname);
4185: return ($fullpath.'/'.$fname,$info[9]);
4186: } else {
4187: return $fullpath.'/'.$fname;
4188: }
1.523 raeburn 4189: }
1.995 raeburn 4190: if ($subdir eq 'scantron') {
4191: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4192: } else {
1.995 raeburn 4193: $fname="$subdir/$fname";
4194: }
1.1090 raeburn 4195: if ($context eq 'coursedoc') {
1.638 albertel 4196: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4197: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4198: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4199: return &finishuserfileupload($docuname,$docudom,
4200: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4201: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4202: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4203: } else {
1.1218 raeburn 4204: if ($env{'form.folder'}) {
4205: $fname=$env{'form.folder'}.'/'.$fname;
4206: }
1.638 albertel 4207: return &process_coursefile('uploaddoc',$docuname,$docudom,
4208: $fname,$formname,$parser,
1.1095 raeburn 4209: $allfiles,$codebase,$mimetype);
1.481 raeburn 4210: }
1.719 banghart 4211: } elsif (defined($destuname)) {
4212: my $docuname=$destuname;
4213: my $docudom=$destudom;
1.860 raeburn 4214: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4215: $parser,$allfiles,$codebase,
1.1051 raeburn 4216: $thumbwidth,$thumbheight,
1.1095 raeburn 4217: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4218: } else {
1.638 albertel 4219: my $docuname=$env{'user.name'};
4220: my $docudom=$env{'user.domain'};
1.1220 raeburn 4221: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4222: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4223: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4224: }
1.860 raeburn 4225: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4226: $parser,$allfiles,$codebase,
1.1051 raeburn 4227: $thumbwidth,$thumbheight,
1.1095 raeburn 4228: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4229: }
1.271 www 4230: }
4231:
4232: sub finishuserfileupload {
1.860 raeburn 4233: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4234: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4235: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4236: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4237:
1.860 raeburn 4238: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4239: $file=$fname;
4240: if ($fname=~m|/|) {
4241: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4242: $path.=$fnamepath.'/';
4243: }
1.259 www 4244: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4245: my $count;
4246: for ($count=4;$count<=$#parts;$count++) {
4247: $filepath.="/$parts[$count]";
4248: if ((-e $filepath)!=1) {
4249: mkdir($filepath,0777);
4250: }
4251: }
1.984 neumanie 4252:
1.258 www 4253: # Save the file
4254: {
1.1359 raeburn 4255: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4256: &logthis('Failed to create '.$filepath.'/'.$file);
4257: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4258: return '/adm/notfound.html';
4259: }
1.1090 raeburn 4260: if ($context eq 'overwrite') {
1.1117 foxr 4261: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4262: my $target = $filepath.'/'.$file;
4263: if (-e $source) {
4264: my @info = stat($source);
4265: if ($info[9] eq $env{'form.timestamp'}) {
4266: unless (&File::Copy::move($source,$target)) {
4267: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4268: return "Moving from $source failed";
4269: }
4270: } else {
4271: return "Temporary file: $source had unexpected date/time for last modification";
4272: }
4273: } else {
4274: return "Temporary file: $source missing";
4275: }
4276: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4277: &logthis('Failed to write to '.$filepath.'/'.$file);
4278: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4279: return '/adm/notfound.html';
4280: }
1.570 albertel 4281: close(FH);
1.1051 raeburn 4282: if ($resizewidth && $resizeheight) {
4283: my $mm = new File::MMagic;
4284: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4285: if ($mime_type =~ m{^image/}) {
4286: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4287: }
1.977 amueller 4288: }
1.258 www 4289: }
1.1152 raeburn 4290: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4291: if (ref($mimetype)) {
4292: if ($$mimetype eq '') {
4293: my $mm = new File::MMagic;
4294: my $type = $mm->checktype_filename($filepath.'/'.$file);
4295: $$mimetype = $type;
4296: }
4297: }
4298: }
1.1401 raeburn 4299: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4300: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4301: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4302: $allfiles,$codebase);
4303: unless ($parse_result eq 'ok') {
4304: &logthis('Failed to parse '.$filepath.$file.
4305: ' for embedded media: '.$parse_result);
4306: }
1.637 raeburn 4307: }
1.1401 raeburn 4308: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4309: my $format = $env{'form.scantron_format'};
4310: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4311: }
1.860 raeburn 4312: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4313: my $input = $filepath.'/'.$file;
4314: my $output = $filepath.'/'.'tn-'.$file;
4315: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4316: my @args = ('convert','-sample',$thumbsize,$input,$output);
4317: system({$args[0]} @args);
1.860 raeburn 4318: if (-e $filepath.'/'.'tn-'.$file) {
4319: $fetchthumb = 1;
4320: }
4321: }
1.858 raeburn 4322:
1.259 www 4323: # Notify homeserver to grep it
4324: #
1.984 neumanie 4325: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4326: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4327: if ($fetchresult eq 'ok') {
1.860 raeburn 4328: if ($fetchthumb) {
4329: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4330: if ($thumbresult ne 'ok') {
4331: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4332: $docuhome.': '.$thumbresult);
4333: }
4334: }
1.259 www 4335: #
1.258 www 4336: # Return the URL to it
1.494 albertel 4337: return '/uploaded/'.$path.$file;
1.263 www 4338: } else {
1.494 albertel 4339: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4340: ': '.$fetchresult);
1.263 www 4341: return '/adm/notfound.html';
1.858 raeburn 4342: }
1.493 albertel 4343: }
4344:
1.637 raeburn 4345: sub extract_embedded_items {
1.961 raeburn 4346: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4347: my @state = ();
1.1164 raeburn 4348: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4349: my %javafiles = (
4350: codebase => '',
4351: code => '',
4352: archive => ''
4353: );
4354: my %mediafiles = (
4355: src => '',
4356: movie => '',
4357: );
1.648 raeburn 4358: my $p;
4359: if ($content) {
4360: $p = HTML::LCParser->new($content);
4361: } else {
1.961 raeburn 4362: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4363: }
1.641 albertel 4364: while (my $t=$p->get_token()) {
1.640 albertel 4365: if ($t->[0] eq 'S') {
4366: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4367: push(@state, $tagname);
1.648 raeburn 4368: if (lc($tagname) eq 'allow') {
4369: &add_filetype($allfiles,$attr->{'src'},'src');
4370: }
1.640 albertel 4371: if (lc($tagname) eq 'img') {
4372: &add_filetype($allfiles,$attr->{'src'},'src');
4373: }
1.886 albertel 4374: if (lc($tagname) eq 'a') {
1.1222 raeburn 4375: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4376: &add_filetype($allfiles,$attr->{'href'},'href');
4377: }
1.886 albertel 4378: }
1.645 raeburn 4379: if (lc($tagname) eq 'script') {
1.1164 raeburn 4380: my $src;
1.645 raeburn 4381: if ($attr->{'archive'} =~ /\.jar$/i) {
4382: &add_filetype($allfiles,$attr->{'archive'},'archive');
4383: } else {
1.1164 raeburn 4384: if ($attr->{'src'} ne '') {
4385: $src = $attr->{'src'};
4386: &add_filetype($allfiles,$src,'src');
4387: }
4388: }
4389: my $text = $p->get_trimmed_text();
4390: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4391: my @swfargs = split(/,/,$1);
4392: foreach my $item (@swfargs) {
4393: $item =~ s/["']//g;
4394: $item =~ s/^\s+//;
4395: $item =~ s/\s+$//;
4396: }
4397: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4398: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4399: push(@{$related{$swfargs[0]}},$swfargs[2]);
4400: } else {
4401: $related{$swfargs[0]} = [$swfargs[2]];
4402: }
4403: }
1.645 raeburn 4404: }
4405: }
4406: if (lc($tagname) eq 'link') {
4407: if (lc($attr->{'rel'}) eq 'stylesheet') {
4408: &add_filetype($allfiles,$attr->{'href'},'href');
4409: }
4410: }
1.640 albertel 4411: if (lc($tagname) eq 'object' ||
4412: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4413: foreach my $item (keys(%javafiles)) {
4414: $javafiles{$item} = '';
4415: }
1.1164 raeburn 4416: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4417: $lastids{lc($tagname)} = $attr->{'id'};
4418: }
1.640 albertel 4419: }
4420: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4421: my $name = lc($attr->{'name'});
4422: foreach my $item (keys(%javafiles)) {
4423: if ($name eq $item) {
4424: $javafiles{$item} = $attr->{'value'};
4425: last;
4426: }
4427: }
1.1164 raeburn 4428: my $pathfrom;
1.640 albertel 4429: foreach my $item (keys(%mediafiles)) {
4430: if ($name eq $item) {
1.1164 raeburn 4431: $pathfrom = $attr->{'value'};
4432: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4433: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4434: last;
4435: }
4436: }
1.1164 raeburn 4437: if ($name eq 'flashvars') {
4438: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4439: }
4440: if ($pathfrom ne '') {
4441: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4442: $pathfrom);
4443: }
1.640 albertel 4444: }
4445: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4446: foreach my $item (keys(%javafiles)) {
4447: if ($attr->{$item}) {
4448: $javafiles{$item} = $attr->{$item};
4449: last;
4450: }
4451: }
4452: foreach my $item (keys(%mediafiles)) {
4453: if ($attr->{$item}) {
4454: &add_filetype($allfiles,$attr->{$item},$item);
4455: last;
4456: }
4457: }
1.1164 raeburn 4458: if (lc($tagname) eq 'embed') {
4459: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4460: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4461: $attr->{'src'});
4462: }
4463: }
1.640 albertel 4464: }
1.1243 raeburn 4465: if (lc($tagname) eq 'iframe') {
4466: my $src = $attr->{'src'} ;
4467: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4468: &add_filetype($allfiles,$src,'src');
4469: } elsif ($src =~ m{^/}) {
4470: if ($env{'request.course.id'}) {
4471: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4472: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4473: my $url = &hreflocation('',$fullpath);
4474: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4475: my $relpath = $1;
4476: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4477: &add_filetype($allfiles,$1,'src');
4478: }
4479: }
4480: }
4481: }
4482: }
1.1164 raeburn 4483: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4484: pop(@state);
1.1164 raeburn 4485: }
1.640 albertel 4486: } elsif ($t->[0] eq 'E') {
4487: my ($tagname) = ($t->[1]);
4488: if ($javafiles{'codebase'} ne '') {
4489: $javafiles{'codebase'} .= '/';
4490: }
4491: if (lc($tagname) eq 'applet' ||
4492: lc($tagname) eq 'object' ||
4493: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4494: ) {
4495: foreach my $item (keys(%javafiles)) {
4496: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4497: my $file=$javafiles{'codebase'}.$javafiles{$item};
4498: &add_filetype($allfiles,$file,$item);
4499: }
4500: }
4501: }
4502: pop @state;
4503: }
4504: }
1.1164 raeburn 4505: foreach my $id (sort(keys(%flashvars))) {
4506: if ($shockwave{$id} ne '') {
4507: my @pairs = split(/\&/,$flashvars{$id});
4508: foreach my $pair (@pairs) {
4509: my ($key,$value) = split(/\=/,$pair);
4510: if ($key eq 'thumb') {
4511: &add_filetype($allfiles,$value,$key);
4512: } elsif ($key eq 'content') {
4513: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4514: my ($ext) = ($value =~ /\.([^.]+)$/);
4515: if ($ext ne '') {
4516: &add_filetype($allfiles,$path.$value,$ext);
4517: }
4518: }
4519: }
4520: }
4521: }
1.637 raeburn 4522: return 'ok';
4523: }
4524:
1.639 albertel 4525: sub add_filetype {
4526: my ($allfiles,$file,$type)=@_;
4527: if (exists($allfiles->{$file})) {
4528: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4529: push(@{$allfiles->{$file}}, &escape($type));
4530: }
4531: } else {
4532: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4533: }
4534: }
4535:
1.1164 raeburn 4536: sub embedded_dependency {
4537: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4538: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4539: if (($identifier ne '') &&
4540: (ref($related->{$identifier}) eq 'ARRAY') &&
4541: ($pathfrom ne '')) {
4542: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4543: foreach my $dep (@{$related->{$identifier}}) {
4544: &add_filetype($allfiles,$path.$dep,'object');
4545: }
4546: }
4547: }
4548: return;
4549: }
4550:
1.1401 raeburn 4551: sub bubblesheet_converter {
4552: my ($cdom,$fullpath,$config,$format) = @_;
4553: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4554: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4555: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4556: my (%csvcols,%csvoptions);
4557: if (ref($config->{'fields'}) eq 'HASH') {
4558: %csvcols = %{$config->{'fields'}};
4559: }
4560: if (ref($config->{'options'}) eq 'HASH') {
4561: %csvoptions = %{$config->{'options'}};
4562: }
1.1401 raeburn 4563: my %csvbynum = reverse(%csvcols);
4564: my %scantronconf = &get_scantron_config($format,$cdom);
4565: if (keys(%scantronconf)) {
4566: my %bynum = (
4567: $scantronconf{CODEstart} => 'CODEstart',
4568: $scantronconf{IDstart} => 'IDstart',
4569: $scantronconf{PaperID} => 'PaperID',
4570: $scantronconf{FirstName} => 'FirstName',
4571: $scantronconf{LastName} => 'LastName',
4572: $scantronconf{Qstart} => 'Qstart',
4573: );
4574: my @ordered;
4575: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4576: push(@ordered,$bynum{$item});
1.1401 raeburn 4577: }
4578: my %mapstart = (
4579: CODEstart => 'CODE',
4580: IDstart => 'ID',
4581: PaperID => 'PaperID',
4582: FirstName => 'FirstName',
4583: LastName => 'LastName',
4584: Qstart => 'FirstQuestion',
4585: );
4586: my %maplength = (
4587: CODEstart => 'CODElength',
4588: IDstart => 'IDlength',
4589: PaperID => 'PaperIDlength',
4590: FirstName => 'FirstNamelength',
4591: LastName => 'LastNamelength',
4592: );
4593: if (open(my $fh,'<',$fullpath)) {
4594: my $output;
1.1403 raeburn 4595: my %lettdig = &letter_to_digits();
4596: my %diglett = reverse(%lettdig);
4597: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4598: my $num = 0;
1.1401 raeburn 4599: while (my $line=<$fh>) {
1.1404 raeburn 4600: $num ++;
4601: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4602: $line =~ s{[\r\n]+$}{};
4603: my %found;
4604: my @values = split(/,/,$line);
4605: my ($qstart,$record);
4606: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4607: if ((($qstart ne '') && ($i > $qstart)) ||
4608: ($csvbynum{$i} eq 'FirstQuestion')) {
4609: if ($values[$i] eq '') {
4610: $values[$i] = $scantronconf{'Qoff'};
4611: } elsif ($scantronconf{'Qon'} eq 'number') {
4612: if ($values[$i] =~ /^[A-Ja-j]$/) {
4613: $values[$i] = $lettdig{uc($values[$i])};
4614: }
4615: } elsif ($scantronconf{'Qon'} eq 'letter') {
4616: if ($values[$i] =~ /^[0-9]$/) {
4617: $values[$i] = $diglett{$values[$i]};
4618: }
4619: } else {
4620: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4621: my $digit;
4622: if ($values[$i] =~ /^[A-Ja-j]$/) {
4623: $digit = $lettdig{uc($values[$i])}-1;
4624: if ($values[$i] eq 'J') {
4625: $digit += $numletts;
4626: }
4627: } elsif ($values[$i] =~ /^[0-9]$/) {
4628: $digit = $values[$i]-1;
4629: if ($values[$i] eq '0') {
4630: $digit += $numletts;
4631: }
4632: }
4633: my $qval='';
4634: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4635: if ($j == $digit) {
4636: $qval .= $scantronconf{'Qon'};
4637: } else {
4638: $qval .= $scantronconf{'Qoff'};
4639: }
4640: }
4641: $values[$i] = $qval;
4642: }
4643: }
4644: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4645: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4646: }
4647: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4648: if ($numblank > 0) {
4649: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4650: }
1.1401 raeburn 4651: if ($csvbynum{$i} eq 'FirstQuestion') {
4652: $qstart = $i;
1.1403 raeburn 4653: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4654: } else {
1.1403 raeburn 4655: $found{'FirstQuestion'} .= $values[$i];
4656: }
4657: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4658: if ($csvoptions{'rem'}) {
4659: $values[$i] =~ s/^\s+//;
4660: }
4661: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4662: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4663: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4664: }
4665: }
4666: $found{$csvbynum{$i}} = $values[$i];
4667: }
4668: }
4669: foreach my $item (@ordered) {
4670: my $currlength = 1+length($record);
4671: my $numspaces = $scantronconf{$item} - $currlength;
4672: if ($numspaces > 0) {
4673: $record .= (' ' x $numspaces);
4674: }
4675: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4676: unless ($item eq 'Qstart') {
4677: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4678: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4679: }
4680: }
4681: $record .= $found{$mapstart{$item}};
4682: }
4683: }
4684: $output .= "$record\n";
4685: }
4686: close($fh);
4687: if ($output) {
4688: if (open(my $fh,'>',$fullpath)) {
4689: print $fh $output;
4690: close($fh);
4691: }
4692: }
4693: }
4694: }
4695: return;
4696: }
4697: }
4698:
1.1403 raeburn 4699: sub letter_to_digits {
4700: my %lettdig = (
4701: A => 1,
4702: B => 2,
4703: C => 3,
4704: D => 4,
4705: E => 5,
4706: F => 6,
4707: G => 7,
4708: H => 8,
4709: I => 9,
4710: J => 0,
4711: );
4712: return %lettdig;
4713: }
4714:
1.1401 raeburn 4715: sub get_scantron_config {
4716: my ($which,$cdom) = @_;
4717: my @lines = &get_scantronformat_file($cdom);
4718: my %config;
4719: #FIXME probably should move to XML it has already gotten a bit much now
4720: foreach my $line (@lines) {
4721: my ($name,$descrip)=split(/:/,$line);
4722: if ($name ne $which ) { next; }
4723: chomp($line);
4724: my @config=split(/:/,$line);
4725: $config{'name'}=$config[0];
4726: $config{'description'}=$config[1];
4727: $config{'CODElocation'}=$config[2];
4728: $config{'CODEstart'}=$config[3];
4729: $config{'CODElength'}=$config[4];
4730: $config{'IDstart'}=$config[5];
4731: $config{'IDlength'}=$config[6];
4732: $config{'Qstart'}=$config[7];
4733: $config{'Qlength'}=$config[8];
4734: $config{'Qoff'}=$config[9];
4735: $config{'Qon'}=$config[10];
4736: $config{'PaperID'}=$config[11];
4737: $config{'PaperIDlength'}=$config[12];
4738: $config{'FirstName'}=$config[13];
4739: $config{'FirstNamelength'}=$config[14];
4740: $config{'LastName'}=$config[15];
4741: $config{'LastNamelength'}=$config[16];
4742: $config{'BubblesPerRow'}=$config[17];
4743: last;
4744: }
4745: return %config;
4746: }
4747:
4748: sub get_scantronformat_file {
4749: my ($cdom) = @_;
4750: if ($cdom eq '') {
4751: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4752: }
4753: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4754: my $gottab = 0;
4755: my @lines;
4756: if (ref($domconfig{'scantron'}) eq 'HASH') {
4757: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4758: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4759: if ($formatfile ne '-1') {
4760: @lines = split("\n",$formatfile,-1);
4761: $gottab = 1;
4762: }
4763: }
4764: }
4765: if (!$gottab) {
4766: my $confname = $cdom.'-domainconfig';
4767: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4768: my $formatfile = &getfile($default);
4769: if ($formatfile ne '-1') {
4770: @lines = split("\n",$formatfile,-1);
4771: $gottab = 1;
4772: }
4773: }
4774: if (!$gottab) {
4775: my @domains = ¤t_machine_domains();
4776: if (grep(/^\Q$cdom\E$/,@domains)) {
4777: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4778: @lines = <$fh>;
4779: close($fh);
1.1403 raeburn 4780: }
1.1401 raeburn 4781: } else {
4782: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4783: @lines = <$fh>;
4784: close($fh);
4785: }
4786: }
4787: }
4788: return @lines;
4789: }
4790:
1.493 albertel 4791: sub removeuploadedurl {
1.984 neumanie 4792: my ($url)=@_;
4793: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4794: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4795: }
4796:
4797: sub removeuserfile {
4798: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4799: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4800: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4801: if ($result eq 'ok') {
1.798 raeburn 4802: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4803: my $metafile = $fname.'.meta';
4804: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4805: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4806: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4807: my $sqlresult =
1.823 albertel 4808: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4809: 'portfolio_metadata',$group,
4810: 'delete');
1.798 raeburn 4811: }
4812: }
4813: return $result;
1.257 www 4814: }
1.15 www 4815:
1.530 albertel 4816: sub mkdiruserfile {
4817: my ($docuname,$docudom,$dir)=@_;
4818: my $home=&homeserver($docuname,$docudom);
4819: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4820: }
4821:
1.531 albertel 4822: sub renameuserfile {
4823: my ($docuname,$docudom,$old,$new)=@_;
4824: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4825: my $result = &reply("renameuserfile:$docudom:$docuname:".
4826: &escape("$old").':'.&escape("$new"),$home);
4827: if ($result eq 'ok') {
4828: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4829: my $oldmeta = $old.'.meta';
4830: my $newmeta = $new.'.meta';
4831: my $metaresult =
4832: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4833: my $url = "/uploaded/$docudom/$docuname/$old";
4834: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4835: my $sqlresult =
1.823 albertel 4836: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4837: 'portfolio_metadata',$group,
4838: 'delete');
1.798 raeburn 4839: }
4840: }
4841: return $result;
1.531 albertel 4842: }
4843:
1.14 www 4844: # ------------------------------------------------------------------------- Log
4845:
4846: sub log {
4847: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4848: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4849: }
4850:
4851: # ------------------------------------------------------------------ Course Log
1.352 www 4852: #
4853: # This routine flushes several buffers of non-mission-critical nature
4854: #
1.157 www 4855:
4856: sub flushcourselogs {
1.352 www 4857: &logthis('Flushing log buffers');
4858: #
4859: # course logs
4860: # This is a log of all transactions in a course, which can be used
4861: # for data mining purposes
4862: #
4863: # It also collects the courseid database, which lists last transaction
4864: # times and course titles for all courseids
4865: #
4866: my %courseidbuffer=();
1.921 raeburn 4867: foreach my $crsid (keys(%courselogs)) {
1.352 www 4868: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4869: &escape($courselogs{$crsid}),
4870: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4871: delete $courselogs{$crsid};
4872: } else {
4873: &logthis('Failed to flush log buffer for '.$crsid);
4874: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4875: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4876: " exceeded maximum size, deleting.</font>");
4877: delete $courselogs{$crsid};
4878: }
1.352 www 4879: }
1.920 raeburn 4880: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4881: 'description' => $coursedescrbuf{$crsid},
4882: 'inst_code' => $courseinstcodebuf{$crsid},
4883: 'type' => $coursetypebuf{$crsid},
4884: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4885: };
1.191 harris41 4886: }
1.352 www 4887: #
4888: # Write course id database (reverse lookup) to homeserver of courses
4889: # Is used in pickcourse
4890: #
1.840 albertel 4891: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4892: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4893: $courseidbuffer{$crs_home},
4894: $crs_home,'timeonly');
1.352 www 4895: }
4896: #
4897: # File accesses
4898: # Writes to the dynamic metadata of resources to get hit counts, etc.
4899: #
1.449 matthew 4900: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4901: if ($entry =~ /___count$/) {
4902: my ($dom,$name);
1.807 albertel 4903: ($dom,$name,undef)=
1.811 albertel 4904: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4905: if (! defined($dom) || $dom eq '' ||
4906: ! defined($name) || $name eq '') {
1.620 albertel 4907: my $cid = $env{'request.course.id'};
4908: $dom = $env{'request.'.$cid.'.domain'};
4909: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4910: }
1.450 matthew 4911: my $value = $accesshash{$entry};
4912: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4913: my %temphash=($url => $value);
1.449 matthew 4914: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4915: if ($result eq 'ok') {
4916: delete $accesshash{$entry};
4917: }
4918: } else {
1.811 albertel 4919: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4920: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4921: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4922: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4923: delete $accesshash{$entry};
4924: }
1.185 www 4925: }
1.191 harris41 4926: }
1.352 www 4927: #
4928: # Roles
4929: # Reverse lookup of user roles for course faculty/staff and co-authorship
4930: #
1.800 albertel 4931: foreach my $entry (keys(%userrolehash)) {
1.351 www 4932: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4933: split(/\:/,$entry);
4934: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4935: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4936: $rudom,$runame) eq 'ok') {
4937: delete $userrolehash{$entry};
4938: }
4939: }
1.662 raeburn 4940: #
1.1334 raeburn 4941: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4942: #
4943: my %domrolebuffer = ();
1.1000 raeburn 4944: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4945: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4946: if ($domrolebuffer{$rudom}) {
4947: $domrolebuffer{$rudom}.='&'.&escape($entry).
4948: '='.&escape($domainrolehash{$entry});
4949: } else {
4950: $domrolebuffer{$rudom}.=&escape($entry).
4951: '='.&escape($domainrolehash{$entry});
4952: }
4953: delete $domainrolehash{$entry};
4954: }
4955: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4956: my %servers;
4957: if (defined(&domain($dom,'primary'))) {
4958: my $primary=&domain($dom,'primary');
4959: my $hostname=&hostname($primary);
4960: $servers{$primary} = $hostname;
4961: } else {
4962: %servers = &get_servers($dom,'library');
4963: }
1.841 albertel 4964: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4965: if (&reply('domroleput:'.$dom.':'.
4966: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4967: last;
4968: } else {
1.841 albertel 4969: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4970: }
1.662 raeburn 4971: }
4972: }
1.186 www 4973: $dumpcount++;
1.157 www 4974: }
4975:
4976: sub courselog {
4977: my $what=shift;
1.158 www 4978: $what=time.':'.$what;
1.620 albertel 4979: unless ($env{'request.course.id'}) { return ''; }
4980: $coursedombuf{$env{'request.course.id'}}=
4981: $env{'course.'.$env{'request.course.id'}.'.domain'};
4982: $coursenumbuf{$env{'request.course.id'}}=
4983: $env{'course.'.$env{'request.course.id'}.'.num'};
4984: $coursehombuf{$env{'request.course.id'}}=
4985: $env{'course.'.$env{'request.course.id'}.'.home'};
4986: $coursedescrbuf{$env{'request.course.id'}}=
4987: $env{'course.'.$env{'request.course.id'}.'.description'};
4988: $courseinstcodebuf{$env{'request.course.id'}}=
4989: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4990: $courseownerbuf{$env{'request.course.id'}}=
4991: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4992: $coursetypebuf{$env{'request.course.id'}}=
4993: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4994: if (defined $courselogs{$env{'request.course.id'}}) {
4995: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4996: } else {
1.620 albertel 4997: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4998: }
1.620 albertel 4999: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5000: &flushcourselogs();
5001: }
1.158 www 5002: }
5003:
5004: sub courseacclog {
5005: my $fnsymb=shift;
1.620 albertel 5006: unless ($env{'request.course.id'}) { return ''; }
5007: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5008: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5009: $what.=':POST';
1.583 matthew 5010: # FIXME: Probably ought to escape things....
1.800 albertel 5011: foreach my $key (keys(%env)) {
5012: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5013: my $formitem = $1;
5014: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5015: $what.=':'.$formitem.'='.$env{$key};
5016: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
5017: $what.=':'.$formitem.'='.$env{$key};
5018: }
1.158 www 5019: }
1.191 harris41 5020: }
1.583 matthew 5021: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5022: # FIXME: We should not be depending on a form parameter that someone
5023: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5024: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5025: $what.= ':POST';
5026: # FIXME: Probably ought to escape things....
5027: foreach my $element ('courseexp','crsfulltext','crsrelated',
5028: 'crsdiscuss') {
1.620 albertel 5029: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5030: }
5031: }
1.158 www 5032: }
5033: &courselog($what);
1.149 www 5034: }
5035:
1.185 www 5036: sub countacc {
5037: my $url=&declutter(shift);
1.458 matthew 5038: return if (! defined($url) || $url eq '');
1.620 albertel 5039: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5040: #
5041: # Mark that this url was used in this course
5042: #
1.620 albertel 5043: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5044: #
5045: # Increase the access count for this resource in this child process
5046: #
1.281 www 5047: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5048: $accesshash{$key}++;
1.185 www 5049: }
1.349 www 5050:
1.361 www 5051: sub linklog {
5052: my ($from,$to)=@_;
5053: $from=&declutter($from);
5054: $to=&declutter($to);
5055: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5056: $accesshash{$to.'___'.$from.'___goto'}=1;
5057: }
1.1160 www 5058:
5059: sub statslog {
5060: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5061: if ($users<2) { return; }
5062: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5063: 'course' => $env{'request.course.id'},
5064: 'sections' => '"all"',
5065: 'num_students' => $users,
5066: 'part' => $part,
5067: 'symb' => $symb,
5068: 'mean_tries' => $av_attempts,
5069: 'deg_of_diff' => $degdiff});
5070: foreach my $key (keys(%dynstore)) {
5071: $accesshash{$key}=$dynstore{$key};
5072: }
5073: }
1.361 www 5074:
1.349 www 5075: sub userrolelog {
5076: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5077: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5078: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5079: $userrolehash
5080: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5081: =$tend.':'.$tstart;
1.662 raeburn 5082: }
1.1169 droeschl 5083: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5084: $userrolehash
5085: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5086: =$tend.':'.$tstart;
5087: }
1.1334 raeburn 5088: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5089: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5090: $domainrolehash
5091: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5092: = $tend.':'.$tstart;
5093: }
1.351 www 5094: }
5095:
1.957 raeburn 5096: sub courserolelog {
5097: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5098: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5099: my $cdom = $1;
5100: my $cnum = $2;
5101: my $sec = $3;
5102: my $namespace = 'rolelog';
5103: my %storehash = (
5104: role => $trole,
5105: start => $tstart,
5106: end => $tend,
5107: selfenroll => $selfenroll,
5108: context => $context,
5109: );
5110: if ($trole eq 'gr') {
5111: $namespace = 'groupslog';
5112: $storehash{'group'} = $sec;
5113: } else {
5114: $storehash{'section'} = $sec;
5115: }
1.1188 raeburn 5116: &write_log('course',$namespace,\%storehash,$delflag,$username,
5117: $domain,$cnum,$cdom);
1.1184 raeburn 5118: if (($trole ne 'st') || ($sec ne '')) {
5119: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5120: }
5121: }
5122: return;
5123: }
5124:
1.1184 raeburn 5125: sub domainrolelog {
5126: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5127: if ($area =~ m{^/($match_domain)/$}) {
5128: my $cdom = $1;
5129: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5130: my $namespace = 'rolelog';
5131: my %storehash = (
5132: role => $trole,
5133: start => $tstart,
5134: end => $tend,
5135: context => $context,
5136: );
1.1188 raeburn 5137: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5138: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5139: }
5140: return;
5141:
5142: }
5143:
5144: sub coauthorrolelog {
5145: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5146: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5147: my $audom = $1;
5148: my $auname = $2;
5149: my $namespace = 'rolelog';
5150: my %storehash = (
5151: role => $trole,
5152: start => $tstart,
5153: end => $tend,
5154: context => $context,
5155: );
1.1188 raeburn 5156: &write_log('author',$namespace,\%storehash,$delflag,$username,
5157: $domain,$auname,$audom);
1.1184 raeburn 5158: }
5159: return;
5160: }
5161:
1.351 www 5162: sub get_course_adv_roles {
1.948 raeburn 5163: my ($cid,$codes) = @_;
1.620 albertel 5164: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5165: my %coursehash=&coursedescription($cid);
1.988 raeburn 5166: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5167: my %nothide=();
1.800 albertel 5168: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5169: if ($user !~ /:/) {
5170: $nothide{join(':',split(/[\@]/,$user))}=1;
5171: } else {
5172: $nothide{$user}=1;
5173: }
1.470 www 5174: }
1.1219 raeburn 5175: my @possdoms = ($coursehash{'domain'});
5176: if ($coursehash{'checkforpriv'}) {
5177: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5178: }
1.351 www 5179: my %returnhash=();
5180: my %dumphash=
5181: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5182: my $now=time;
1.997 raeburn 5183: my %privileged;
1.1000 raeburn 5184: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5185: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5186: if (($tstart) && ($tstart<0)) { next; }
5187: if (($tend) && ($tend<$now)) { next; }
5188: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5189: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5190: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5191: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5192: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5193: if ($role eq 'cr') { next; }
1.948 raeburn 5194: if ($codes) {
5195: if ($section) { $role .= ':'.$section; }
5196: if ($returnhash{$role}) {
5197: $returnhash{$role}.=','.$username.':'.$domain;
5198: } else {
5199: $returnhash{$role}=$username.':'.$domain;
5200: }
1.351 www 5201: } else {
1.988 raeburn 5202: my $key=&plaintext($role,$crstype);
1.973 bisitz 5203: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5204: if ($returnhash{$key}) {
5205: $returnhash{$key}.=','.$username.':'.$domain;
5206: } else {
5207: $returnhash{$key}=$username.':'.$domain;
5208: }
1.351 www 5209: }
1.948 raeburn 5210: }
1.400 www 5211: return %returnhash;
5212: }
5213:
5214: sub get_my_roles {
1.937 raeburn 5215: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5216: unless (defined($uname)) { $uname=$env{'user.name'}; }
5217: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5218: my (%dumphash,%nothide);
1.1086 raeburn 5219: if ($context eq 'userroles') {
1.1166 raeburn 5220: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5221: } else {
1.1219 raeburn 5222: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5223: if ($hidepriv) {
5224: my %coursehash=&coursedescription($udom.'_'.$uname);
5225: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5226: if ($user !~ /:/) {
5227: $nothide{join(':',split(/[\@]/,$user))} = 1;
5228: } else {
5229: $nothide{$user} = 1;
5230: }
5231: }
5232: }
1.858 raeburn 5233: }
1.400 www 5234: my %returnhash=();
5235: my $now=time;
1.999 raeburn 5236: my %privileged;
1.800 albertel 5237: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5238: my ($role,$tend,$tstart);
5239: if ($context eq 'userroles') {
1.1149 raeburn 5240: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5241: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5242: } else {
5243: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5244: }
1.400 www 5245: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5246: my $status = 'active';
1.939 raeburn 5247: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5248: $status = 'previous';
5249: }
5250: if (($tstart) && ($now<$tstart)) {
5251: $status = 'future';
5252: }
5253: if (ref($types) eq 'ARRAY') {
5254: if (!grep(/^\Q$status\E$/,@{$types})) {
5255: next;
5256: }
5257: } else {
5258: if ($status ne 'active') {
5259: next;
5260: }
5261: }
1.867 raeburn 5262: my ($rolecode,$username,$domain,$section,$area);
5263: if ($context eq 'userroles') {
1.1186 raeburn 5264: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5265: (undef,$domain,$username,$section) = split(/\//,$area);
5266: } else {
5267: ($role,$username,$domain,$section) = split(/\:/,$entry);
5268: }
1.832 raeburn 5269: if (ref($roledoms) eq 'ARRAY') {
5270: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5271: next;
5272: }
5273: }
5274: if (ref($roles) eq 'ARRAY') {
5275: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5276: if ($role =~ /^cr\//) {
5277: if (!grep(/^cr$/,@{$roles})) {
5278: next;
5279: }
1.1104 raeburn 5280: } elsif ($role =~ /^gr\//) {
5281: if (!grep(/^gr$/,@{$roles})) {
5282: next;
5283: }
1.922 raeburn 5284: } else {
5285: next;
5286: }
1.832 raeburn 5287: }
1.867 raeburn 5288: }
1.937 raeburn 5289: if ($hidepriv) {
1.1219 raeburn 5290: my @privroles = ('dc','su');
1.999 raeburn 5291: if ($context eq 'userroles') {
1.1219 raeburn 5292: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5293: } else {
1.1219 raeburn 5294: my $possdoms = [$domain];
5295: if (ref($roledoms) eq 'ARRAY') {
5296: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5297: }
1.1219 raeburn 5298: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5299: if (!$nothide{$username.':'.$domain}) {
5300: next;
5301: }
5302: }
1.937 raeburn 5303: }
5304: }
1.933 raeburn 5305: if ($withsec) {
5306: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5307: $tstart.':'.$tend;
5308: } else {
5309: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5310: }
1.832 raeburn 5311: }
1.373 www 5312: return %returnhash;
1.399 www 5313: }
5314:
1.1333 raeburn 5315: sub get_all_adhocroles {
5316: my ($dom) = @_;
5317: my @roles_by_num = ();
5318: my %domdefaults = &get_domain_defaults($dom);
5319: my (%description,%access_in_dom,%access_info);
5320: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5321: my $count = 0;
5322: my %domcurrent = %{$domdefaults{'adhocroles'}};
5323: my %ordered;
5324: foreach my $role (sort(keys(%domcurrent))) {
5325: my ($order,$desc,$access_in_dom);
5326: if (ref($domcurrent{$role}) eq 'HASH') {
5327: $order = $domcurrent{$role}{'order'};
5328: $desc = $domcurrent{$role}{'desc'};
5329: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5330: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5331: }
5332: if ($order eq '') {
5333: $order = $count;
5334: }
5335: $ordered{$order} = $role;
5336: if ($desc ne '') {
5337: $description{$role} = $desc;
5338: } else {
5339: $description{$role}= $role;
5340: }
5341: $count++;
5342: }
5343: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5344: push(@roles_by_num,$ordered{$item});
5345: }
5346: }
5347: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5348: }
5349:
1.1332 raeburn 5350: sub get_my_adhocroles {
1.1333 raeburn 5351: my ($cid,$checkreg) = @_;
5352: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5353: if ($env{'request.course.id'} eq $cid) {
5354: $cdom = $env{'course.'.$cid.'.domain'};
5355: $cnum = $env{'course.'.$cid.'.num'};
5356: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5357: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5358: $cdom = $1;
5359: $cnum = $2;
5360: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5361: $cdom,$cnum);
5362: }
5363: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5364: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5365: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5366: if ($rosterhash{$user} ne '') {
5367: my $type = (split(/:/,$rosterhash{$user}))[5];
5368: return ([],{}) if ($type eq 'auto');
5369: }
5370: }
5371: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5372: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5373: my $then=$env{'user.login.time'};
5374: my $update=$env{'user.update.time'};
1.1335 raeburn 5375: if (!$update) {
5376: $update = $then;
5377: }
5378: my @liveroles;
1.1334 raeburn 5379: foreach my $role ('dh','da') {
5380: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5381: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5382: my $limit = $update;
5383: if ($env{'request.role'} eq "$role./$cdom/") {
5384: $limit = $then;
5385: }
1.1335 raeburn 5386: my $activerole = 1;
5387: if ($tstart && $tstart>$limit) { $activerole = 0; }
5388: if ($tend && $tend <$limit) { $activerole = 0; }
5389: if ($activerole) {
5390: push(@liveroles,$role);
5391: }
1.1334 raeburn 5392: }
1.1332 raeburn 5393: }
1.1335 raeburn 5394: if (@liveroles) {
1.1332 raeburn 5395: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5396: my ($accessref,$accessinfo,%access_in_dom);
5397: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5398: if (ref($roles_by_num) eq 'ARRAY') {
5399: if (@{$roles_by_num}) {
1.1332 raeburn 5400: my %settings;
5401: if ($env{'request.course.id'} eq $cid) {
5402: foreach my $envkey (keys(%env)) {
5403: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5404: $settings{$1} = $env{$envkey};
5405: }
5406: }
5407: } else {
5408: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5409: }
5410: my %setincrs;
5411: if ($settings{'internal.adhocaccess'}) {
5412: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5413: }
5414: my @statuses;
5415: if ($env{'environment.inststatus'}) {
5416: @statuses = split(/,/,$env{'environment.inststatus'});
5417: }
5418: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5419: if (ref($accessref) eq 'HASH') {
5420: %access_in_dom = %{$accessref};
5421: }
5422: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5423: my ($curraccess,@okstatus,@personnel);
5424: if ($setincrs{$role}) {
5425: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5426: if ($curraccess eq 'status') {
5427: @okstatus = split(/\&/,$rest);
5428: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5429: @personnel = split(/\&/,$rest);
5430: }
5431: } else {
5432: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5433: if (ref($accessinfo) eq 'HASH') {
5434: if ($curraccess eq 'status') {
5435: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5436: @okstatus = @{$accessinfo->{$role}};
5437: }
5438: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5439: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5440: @personnel = @{$accessinfo->{$role}};
5441: }
1.1332 raeburn 5442: }
5443: }
5444: }
5445: if ($curraccess eq 'none') {
5446: next;
5447: } elsif ($curraccess eq 'all') {
5448: push(@possroles,$role);
1.1336 raeburn 5449: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5450: if (grep(/^dh$/,@liveroles)) {
5451: push(@possroles,$role);
5452: } else {
5453: next;
5454: }
1.1336 raeburn 5455: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5456: if (grep(/^da$/,@liveroles)) {
5457: push(@possroles,$role);
5458: } else {
5459: next;
5460: }
1.1332 raeburn 5461: } elsif ($curraccess eq 'status') {
5462: if (@okstatus) {
5463: if (!@statuses) {
5464: if (grep(/^default$/,@okstatus)) {
5465: push(@possroles,$role);
5466: }
5467: } else {
5468: foreach my $status (@okstatus) {
5469: if (grep(/^\Q$status\E$/,@statuses)) {
5470: push(@possroles,$role);
5471: last;
5472: }
5473: }
5474: }
5475: }
5476: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5477: if (grep(/^\Q$user\E$/,@personnel)) {
5478: if ($curraccess eq 'exc') {
5479: push(@possroles,$role);
5480: }
5481: } elsif ($curraccess eq 'inc') {
5482: push(@possroles,$role);
5483: }
5484: }
5485: }
5486: }
5487: }
5488: }
5489: }
5490: }
5491: }
1.1333 raeburn 5492: unless (ref($description) eq 'HASH') {
5493: if (ref($roles_by_num) eq 'ARRAY') {
5494: my %desc;
5495: map { $desc{$_} = $_; } (@{$roles_by_num});
5496: $description = \%desc;
5497: } else {
5498: $description = {};
5499: }
5500: }
5501: return (\@possroles,$description);
1.1332 raeburn 5502: }
5503:
1.399 www 5504: # ----------------------------------------------------- Frontpage Announcements
5505: #
5506: #
5507:
5508: sub postannounce {
5509: my ($server,$text)=@_;
1.844 albertel 5510: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5511: unless ($text=~/\w/) { $text=''; }
5512: return &reply('setannounce:'.&escape($text),$server);
5513: }
5514:
5515: sub getannounce {
1.448 albertel 5516:
1.1359 raeburn 5517: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5518: my $announcement='';
1.800 albertel 5519: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5520: close($fh);
1.399 www 5521: if ($announcement=~/\w/) {
5522: return
5523: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5524: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5525: } else {
5526: return '';
5527: }
5528: } else {
5529: return '';
5530: }
1.351 www 5531: }
1.353 www 5532:
5533: # ---------------------------------------------------------- Course ID routines
5534: # Deal with domain's nohist_courseid.db files
5535: #
5536:
5537: sub courseidput {
1.921 raeburn 5538: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5539: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5540: my $outcome;
5541: if ($caller eq 'timeonly') {
5542: my $cids = '';
5543: foreach my $item (keys(%$storehash)) {
5544: $cids.=&escape($item).'&';
5545: }
5546: $cids=~s/\&$//;
5547: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5548: $coursehome);
5549: } else {
5550: my $items = '';
5551: foreach my $item (keys(%$storehash)) {
5552: $items.= &escape($item).'='.
5553: &freeze_escape($$storehash{$item}).'&';
5554: }
5555: $items=~s/\&$//;
5556: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5557: $coursehome);
1.918 raeburn 5558: }
5559: if ($outcome eq 'unknown_cmd') {
5560: my $what;
5561: foreach my $cid (keys(%$storehash)) {
5562: $what .= &escape($cid).'=';
1.921 raeburn 5563: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5564: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5565: }
5566: $what =~ s/\:$/&/;
5567: }
5568: $what =~ s/\&$//;
5569: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5570: } else {
5571: return $outcome;
5572: }
1.353 www 5573: }
5574:
5575: sub courseiddump {
1.921 raeburn 5576: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5577: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5578: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5579: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5580: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5581: my $as_hash = 1;
5582: my %returnhash;
5583: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5584: my %libserv = &all_library();
5585: foreach my $tryserver (keys(%libserv)) {
5586: if ( ( $hostidflag == 1
5587: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5588: || (!defined($hostidflag)) ) {
5589:
1.918 raeburn 5590: if (($domfilter eq '') ||
5591: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5592: my $rep;
5593: if (grep { $_ eq $tryserver } current_machine_ids()) {
5594: $rep = LONCAPA::Lond::dump_course_id_handler(
5595: join(":", (&host_domain($tryserver), $sincefilter,
5596: &escape($descfilter), &escape($instcodefilter),
5597: &escape($ownerfilter), &escape($coursefilter),
5598: &escape($typefilter), &escape($regexp_ok),
5599: $as_hash, &escape($selfenrollonly),
5600: &escape($catfilter), $showhidden, $caller,
5601: &escape($cloner), &escape($cc_clone), $cloneonly,
5602: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5603: &escape($creationcontext),$domcloner,$hasuniquecode,
5604: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5605: } else {
5606: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5607: $sincefilter.':'.&escape($descfilter).':'.
5608: &escape($instcodefilter).':'.&escape($ownerfilter).
5609: ':'.&escape($coursefilter).':'.&escape($typefilter).
5610: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5611: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5612: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5613: &escape($cc_clone).':'.$cloneonly.':'.
5614: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5615: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5616: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5617: }
5618:
1.918 raeburn 5619: my @pairs=split(/\&/,$rep);
5620: foreach my $item (@pairs) {
5621: my ($key,$value)=split(/\=/,$item,2);
5622: $key = &unescape($key);
5623: next if ($key =~ /^error: 2 /);
5624: my $result = &thaw_unescape($value);
5625: if (ref($result) eq 'HASH') {
5626: $returnhash{$key}=$result;
5627: } else {
1.921 raeburn 5628: my @responses = split(/:/,$value);
5629: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5630: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5631: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5632: }
1.1008 raeburn 5633: }
1.353 www 5634: }
5635: }
5636: }
5637: }
5638: return %returnhash;
5639: }
5640:
1.1055 raeburn 5641: sub courselastaccess {
5642: my ($cdom,$cnum,$hostidref) = @_;
5643: my %returnhash;
5644: if ($cdom && $cnum) {
5645: my $chome = &homeserver($cnum,$cdom);
5646: if ($chome ne 'no_host') {
5647: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5648: &extract_lastaccess(\%returnhash,$rep);
5649: }
5650: } else {
5651: if (!$cdom) { $cdom=''; }
5652: my %libserv = &all_library();
5653: foreach my $tryserver (keys(%libserv)) {
5654: if (ref($hostidref) eq 'ARRAY') {
5655: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5656: }
5657: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5658: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5659: &extract_lastaccess(\%returnhash,$rep);
5660: }
5661: }
5662: }
5663: return %returnhash;
5664: }
5665:
5666: sub extract_lastaccess {
5667: my ($returnhash,$rep) = @_;
5668: if (ref($returnhash) eq 'HASH') {
5669: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5670: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5671: $rep eq '') {
5672: my @pairs=split(/\&/,$rep);
5673: foreach my $item (@pairs) {
5674: my ($key,$value)=split(/\=/,$item,2);
5675: $key = &unescape($key);
5676: next if ($key =~ /^error: 2 /);
5677: $returnhash->{$key} = &thaw_unescape($value);
5678: }
5679: }
5680: }
5681: return;
5682: }
5683:
1.658 raeburn 5684: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5685:
5686: sub dcmailput {
1.685 raeburn 5687: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5688: my $status = &Apache::lonnet::critical(
1.740 www 5689: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5690: &escape($message),$server);
1.662 raeburn 5691: return $status;
5692: }
5693:
1.658 raeburn 5694: sub dcmaildump {
5695: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5696: my %returnhash=();
1.846 albertel 5697:
5698: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5699: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5700: &escape($enddate).':';
5701: my @esc_senders=map { &escape($_)} @$senders;
5702: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5703: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5704: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5705: if (($key) && ($value)) {
5706: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5707: }
5708: }
5709: }
5710: return %returnhash;
5711: }
1.662 raeburn 5712: # ---------------------------------------------------------- Domain roles
5713:
5714: sub get_domain_roles {
5715: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5716: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5717: $startdate = '.';
5718: }
1.1018 raeburn 5719: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5720: $enddate = '.';
5721: }
1.922 raeburn 5722: my $rolelist;
5723: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5724: $rolelist = join('&',@{$roles});
1.922 raeburn 5725: }
1.662 raeburn 5726: my %personnel = ();
1.841 albertel 5727:
5728: my %servers = &get_servers($dom,'library');
5729: foreach my $tryserver (keys(%servers)) {
5730: %{$personnel{$tryserver}}=();
5731: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5732: &escape($startdate).':'.
5733: &escape($enddate).':'.
5734: &escape($rolelist), $tryserver))) {
5735: my ($key,$value) = split(/\=/,$line,2);
5736: if (($key) && ($value)) {
5737: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5738: }
5739: }
1.662 raeburn 5740: }
5741: return %personnel;
5742: }
1.658 raeburn 5743:
1.1332 raeburn 5744: sub get_active_domroles {
5745: my ($dom,$roles) = @_;
5746: return () unless (ref($roles) eq 'ARRAY');
5747: my $now = time;
5748: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5749: my %domroles;
5750: foreach my $server (keys(%dompersonnel)) {
5751: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5752: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5753: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5754: }
5755: }
5756: return %domroles;
5757: }
5758:
1.1057 www 5759: # ----------------------------------------------------------- Interval timing
1.149 www 5760:
1.1153 www 5761: {
5762: # Caches needed for speedup of navmaps
5763: # We don't want to cache this for very long at all (5 seconds at most)
5764: #
5765: # The user for whom we cache
5766: my $cachedkey='';
5767: # The cached times for this user
5768: my %cachedtimes=();
5769: # When this was last done
1.1282 raeburn 5770: my $cachedtime='';
1.1153 www 5771:
5772: sub load_all_first_access {
1.1308 raeburn 5773: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5774: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5775: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5776: (!$ignorecache)) {
1.1154 raeburn 5777: return;
5778: }
5779: $cachedtime=time;
5780: $cachedkey=$uname.':'.$udom;
5781: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5782: }
5783:
1.504 albertel 5784: sub get_first_access {
1.1308 raeburn 5785: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5786: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5787: if ($argsymb) { $symb=$argsymb; }
5788: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5789: if ($argmap) { $map = $argmap; }
1.926 albertel 5790: if ($type eq 'course') {
5791: $res='course';
5792: } elsif ($type eq 'map') {
1.588 albertel 5793: $res=&symbread($map);
5794: } else {
5795: $res=$symb;
5796: }
1.1308 raeburn 5797: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5798: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5799: }
5800:
5801: sub set_first_access {
1.1162 raeburn 5802: my ($type,$interval)=@_;
1.790 albertel 5803: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5804: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5805: if ($type eq 'course') {
5806: $res='course';
5807: } elsif ($type eq 'map') {
1.588 albertel 5808: $res=&symbread($map);
5809: } else {
5810: $res=$symb;
5811: }
1.1153 www 5812: $cachedkey='';
1.1162 raeburn 5813: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5814: if ($firstaccess) {
5815: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5816: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5817: "in $courseid");
1.1386 raeburn 5818: return 'already_set';
5819: } else {
1.1162 raeburn 5820: my $start = time;
5821: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5822: $udom,$uname);
5823: if ($putres eq 'ok') {
5824: &put('timerinterval',{"$courseid\0$res"=>$interval},
5825: $udom,$uname);
5826: &appenv(
5827: {
5828: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5829: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5830: }
5831: );
1.1365 raeburn 5832: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5833: $cachedtimes{"$courseid\0$res"} = $start;
5834: }
1.1386 raeburn 5835: } elsif ($putres ne 'refused') {
5836: &logthis("Result: $putres when attempting to set first access time ".
5837: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5838: }
5839: return $putres;
1.505 albertel 5840: }
5841: return 'already_set';
1.504 albertel 5842: }
1.1153 www 5843: }
1.1282 raeburn 5844:
1.110 www 5845: # --------------------------------------------- Set Expire Date for Spreadsheet
5846:
5847: sub expirespread {
5848: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5849: my $cid=$env{'request.course.id'};
1.110 www 5850: if ($cid) {
5851: my $now=time;
5852: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5853: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5854: $env{'course.'.$cid.'.num'}.
1.110 www 5855: ':nohist_expirationdates:'.
5856: &escape($key).'='.$now,
1.620 albertel 5857: $env{'course.'.$cid.'.home'})
1.110 www 5858: }
5859: return 'ok';
1.14 www 5860: }
5861:
1.109 www 5862: # ----------------------------------------------------- Devalidate Spreadsheets
5863:
5864: sub devalidate {
1.325 www 5865: my ($symb,$uname,$udom)=@_;
1.620 albertel 5866: my $cid=$env{'request.course.id'};
1.109 www 5867: if ($cid) {
1.391 matthew 5868: # delete the stored spreadsheets for
5869: # - the student level sheet of this user in course's homespace
5870: # - the assessment level sheet for this resource
5871: # for this user in user's homespace
1.553 albertel 5872: # - current conditional state info
1.325 www 5873: my $key=$uname.':'.$udom.':';
1.109 www 5874: my $status=
1.299 matthew 5875: &del('nohist_calculatedsheets',
1.391 matthew 5876: [$key.'studentcalc:'],
1.620 albertel 5877: $env{'course.'.$cid.'.domain'},
5878: $env{'course.'.$cid.'.num'})
1.133 albertel 5879: .' '.
5880: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5881: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5882: unless ($status eq 'ok ok') {
5883: &logthis('Could not devalidate spreadsheet '.
1.325 www 5884: $uname.' at '.$udom.' for '.
1.109 www 5885: $symb.': '.$status);
1.133 albertel 5886: }
1.553 albertel 5887: &delenv('user.state.'.$cid);
1.109 www 5888: }
5889: }
5890:
1.265 albertel 5891: sub get_scalar {
5892: my ($string,$end) = @_;
5893: my $value;
5894: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5895: $value = $1;
5896: } elsif ($$string =~ s/^([^&]*?)&//) {
5897: $value = $1;
5898: }
5899: return &unescape($value);
5900: }
5901:
5902: sub array2str {
5903: my (@array) = @_;
5904: my $result=&arrayref2str(\@array);
5905: $result=~s/^__ARRAY_REF__//;
5906: $result=~s/__END_ARRAY_REF__$//;
5907: return $result;
5908: }
5909:
1.204 albertel 5910: sub arrayref2str {
5911: my ($arrayref) = @_;
1.265 albertel 5912: my $result='__ARRAY_REF__';
1.204 albertel 5913: foreach my $elem (@$arrayref) {
1.265 albertel 5914: if(ref($elem) eq 'ARRAY') {
5915: $result.=&arrayref2str($elem).'&';
5916: } elsif(ref($elem) eq 'HASH') {
5917: $result.=&hashref2str($elem).'&';
5918: } elsif(ref($elem)) {
5919: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5920: } else {
5921: $result.=&escape($elem).'&';
5922: }
5923: }
5924: $result=~s/\&$//;
1.265 albertel 5925: $result .= '__END_ARRAY_REF__';
1.204 albertel 5926: return $result;
5927: }
5928:
1.168 albertel 5929: sub hash2str {
1.204 albertel 5930: my (%hash) = @_;
5931: my $result=&hashref2str(\%hash);
1.265 albertel 5932: $result=~s/^__HASH_REF__//;
5933: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5934: return $result;
5935: }
5936:
5937: sub hashref2str {
5938: my ($hashref)=@_;
1.265 albertel 5939: my $result='__HASH_REF__';
1.800 albertel 5940: foreach my $key (sort(keys(%$hashref))) {
5941: if (ref($key) eq 'ARRAY') {
5942: $result.=&arrayref2str($key).'=';
5943: } elsif (ref($key) eq 'HASH') {
5944: $result.=&hashref2str($key).'=';
5945: } elsif (ref($key)) {
1.265 albertel 5946: $result.='=';
1.800 albertel 5947: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5948: } else {
1.1132 raeburn 5949: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5950: }
5951:
1.800 albertel 5952: if(ref($hashref->{$key}) eq 'ARRAY') {
5953: $result.=&arrayref2str($hashref->{$key}).'&';
5954: } elsif(ref($hashref->{$key}) eq 'HASH') {
5955: $result.=&hashref2str($hashref->{$key}).'&';
5956: } elsif(ref($hashref->{$key})) {
1.265 albertel 5957: $result.='&';
1.800 albertel 5958: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5959: } else {
1.800 albertel 5960: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5961: }
5962: }
1.168 albertel 5963: $result=~s/\&$//;
1.265 albertel 5964: $result .= '__END_HASH_REF__';
1.168 albertel 5965: return $result;
5966: }
5967:
5968: sub str2hash {
1.265 albertel 5969: my ($string)=@_;
5970: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5971: return %$hash;
5972: }
5973:
5974: sub str2hashref {
1.168 albertel 5975: my ($string) = @_;
1.265 albertel 5976:
5977: my %hash;
5978:
5979: if($string !~ /^__HASH_REF__/) {
5980: if (! ($string eq '' || !defined($string))) {
5981: $hash{'error'}='Not hash reference';
5982: }
5983: return (\%hash, $string);
5984: }
5985:
5986: $string =~ s/^__HASH_REF__//;
5987:
5988: while($string !~ /^__END_HASH_REF__/) {
5989: #key
5990: my $key='';
5991: if($string =~ /^__HASH_REF__/) {
5992: ($key, $string)=&str2hashref($string);
5993: if(defined($key->{'error'})) {
5994: $hash{'error'}='Bad data';
5995: return (\%hash, $string);
5996: }
5997: } elsif($string =~ /^__ARRAY_REF__/) {
5998: ($key, $string)=&str2arrayref($string);
5999: if($key->[0] eq 'Array reference error') {
6000: $hash{'error'}='Bad data';
6001: return (\%hash, $string);
6002: }
6003: } else {
6004: $string =~ s/^(.*?)=//;
1.267 albertel 6005: $key=&unescape($1);
1.265 albertel 6006: }
6007: $string =~ s/^=//;
6008:
6009: #value
6010: my $value='';
6011: if($string =~ /^__HASH_REF__/) {
6012: ($value, $string)=&str2hashref($string);
6013: if(defined($value->{'error'})) {
6014: $hash{'error'}='Bad data';
6015: return (\%hash, $string);
6016: }
6017: } elsif($string =~ /^__ARRAY_REF__/) {
6018: ($value, $string)=&str2arrayref($string);
6019: if($value->[0] eq 'Array reference error') {
6020: $hash{'error'}='Bad data';
6021: return (\%hash, $string);
6022: }
6023: } else {
6024: $value=&get_scalar(\$string,'__END_HASH_REF__');
6025: }
6026: $string =~ s/^&//;
6027:
6028: $hash{$key}=$value;
1.204 albertel 6029: }
1.265 albertel 6030:
6031: $string =~ s/^__END_HASH_REF__//;
6032:
6033: return (\%hash, $string);
1.204 albertel 6034: }
6035:
6036: sub str2array {
1.265 albertel 6037: my ($string)=@_;
6038: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6039: return @$array;
6040: }
6041:
6042: sub str2arrayref {
1.204 albertel 6043: my ($string) = @_;
1.265 albertel 6044: my @array;
6045:
6046: if($string !~ /^__ARRAY_REF__/) {
6047: if (! ($string eq '' || !defined($string))) {
6048: $array[0]='Array reference error';
6049: }
6050: return (\@array, $string);
6051: }
6052:
6053: $string =~ s/^__ARRAY_REF__//;
6054:
6055: while($string !~ /^__END_ARRAY_REF__/) {
6056: my $value='';
6057: if($string =~ /^__HASH_REF__/) {
6058: ($value, $string)=&str2hashref($string);
6059: if(defined($value->{'error'})) {
6060: $array[0] ='Array reference error';
6061: return (\@array, $string);
6062: }
6063: } elsif($string =~ /^__ARRAY_REF__/) {
6064: ($value, $string)=&str2arrayref($string);
6065: if($value->[0] eq 'Array reference error') {
6066: $array[0] ='Array reference error';
6067: return (\@array, $string);
6068: }
6069: } else {
6070: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6071: }
6072: $string =~ s/^&//;
6073:
6074: push(@array, $value);
1.191 harris41 6075: }
1.265 albertel 6076:
6077: $string =~ s/^__END_ARRAY_REF__//;
6078:
6079: return (\@array, $string);
1.168 albertel 6080: }
6081:
1.167 albertel 6082: # -------------------------------------------------------------------Temp Store
6083:
1.168 albertel 6084: sub tmpreset {
6085: my ($symb,$namespace,$domain,$stuname) = @_;
6086: if (!$symb) {
6087: $symb=&symbread();
1.620 albertel 6088: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6089: }
6090: $symb=escape($symb);
6091:
1.620 albertel 6092: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6093: $namespace=~s/\//\_/g;
6094: $namespace=~s/\W//g;
6095:
1.620 albertel 6096: if (!$domain) { $domain=$env{'user.domain'}; }
6097: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6098: if ($domain eq 'public' && $stuname eq 'public') {
6099: $stuname=$ENV{'REMOTE_ADDR'};
6100: }
1.1117 foxr 6101: my $path=LONCAPA::tempdir();
1.168 albertel 6102: my %hash;
6103: if (tie(%hash,'GDBM_File',
6104: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6105: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6106: foreach my $key (keys(%hash)) {
1.180 albertel 6107: if ($key=~ /:$symb/) {
1.168 albertel 6108: delete($hash{$key});
6109: }
6110: }
6111: }
6112: }
6113:
1.167 albertel 6114: sub tmpstore {
1.168 albertel 6115: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6116:
6117: if (!$symb) {
6118: $symb=&symbread();
1.620 albertel 6119: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6120: }
6121: $symb=escape($symb);
6122:
6123: if (!$namespace) {
6124: # I don't think we would ever want to store this for a course.
6125: # it seems this will only be used if we don't have a course.
1.620 albertel 6126: #$namespace=$env{'request.course.id'};
1.168 albertel 6127: #if (!$namespace) {
1.620 albertel 6128: $namespace=$env{'request.state'};
1.168 albertel 6129: #}
6130: }
6131: $namespace=~s/\//\_/g;
6132: $namespace=~s/\W//g;
1.620 albertel 6133: if (!$domain) { $domain=$env{'user.domain'}; }
6134: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6135: if ($domain eq 'public' && $stuname eq 'public') {
6136: $stuname=$ENV{'REMOTE_ADDR'};
6137: }
1.168 albertel 6138: my $now=time;
6139: my %hash;
1.1117 foxr 6140: my $path=LONCAPA::tempdir();
1.168 albertel 6141: if (tie(%hash,'GDBM_File',
6142: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6143: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6144: $hash{"version:$symb"}++;
6145: my $version=$hash{"version:$symb"};
6146: my $allkeys='';
6147: foreach my $key (keys(%$storehash)) {
6148: $allkeys.=$key.':';
1.591 albertel 6149: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6150: }
6151: $hash{"$version:$symb:timestamp"}=$now;
6152: $allkeys.='timestamp';
6153: $hash{"$version:keys:$symb"}=$allkeys;
6154: if (untie(%hash)) {
6155: return 'ok';
6156: } else {
6157: return "error:$!";
6158: }
6159: } else {
6160: return "error:$!";
6161: }
6162: }
1.167 albertel 6163:
1.168 albertel 6164: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6165:
1.168 albertel 6166: sub tmprestore {
6167: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6168:
1.168 albertel 6169: if (!$symb) {
6170: $symb=&symbread();
1.620 albertel 6171: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6172: }
6173: $symb=escape($symb);
6174:
1.620 albertel 6175: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6176:
1.620 albertel 6177: if (!$domain) { $domain=$env{'user.domain'}; }
6178: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6179: if ($domain eq 'public' && $stuname eq 'public') {
6180: $stuname=$ENV{'REMOTE_ADDR'};
6181: }
1.168 albertel 6182: my %returnhash;
6183: $namespace=~s/\//\_/g;
6184: $namespace=~s/\W//g;
6185: my %hash;
1.1117 foxr 6186: my $path=LONCAPA::tempdir();
1.168 albertel 6187: if (tie(%hash,'GDBM_File',
6188: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6189: &GDBM_READER(),0640)) {
1.168 albertel 6190: my $version=$hash{"version:$symb"};
6191: $returnhash{'version'}=$version;
6192: my $scope;
6193: for ($scope=1;$scope<=$version;$scope++) {
6194: my $vkeys=$hash{"$scope:keys:$symb"};
6195: my @keys=split(/:/,$vkeys);
6196: my $key;
6197: $returnhash{"$scope:keys"}=$vkeys;
6198: foreach $key (@keys) {
1.591 albertel 6199: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6200: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6201: }
6202: }
1.168 albertel 6203: if (!(untie(%hash))) {
6204: return "error:$!";
6205: }
6206: } else {
6207: return "error:$!";
6208: }
6209: return %returnhash;
1.167 albertel 6210: }
6211:
1.9 www 6212: # ----------------------------------------------------------------------- Store
6213:
6214: sub store {
1.1269 raeburn 6215: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6216: my $home='';
6217:
1.168 albertel 6218: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6219:
1.213 www 6220: $symb=&symbclean($symb);
1.122 albertel 6221: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6222:
1.620 albertel 6223: if (!$domain) { $domain=$env{'user.domain'}; }
6224: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6225:
6226: &devalidate($symb,$stuname,$domain);
1.109 www 6227:
6228: $symb=escape($symb);
1.187 www 6229: if (!$namespace) {
1.620 albertel 6230: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6231: return '';
6232: }
6233: }
1.620 albertel 6234: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6235:
6236: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6237: $$storehash{'host'}=$perlvar{'lonHostID'};
6238:
1.12 www 6239: my $namevalue='';
1.800 albertel 6240: foreach my $key (keys(%$storehash)) {
6241: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6242: }
1.12 www 6243: $namevalue=~s/\&$//;
1.187 www 6244: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6245: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6246: }
6247:
1.47 www 6248: # -------------------------------------------------------------- Critical Store
6249:
6250: sub cstore {
1.1269 raeburn 6251: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6252: my $home='';
6253:
1.168 albertel 6254: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6255:
1.213 www 6256: $symb=&symbclean($symb);
1.122 albertel 6257: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6258:
1.620 albertel 6259: if (!$domain) { $domain=$env{'user.domain'}; }
6260: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6261:
6262: &devalidate($symb,$stuname,$domain);
1.109 www 6263:
6264: $symb=escape($symb);
1.187 www 6265: if (!$namespace) {
1.620 albertel 6266: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6267: return '';
6268: }
6269: }
1.620 albertel 6270: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6271:
6272: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6273: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6274:
1.47 www 6275: my $namevalue='';
1.800 albertel 6276: foreach my $key (keys(%$storehash)) {
6277: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6278: }
1.47 www 6279: $namevalue=~s/\&$//;
1.187 www 6280: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6281: return critical
1.1269 raeburn 6282: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6283: }
6284:
1.9 www 6285: # --------------------------------------------------------------------- Restore
6286:
6287: sub restore {
1.124 www 6288: my ($symb,$namespace,$domain,$stuname) = @_;
6289: my $home='';
6290:
1.168 albertel 6291: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6292:
1.122 albertel 6293: if (!$symb) {
1.1224 raeburn 6294: return if ($namespace eq 'courserequests');
6295: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6296: } else {
1.1224 raeburn 6297: unless ($namespace eq 'courserequests') {
6298: $symb=&escape(&symbclean($symb));
6299: }
1.122 albertel 6300: }
1.188 www 6301: if (!$namespace) {
1.620 albertel 6302: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6303: return '';
6304: }
6305: }
1.620 albertel 6306: if (!$domain) { $domain=$env{'user.domain'}; }
6307: if (!$stuname) { $stuname=$env{'user.name'}; }
6308: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6309: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6310:
1.12 www 6311: my %returnhash=();
1.800 albertel 6312: foreach my $line (split(/\&/,$answer)) {
6313: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6314: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6315: }
1.75 www 6316: my $version;
6317: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6318: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6319: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6320: }
1.75 www 6321: }
1.13 www 6322: return %returnhash;
1.34 www 6323: }
6324:
6325: # ---------------------------------------------------------- Course Description
1.1118 foxr 6326: #
6327: #
1.34 www 6328:
6329: sub coursedescription {
1.731 albertel 6330: my ($courseid,$args)=@_;
1.34 www 6331: $courseid=~s/^\///;
1.49 www 6332: $courseid=~s/\_/\//g;
1.34 www 6333: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6334: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6335: my $normalid=$cdomain.'_'.$cnum;
6336: # need to always cache even if we get errors otherwise we keep
6337: # trying and trying and trying to get the course description.
6338: my %envhash=();
6339: my %returnhash=();
1.731 albertel 6340:
6341: my $expiretime=600;
6342: if ($env{'request.course.id'} eq $normalid) {
6343: $expiretime=120;
6344: }
6345:
6346: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6347: if (!$args->{'freshen_cache'}
6348: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6349: foreach my $key (keys(%env)) {
6350: next if ($key !~ /^\Q$prefix\E(.*)/);
6351: my ($setting) = $1;
6352: $returnhash{$setting} = $env{$key};
6353: }
6354: return %returnhash;
6355: }
6356:
1.1118 foxr 6357: # get the data again
6358:
1.731 albertel 6359: if (!$args->{'one_time'}) {
6360: $envhash{'course.'.$normalid.'.last_cache'}=time;
6361: }
1.811 albertel 6362:
1.34 www 6363: if ($chome ne 'no_host') {
1.302 albertel 6364: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6365: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6366: my $username = $env{'user.name'}; # Defult username
6367: if(defined $args->{'user'}) {
6368: $username = $args->{'user'};
6369: }
1.129 albertel 6370: $returnhash{'home'}= $chome;
6371: $returnhash{'domain'} = $cdomain;
6372: $returnhash{'num'} = $cnum;
1.741 raeburn 6373: if (!defined($returnhash{'type'})) {
6374: $returnhash{'type'} = 'Course';
6375: }
1.130 albertel 6376: while (my ($name,$value) = each %returnhash) {
1.53 www 6377: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6378: }
1.270 www 6379: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6380: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6381: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6382: $envhash{'course.'.$normalid.'.home'}=$chome;
6383: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6384: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6385: }
6386: }
1.731 albertel 6387: if (!$args->{'one_time'}) {
1.949 raeburn 6388: &appenv(\%envhash);
1.731 albertel 6389: }
1.302 albertel 6390: return %returnhash;
1.461 www 6391: }
6392:
1.1080 raeburn 6393: sub update_released_required {
6394: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6395: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6396: $cid = $env{'request.course.id'};
6397: $cdom = $env{'course.'.$cid.'.domain'};
6398: $cnum = $env{'course.'.$cid.'.num'};
6399: $chome = $env{'course.'.$cid.'.home'};
6400: }
6401: if ($needsrelease) {
6402: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6403: my $needsupdate;
6404: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6405: $needsupdate = 1;
6406: } else {
6407: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6408: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6409: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6410: $needsupdate = 1;
6411: }
6412: }
6413: if ($needsupdate) {
6414: my %needshash = (
6415: 'internal.releaserequired' => $needsrelease,
6416: );
6417: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6418: if ($putresult eq 'ok') {
6419: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6420: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6421: if (ref($crsinfo{$cid}) eq 'HASH') {
6422: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6423: &courseidput($cdom,\%crsinfo,$chome,'notime');
6424: }
6425: }
6426: }
6427: }
6428: return;
6429: }
6430:
1.461 www 6431: # -------------------------------------------------See if a user is privileged
6432:
6433: sub privileged {
1.1219 raeburn 6434: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6435: my $now = time;
1.1219 raeburn 6436: my $roles;
6437: if (ref($possroles) eq 'ARRAY') {
6438: $roles = $possroles;
6439: } else {
6440: $roles = ['dc','su'];
6441: }
6442: if (ref($possdomains) eq 'ARRAY') {
6443: my %privileged = &privileged_by_domain($possdomains,$roles);
6444: foreach my $dom (@{$possdomains}) {
6445: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6446: (ref($privileged{$dom}) eq 'HASH')) {
6447: foreach my $role (@{$roles}) {
6448: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6449: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6450: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6451: return 1 unless (($end && $end < $now) ||
6452: ($start && $start > $now));
6453: }
6454: }
6455: }
6456: }
6457: }
6458: } else {
6459: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6460: my $now = time;
1.1170 droeschl 6461:
1.1275 musolffc 6462: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6463: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6464: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6465: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6466: or ($tstart && $tstart > $now);
1.1170 droeschl 6467: }
1.1219 raeburn 6468: }
6469: }
6470: return 0;
6471: }
1.1170 droeschl 6472:
1.1219 raeburn 6473: sub privileged_by_domain {
6474: my ($domains,$roles) = @_;
6475: my %privileged = ();
6476: my $cachetime = 60*60*24;
6477: my $now = time;
6478: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6479: return %privileged;
6480: }
6481: foreach my $dom (@{$domains}) {
6482: next if (ref($privileged{$dom}) eq 'HASH');
6483: my $needroles;
6484: foreach my $role (@{$roles}) {
6485: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6486: if (defined($cached)) {
6487: if (ref($result) eq 'HASH') {
6488: $privileged{$dom}{$role} = $result;
6489: }
6490: } else {
6491: $needroles = 1;
6492: }
6493: }
6494: if ($needroles) {
6495: my %dompersonnel = &get_domain_roles($dom,$roles);
6496: $privileged{$dom} = {};
6497: foreach my $server (keys(%dompersonnel)) {
6498: if (ref($dompersonnel{$server}) eq 'HASH') {
6499: foreach my $item (keys(%{$dompersonnel{$server}})) {
6500: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6501: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6502: next if ($end && $end < $now);
6503: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6504: $dompersonnel{$server}{$item};
6505: }
6506: }
6507: }
6508: if (ref($privileged{$dom}) eq 'HASH') {
6509: foreach my $role (@{$roles}) {
6510: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6511: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6512: } else {
6513: my %hash = ();
6514: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6515: }
6516: }
6517: }
6518: }
6519: }
6520: return %privileged;
1.9 www 6521: }
1.1 albertel 6522:
1.103 harris41 6523: # -------------------------------------------------------- Get user privileges
1.11 www 6524:
6525: sub rolesinit {
1.1169 droeschl 6526: my ($domain, $username) = @_;
6527: my %userroles = ('user.login.time' => time);
6528: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6529:
6530: # firstaccess and timerinterval are related to timed maps/resources.
6531: # also, blocking can be triggered by an activating timer
6532: # it's saved in the user's %env.
6533: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6534: my %timerinterval = &dump('timerinterval', $domain, $username);
6535: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6536: %timerintchk, %timerintenv);
6537:
1.1162 raeburn 6538: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6539: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6540: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6541: }
1.1169 droeschl 6542:
1.1162 raeburn 6543: foreach my $key (keys(%timerinterval)) {
6544: my ($cid,$rest) = split(/\0/,$key);
6545: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6546: }
1.1169 droeschl 6547:
1.11 www 6548: my %allroles=();
1.1162 raeburn 6549: my %allgroups=();
1.11 www 6550:
1.1274 raeburn 6551: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6552: my $role = $rolesdump{$area};
6553: $area =~ s/\_\w\w$//;
6554:
6555: my ($trole, $tend, $tstart, $group_privs);
6556:
6557: if ($role =~ /^cr/) {
6558: # Custom role, defined by a user
6559: # e.g., user.role.cr/msu/smith/mynewrole
6560: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6561: $trole = $1;
6562: ($tend, $tstart) = split('_', $2);
6563: } else {
6564: $trole = $role;
6565: }
6566: } elsif ($role =~ m|^gr/|) {
6567: # Role of member in a group, defined within a course/community
6568: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6569: ($trole, $tend, $tstart) = split(/_/, $role);
6570: next if $tstart eq '-1';
6571: ($trole, $group_privs) = split(/\//, $trole);
6572: $group_privs = &unescape($group_privs);
6573: } else {
6574: # Just a normal role, defined in roles.tab
6575: ($trole, $tend, $tstart) = split(/_/,$role);
6576: }
6577:
6578: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6579: $username);
6580: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6581:
6582: # role expired or not available yet?
6583: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6584: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6585:
6586: next if $area eq '' or $trole eq '';
6587:
6588: my $spec = "$trole.$area";
6589: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6590:
6591: if ($trole =~ /^cr\//) {
6592: # Custom role, defined by a user
6593: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6594: } elsif ($trole eq 'gr') {
6595: # Role of a member in a group, defined within a course/community
6596: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6597: next;
6598: } else {
6599: # Normal role, defined in roles.tab
6600: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6601: }
6602:
6603: my $cid = $tdomain.'_'.$trest;
6604: unless ($firstaccchk{$cid}) {
6605: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6606: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6607: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6608: $coursetimerstarts{$cid}{$item};
6609: }
6610: }
6611: $firstaccchk{$cid} = 1;
6612: }
6613: unless ($timerintchk{$cid}) {
6614: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6615: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6616: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6617: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6618: }
1.12 www 6619: }
1.1169 droeschl 6620: $timerintchk{$cid} = 1;
1.191 harris41 6621: }
1.11 www 6622: }
1.1169 droeschl 6623:
1.1341 raeburn 6624: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6625: \%allroles, \%allgroups);
1.1169 droeschl 6626: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6627: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6628:
1.1162 raeburn 6629: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6630: }
6631:
1.567 raeburn 6632: sub set_arearole {
1.1215 raeburn 6633: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6634: unless ($nolog) {
1.567 raeburn 6635: # log the associated role with the area
1.1215 raeburn 6636: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6637: }
1.743 albertel 6638: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6639: }
6640:
6641: sub custom_roleprivs {
6642: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6643: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6644: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6645: if (&hostname($homsvr) ne '') {
1.567 raeburn 6646: my ($rdummy,$roledef)=
6647: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6648: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6649: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6650: if (defined($syspriv)) {
1.1043 raeburn 6651: if ($trest =~ /^$match_community$/) {
6652: $syspriv =~ s/bre\&S//;
6653: }
1.567 raeburn 6654: $$allroles{'cm./'}.=':'.$syspriv;
6655: $$allroles{$spec.'./'}.=':'.$syspriv;
6656: }
6657: if ($tdomain ne '') {
6658: if (defined($dompriv)) {
6659: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6660: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6661: }
6662: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6663: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6664: my $rolename = $1;
6665: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6666: }
1.567 raeburn 6667: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6668: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6669: }
6670: }
6671: }
6672: }
6673: }
6674:
1.1332 raeburn 6675: sub course_adhocrole_privs {
6676: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6677: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6678: if ($overrides{"internal.adhocpriv.$rolename"}) {
6679: my (%currprivs,%storeprivs);
6680: foreach my $item (split(/:/,$coursepriv)) {
6681: my ($priv,$restrict) = split(/\&/,$item);
6682: $currprivs{$priv} = $restrict;
6683: }
6684: my (%possadd,%possremove,%full);
6685: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6686: my ($priv,$restrict)=split(/\&/,$item);
6687: $full{$priv} = $restrict;
6688: }
6689: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6690: next if ($item eq '');
6691: my ($rule,$rest) = split(/=/,$item);
6692: next unless (($rule eq 'off') || ($rule eq 'on'));
6693: foreach my $priv (split(/:/,$rest)) {
6694: if ($priv ne '') {
6695: if ($rule eq 'off') {
6696: $possremove{$priv} = 1;
6697: } else {
6698: $possadd{$priv} = 1;
6699: }
6700: }
6701: }
6702: }
6703: foreach my $priv (sort(keys(%full))) {
6704: if (exists($currprivs{$priv})) {
6705: unless (exists($possremove{$priv})) {
6706: $storeprivs{$priv} = $currprivs{$priv};
6707: }
6708: } elsif (exists($possadd{$priv})) {
6709: $storeprivs{$priv} = $full{$priv};
6710: }
6711: }
6712: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6713: }
6714: return $coursepriv;
6715: }
6716:
1.678 raeburn 6717: sub group_roleprivs {
6718: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6719: my $access = 1;
6720: my $now = time;
6721: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6722: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6723: if ($access) {
1.811 albertel 6724: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6725: $$allgroups{$course}{$group} .=':'.$group_privs;
6726: }
6727: }
1.567 raeburn 6728:
6729: sub standard_roleprivs {
6730: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6731: if (defined($pr{$trole.':s'})) {
6732: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6733: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6734: }
6735: if ($tdomain ne '') {
6736: if (defined($pr{$trole.':d'})) {
6737: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6738: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6739: }
6740: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6741: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6742: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6743: }
6744: }
6745: }
6746:
6747: sub set_userprivs {
1.1064 raeburn 6748: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6749: my $author=0;
6750: my $adv=0;
1.1341 raeburn 6751: my $rar=0;
1.678 raeburn 6752: my %grouproles = ();
6753: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6754: my @groupkeys;
1.1000 raeburn 6755: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6756: push(@groupkeys,$role);
6757: }
6758: if (ref($groups_roles) eq 'HASH') {
6759: foreach my $key (keys(%{$groups_roles})) {
6760: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6761: push(@groupkeys,$key);
6762: }
6763: }
6764: }
6765: if (@groupkeys > 0) {
6766: foreach my $role (@groupkeys) {
6767: my ($trole,$area,$sec,$extendedarea);
6768: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6769: $trole = $1;
6770: $area = $2;
6771: $sec = $3;
6772: $extendedarea = $area.$sec;
6773: if (exists($$allgroups{$area})) {
6774: foreach my $group (keys(%{$$allgroups{$area}})) {
6775: my $spec = $trole.'.'.$extendedarea;
6776: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6777: $$allgroups{$area}{$group};
1.1064 raeburn 6778: }
1.678 raeburn 6779: }
6780: }
6781: }
6782: }
6783: }
1.800 albertel 6784: foreach my $group (keys(%grouproles)) {
6785: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6786: }
1.800 albertel 6787: foreach my $role (keys(%{$allroles})) {
6788: my %thesepriv;
1.941 raeburn 6789: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6790: foreach my $item (split(/:/,$$allroles{$role})) {
6791: if ($item ne '') {
6792: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6793: if ($restrictions eq '') {
6794: $thesepriv{$privilege}='F';
6795: } elsif ($thesepriv{$privilege} ne 'F') {
6796: $thesepriv{$privilege}.=$restrictions;
6797: }
6798: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6799: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6800: }
6801: }
6802: my $thesestr='';
1.1104 raeburn 6803: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6804: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6805: }
6806: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6807: }
1.1341 raeburn 6808: return ($author,$adv,$rar);
1.567 raeburn 6809: }
6810:
1.994 raeburn 6811: sub role_status {
1.1104 raeburn 6812: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6813: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6814: my ($one,$two) = split(m{\./},$rolekey,2);
6815: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6816: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6817: $$where = '/'.$two;
1.994 raeburn 6818: $$trolecode=$$role.'.'.$$where;
6819: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6820: $$tstatus='is';
1.1104 raeburn 6821: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6822: $$tstatus='future';
1.1034 raeburn 6823: if ($$tstart<$now) {
6824: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6825: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6826: my (%allroles,%allgroups,$group_privs,
6827: %groups_roles,@rolecodes);
1.1002 raeburn 6828: my %userroles = (
6829: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6830: );
1.1064 raeburn 6831: @rolecodes = ('cm');
1.1002 raeburn 6832: my $spec=$$role.'.'.$$where;
6833: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6834: if ($$role =~ /^cr\//) {
6835: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6836: push(@rolecodes,'cr');
1.1002 raeburn 6837: } elsif ($$role eq 'gr') {
1.1064 raeburn 6838: push(@rolecodes,$$role);
1.1002 raeburn 6839: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6840: $env{'user.name'});
1.1064 raeburn 6841: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6842: (undef,my $group_privs) = split(/\//,$trole);
6843: $group_privs = &unescape($group_privs);
6844: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6845: 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 6846: &get_groups_roles($tdomain,$trest,
6847: \%course_roles,\@rolecodes,
6848: \%groups_roles);
1.1002 raeburn 6849: } else {
1.1064 raeburn 6850: push(@rolecodes,$$role);
1.1002 raeburn 6851: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6852: }
1.1341 raeburn 6853: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6854: \%groups_roles);
1.1064 raeburn 6855: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6856: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6857: }
6858: }
1.1034 raeburn 6859: $$tstatus = 'is';
1.1002 raeburn 6860: }
1.994 raeburn 6861: }
6862: if ($$tend) {
1.1104 raeburn 6863: if ($$tend<$update) {
1.994 raeburn 6864: $$tstatus='expired';
6865: } elsif ($$tend<$now) {
6866: $$tstatus='will_not';
6867: }
6868: }
6869: }
6870: }
6871: }
6872:
1.1104 raeburn 6873: sub get_groups_roles {
6874: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6875: return unless((ref($cdom_courseroles) eq 'HASH') &&
6876: (ref($rolecodes) eq 'ARRAY') &&
6877: (ref($groups_roles) eq 'HASH'));
6878: if (keys(%{$cdom_courseroles}) > 0) {
6879: my ($cnum) = ($rest =~ /^($match_courseid)/);
6880: if ($cdom ne '' && $cnum ne '') {
6881: foreach my $key (keys(%{$cdom_courseroles})) {
6882: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6883: my $crsrole = $1;
6884: my $crssec = $2;
6885: if ($crsrole =~ /^cr/) {
6886: unless (grep(/^cr$/,@{$rolecodes})) {
6887: push(@{$rolecodes},'cr');
6888: }
6889: } else {
6890: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6891: push(@{$rolecodes},$crsrole);
6892: }
6893: }
6894: my $rolekey = "$crsrole./$cdom/$cnum";
6895: if ($crssec ne '') {
6896: $rolekey .= "/$crssec";
6897: }
6898: $rolekey .= './';
6899: $groups_roles->{$rolekey} = $rolecodes;
6900: }
6901: }
6902: }
6903: }
6904: return;
6905: }
6906:
6907: sub delete_env_groupprivs {
6908: my ($where,$courseroles,$possroles) = @_;
6909: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6910: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6911: unless (ref($courseroles->{$udom}) eq 'HASH') {
6912: %{$courseroles->{$udom}} =
6913: &get_my_roles('','','userroles',['active'],
6914: $possroles,[$udom],1);
6915: }
6916: if (ref($courseroles->{$udom}) eq 'HASH') {
6917: foreach my $item (keys(%{$courseroles->{$udom}})) {
6918: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6919: my $area = '/'.$cdom.'/'.$cnum;
6920: my $privkey = "user.priv.$crsrole.$area";
6921: if ($crssec ne '') {
6922: $privkey .= '/'.$crssec;
6923: }
6924: $privkey .= ".$area/$group";
6925: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6926: }
6927: }
6928: return;
6929: }
6930:
1.994 raeburn 6931: sub check_adhoc_privs {
1.1329 raeburn 6932: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6933: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6934: if ($sec) {
6935: $cckey .= '/'.$sec;
6936: }
1.1185 raeburn 6937: my $setprivs;
1.994 raeburn 6938: if ($env{$cckey}) {
6939: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6940: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6941: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6942: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6943: $setprivs = 1;
1.994 raeburn 6944: }
6945: } else {
1.1330 raeburn 6946: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6947: $setprivs = 1;
1.994 raeburn 6948: }
1.1185 raeburn 6949: return $setprivs;
1.994 raeburn 6950: }
6951:
6952: sub set_adhoc_privileges {
1.1326 raeburn 6953: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6954: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6955: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6956: if ($sec ne '') {
6957: $area .= '/'.$sec;
6958: }
1.994 raeburn 6959: my $spec = $role.'.'.$area;
6960: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6961: $env{'user.name'},1);
1.1326 raeburn 6962: my %rolehash = ();
1.1332 raeburn 6963: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6964: my $rolename = $1;
1.1326 raeburn 6965: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6966: my %domdef = &get_domain_defaults($dcdom);
6967: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6968: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6969: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6970: }
6971: }
1.1326 raeburn 6972: } else {
6973: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6974: }
1.1341 raeburn 6975: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6976: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6977: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 6978: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
6979: ($caller eq 'tiny')) {
1.1088 raeburn 6980: &appenv( {'request.role' => $spec,
6981: 'request.role.domain' => $dcdom,
1.1332 raeburn 6982: 'request.course.sec' => $sec,
1.1088 raeburn 6983: }
6984: );
6985: my $tadv=0;
6986: if (&allowed('adv') eq 'F') { $tadv=1; }
6987: &appenv({'request.role.adv' => $tadv});
6988: }
1.994 raeburn 6989: }
6990:
1.12 www 6991: # --------------------------------------------------------------- get interface
6992:
6993: sub get {
1.131 albertel 6994: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6995: my $items='';
1.800 albertel 6996: foreach my $item (@$storearr) {
6997: $items.=&escape($item).'&';
1.191 harris41 6998: }
1.12 www 6999: $items=~s/\&$//;
1.620 albertel 7000: if (!$udomain) { $udomain=$env{'user.domain'}; }
7001: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7002: my $uhome=&homeserver($uname,$udomain);
7003:
1.133 albertel 7004: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7005: my @pairs=split(/\&/,$rep);
1.273 albertel 7006: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7007: return @pairs;
7008: }
1.15 www 7009: my %returnhash=();
1.42 www 7010: my $i=0;
1.800 albertel 7011: foreach my $item (@$storearr) {
7012: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7013: $i++;
1.191 harris41 7014: }
1.15 www 7015: return %returnhash;
1.27 www 7016: }
7017:
7018: # --------------------------------------------------------------- del interface
7019:
7020: sub del {
1.133 albertel 7021: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7022: my $items='';
1.800 albertel 7023: foreach my $item (@$storearr) {
7024: $items.=&escape($item).'&';
1.191 harris41 7025: }
1.984 neumanie 7026:
1.27 www 7027: $items=~s/\&$//;
1.620 albertel 7028: if (!$udomain) { $udomain=$env{'user.domain'}; }
7029: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7030: my $uhome=&homeserver($uname,$udomain);
7031: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7032: }
7033:
7034: # -------------------------------------------------------------- dump interface
7035:
1.1180 droeschl 7036: sub unserialize {
7037: my ($rep, $escapedkeys) = @_;
7038:
7039: return {} if $rep =~ /^error/;
7040:
7041: my %returnhash=();
1.1252 raeburn 7042: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7043: my ($key, $value) = split(/=/, $item, 2);
7044: $key = unescape($key) unless $escapedkeys;
7045: next if $key =~ /^error: 2 /;
1.1252 raeburn 7046: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7047: }
7048: #return %returnhash;
7049: return \%returnhash;
7050: }
7051:
7052: # see Lond::dump_with_regexp
7053: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7054: sub dump {
1.1180 droeschl 7055: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 7056: if (!$udomain) { $udomain=$env{'user.domain'}; }
7057: if (!$uname) { $uname=$env{'user.name'}; }
7058: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7059:
1.1266 raeburn 7060: if ($regexp) {
7061: $regexp=&escape($regexp);
7062: } else {
7063: $regexp='.';
7064: }
1.1180 droeschl 7065: if (grep { $_ eq $uhome } current_machine_ids()) {
7066: # user is hosted on this machine
1.1266 raeburn 7067: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7068: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7069: return %{unserialize($reply, $escapedkeys)};
7070: }
1.1166 raeburn 7071: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 7072: my @pairs=split(/\&/,$rep);
7073: my %returnhash=();
1.1098 foxr 7074: if (!($rep =~ /^error/ )) {
7075: foreach my $item (@pairs) {
7076: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7077: $key = unescape($key) unless $escapedkeys;
7078: #$key = &unescape($key);
1.1098 foxr 7079: next if ($key =~ /^error: 2 /);
7080: $returnhash{$key}=&thaw_unescape($value);
7081: }
1.755 albertel 7082: }
7083: return %returnhash;
1.407 www 7084: }
7085:
1.1098 foxr 7086:
1.717 albertel 7087: # --------------------------------------------------------- dumpstore interface
7088:
7089: sub dumpstore {
7090: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7091: # same as dump but keys must be escaped. They may contain colon separated
7092: # lists of values that may themself contain colons (e.g. symbs).
7093: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7094: }
7095:
1.407 www 7096: # -------------------------------------------------------------- keys interface
7097:
7098: sub getkeys {
7099: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7100: if (!$udomain) { $udomain=$env{'user.domain'}; }
7101: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7102: my $uhome=&homeserver($uname,$udomain);
7103: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7104: my @keyarray=();
1.800 albertel 7105: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7106: next if ($key =~ /^error: 2 /);
1.800 albertel 7107: push(@keyarray,&unescape($key));
1.407 www 7108: }
7109: return @keyarray;
1.318 matthew 7110: }
7111:
1.319 matthew 7112: # --------------------------------------------------------------- currentdump
7113: sub currentdump {
1.328 matthew 7114: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7115: $courseid = $env{'request.course.id'} if (! defined($courseid));
7116: $sdom = $env{'user.domain'} if (! defined($sdom));
7117: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7118: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7119: my $rep;
7120:
7121: if (grep { $_ eq $uhome } current_machine_ids()) {
7122: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7123: $courseid)));
7124: } else {
7125: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7126: }
7127:
1.318 matthew 7128: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7129: #
1.318 matthew 7130: my %returnhash=();
1.319 matthew 7131: #
1.1343 raeburn 7132: if ($rep eq 'unknown_cmd') {
1.319 matthew 7133: # an old lond will not know currentdump
7134: # Do a dump and make it look like a currentdump
1.822 albertel 7135: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7136: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7137: my %hash = @tmp;
7138: @tmp=();
1.424 matthew 7139: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7140: } else {
7141: my @pairs=split(/\&/,$rep);
1.800 albertel 7142: foreach my $pair (@pairs) {
7143: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7144: my ($symb,$param) = split(/:/,$key);
7145: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7146: &thaw_unescape($value);
1.319 matthew 7147: }
1.191 harris41 7148: }
1.12 www 7149: return %returnhash;
1.424 matthew 7150: }
7151:
7152: sub convert_dump_to_currentdump{
7153: my %hash = %{shift()};
7154: my %returnhash;
7155: # Code ripped from lond, essentially. The only difference
7156: # here is the unescaping done by lonnet::dump(). Conceivably
7157: # we might run in to problems with parameter names =~ /^v\./
7158: while (my ($key,$value) = each(%hash)) {
7159: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7160: $symb = &unescape($symb);
7161: $param = &unescape($param);
1.424 matthew 7162: next if ($v eq 'version' || $symb eq 'keys');
7163: next if (exists($returnhash{$symb}) &&
7164: exists($returnhash{$symb}->{$param}) &&
7165: $returnhash{$symb}->{'v.'.$param} > $v);
7166: $returnhash{$symb}->{$param}=$value;
7167: $returnhash{$symb}->{'v.'.$param}=$v;
7168: }
7169: #
7170: # Remove all of the keys in the hashes which keep track of
7171: # the version of the parameter.
7172: while (my ($symb,$param_hash) = each(%returnhash)) {
7173: # use a foreach because we are going to delete from the hash.
7174: foreach my $key (keys(%$param_hash)) {
7175: delete($param_hash->{$key}) if ($key =~ /^v\./);
7176: }
7177: }
7178: return \%returnhash;
1.12 www 7179: }
7180:
1.627 albertel 7181: # ------------------------------------------------------ critical inc interface
7182:
7183: sub cinc {
7184: return &inc(@_,'critical');
7185: }
7186:
1.449 matthew 7187: # --------------------------------------------------------------- inc interface
7188:
7189: sub inc {
1.627 albertel 7190: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7191: if (!$udomain) { $udomain=$env{'user.domain'}; }
7192: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7193: my $uhome=&homeserver($uname,$udomain);
7194: my $items='';
7195: if (! ref($store)) {
7196: # got a single value, so use that instead
7197: $items = &escape($store).'=&';
7198: } elsif (ref($store) eq 'SCALAR') {
7199: $items = &escape($$store).'=&';
7200: } elsif (ref($store) eq 'ARRAY') {
7201: $items = join('=&',map {&escape($_);} @{$store});
7202: } elsif (ref($store) eq 'HASH') {
7203: while (my($key,$value) = each(%{$store})) {
7204: $items.= &escape($key).'='.&escape($value).'&';
7205: }
7206: }
7207: $items=~s/\&$//;
1.627 albertel 7208: if ($critical) {
7209: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7210: } else {
7211: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7212: }
1.449 matthew 7213: }
7214:
1.12 www 7215: # --------------------------------------------------------------- put interface
7216:
7217: sub put {
1.134 albertel 7218: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7219: if (!$udomain) { $udomain=$env{'user.domain'}; }
7220: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7221: my $uhome=&homeserver($uname,$udomain);
1.12 www 7222: my $items='';
1.800 albertel 7223: foreach my $item (keys(%$storehash)) {
7224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7225: }
1.12 www 7226: $items=~s/\&$//;
1.134 albertel 7227: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7228: }
7229:
1.631 albertel 7230: # ------------------------------------------------------------ newput interface
7231:
7232: sub newput {
7233: my ($namespace,$storehash,$udomain,$uname)=@_;
7234: if (!$udomain) { $udomain=$env{'user.domain'}; }
7235: if (!$uname) { $uname=$env{'user.name'}; }
7236: my $uhome=&homeserver($uname,$udomain);
7237: my $items='';
7238: foreach my $key (keys(%$storehash)) {
7239: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7240: }
7241: $items=~s/\&$//;
7242: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7243: }
7244:
7245: # --------------------------------------------------------- putstore interface
7246:
1.524 raeburn 7247: sub putstore {
1.1269 raeburn 7248: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7249: if (!$udomain) { $udomain=$env{'user.domain'}; }
7250: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7251: my $uhome=&homeserver($uname,$udomain);
7252: my $items='';
1.715 albertel 7253: foreach my $key (keys(%$storehash)) {
7254: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7255: }
1.715 albertel 7256: $items=~s/\&$//;
1.716 albertel 7257: my $esc_symb=&escape($symb);
7258: my $esc_v=&escape($version);
1.715 albertel 7259: my $reply =
1.716 albertel 7260: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7261: $uhome);
1.1269 raeburn 7262: if (($tolog) && ($reply eq 'ok')) {
7263: my $namevalue='';
7264: foreach my $key (keys(%{$storehash})) {
7265: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7266: }
7267: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7268: '&host='.&escape($perlvar{'lonHostID'}).
7269: '&version='.$esc_v.
7270: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7271: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7272: }
1.715 albertel 7273: if ($reply eq 'unknown_cmd') {
1.716 albertel 7274: # gfall back to way things use to be done
1.715 albertel 7275: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7276: $uname);
1.524 raeburn 7277: }
1.715 albertel 7278: return $reply;
7279: }
7280:
7281: sub old_putstore {
1.716 albertel 7282: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7283: if (!$udomain) { $udomain=$env{'user.domain'}; }
7284: if (!$uname) { $uname=$env{'user.name'}; }
7285: my $uhome=&homeserver($uname,$udomain);
7286: my %newstorehash;
1.800 albertel 7287: foreach my $item (keys(%$storehash)) {
7288: my $key = $version.':'.&escape($symb).':'.$item;
7289: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7290: }
7291: my $items='';
7292: my %allitems = ();
1.800 albertel 7293: foreach my $item (keys(%newstorehash)) {
7294: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7295: my $key = $1.':keys:'.$2;
7296: $allitems{$key} .= $3.':';
7297: }
1.800 albertel 7298: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7299: }
1.800 albertel 7300: foreach my $item (keys(%allitems)) {
7301: $allitems{$item} =~ s/\:$//;
7302: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7303: }
7304: $items=~s/\&$//;
7305: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7306: }
7307:
1.47 www 7308: # ------------------------------------------------------ critical put interface
7309:
7310: sub cput {
1.134 albertel 7311: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7312: if (!$udomain) { $udomain=$env{'user.domain'}; }
7313: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7314: my $uhome=&homeserver($uname,$udomain);
1.47 www 7315: my $items='';
1.800 albertel 7316: foreach my $item (keys(%$storehash)) {
7317: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7318: }
1.47 www 7319: $items=~s/\&$//;
1.134 albertel 7320: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7321: }
7322:
7323: # -------------------------------------------------------------- eget interface
7324:
7325: sub eget {
1.133 albertel 7326: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7327: my $items='';
1.800 albertel 7328: foreach my $item (@$storearr) {
7329: $items.=&escape($item).'&';
1.191 harris41 7330: }
1.12 www 7331: $items=~s/\&$//;
1.620 albertel 7332: if (!$udomain) { $udomain=$env{'user.domain'}; }
7333: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7334: my $uhome=&homeserver($uname,$udomain);
7335: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7336: my @pairs=split(/\&/,$rep);
7337: my %returnhash=();
1.42 www 7338: my $i=0;
1.800 albertel 7339: foreach my $item (@$storearr) {
7340: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7341: $i++;
1.191 harris41 7342: }
1.12 www 7343: return %returnhash;
7344: }
7345:
1.667 albertel 7346: # ------------------------------------------------------------ tmpput interface
7347: sub tmpput {
1.802 raeburn 7348: my ($storehash,$server,$context)=@_;
1.667 albertel 7349: my $items='';
1.800 albertel 7350: foreach my $item (keys(%$storehash)) {
7351: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7352: }
7353: $items=~s/\&$//;
1.802 raeburn 7354: if (defined($context)) {
7355: $items .= ':'.&escape($context);
7356: }
1.667 albertel 7357: return &reply("tmpput:$items",$server);
7358: }
7359:
7360: # ------------------------------------------------------------ tmpget interface
7361: sub tmpget {
1.688 albertel 7362: my ($token,$server)=@_;
7363: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7364: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7365: my %returnhash;
1.1328 raeburn 7366: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7367: return %returnhash;
7368: }
1.667 albertel 7369: foreach my $item (split(/\&/,$rep)) {
7370: my ($key,$value)=split(/=/,$item);
7371: $returnhash{&unescape($key)}=&thaw_unescape($value);
7372: }
7373: return %returnhash;
7374: }
7375:
1.1113 raeburn 7376: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7377: sub tmpdel {
7378: my ($token,$server)=@_;
7379: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7380: return &reply("tmpdel:$token",$server);
7381: }
7382:
1.1198 raeburn 7383: # ------------------------------------------------------------ get_timebased_id
7384:
7385: sub get_timebased_id {
7386: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7387: $maxtries) = @_;
7388: my ($newid,$error,$dellock);
7389: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7390: return ('','ok','invalid call to get suffix');
7391: }
7392:
7393: # set defaults for any optional args for which values were not supplied
7394: if ($who eq '') {
7395: $who = $env{'user.name'}.':'.$env{'user.domain'};
7396: }
7397: if (!$locktries) {
7398: $locktries = 3;
7399: }
7400: if (!$maxtries) {
7401: $maxtries = 10;
7402: }
7403:
7404: if (($cdom eq '') || ($cnum eq '')) {
7405: if ($env{'request.course.id'}) {
7406: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7407: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7408: }
7409: if (($cdom eq '') || ($cnum eq '')) {
7410: return ('','ok','call to get suffix not in course context');
7411: }
7412: }
7413:
7414: # construct locking item
7415: my $lockhash = {
7416: $prefix."\0".'locked_'.$keyid => $who,
7417: };
7418: my $tries = 0;
7419:
7420: # attempt to get lock on nohist_$namespace file
7421: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7422: while (($gotlock ne 'ok') && $tries <$locktries) {
7423: $tries ++;
7424: sleep 1;
7425: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7426: }
7427:
7428: # attempt to get unique identifier, based on current timestamp
7429: if ($gotlock eq 'ok') {
7430: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7431: my $id = time;
7432: $newid = $id;
1.1268 raeburn 7433: if ($idtype eq 'addcode') {
7434: $newid .= &sixnum_code();
7435: }
1.1198 raeburn 7436: my $idtries = 0;
7437: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7438: if ($idtype eq 'concat') {
7439: $newid = $id.$idtries;
1.1268 raeburn 7440: } elsif ($idtype eq 'addcode') {
7441: $newid = $newid.&sixnum_code();
1.1198 raeburn 7442: } else {
7443: $newid ++;
7444: }
7445: $idtries ++;
7446: }
7447: if (!exists($inuse{$prefix."\0".$newid})) {
7448: my %new_item = (
7449: $prefix."\0".$newid => $who,
7450: );
7451: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7452: $cdom,$cnum);
7453: if ($putresult ne 'ok') {
7454: undef($newid);
7455: $error = 'error saving new item: '.$putresult;
7456: }
7457: } else {
1.1268 raeburn 7458: undef($newid);
1.1198 raeburn 7459: $error = ('error: no unique suffix available for the new item ');
7460: }
7461: # remove lock
7462: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7463: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7464: } else {
7465: $error = "error: could not obtain lockfile\n";
7466: $dellock = 'ok';
1.1276 raeburn 7467: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7468: $dellock = 'nolock';
7469: }
1.1198 raeburn 7470: }
7471: return ($newid,$dellock,$error);
7472: }
7473:
1.1268 raeburn 7474: sub sixnum_code {
7475: my $code;
7476: for (0..6) {
7477: $code .= int( rand(9) );
7478: }
7479: return $code;
7480: }
7481:
1.765 albertel 7482: # -------------------------------------------------- portfolio access checking
7483:
7484: sub portfolio_access {
1.1270 raeburn 7485: my ($requrl,$clientip) = @_;
1.765 albertel 7486: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7487: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7488: if ($result) {
7489: my %setters;
7490: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7491: my ($startblock,$endblock) =
7492: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7493: if ($startblock && $endblock) {
7494: return 'B';
7495: }
7496: } else {
7497: my ($startblock,$endblock) =
7498: &Apache::loncommon::blockcheck(\%setters,'port');
7499: if ($startblock && $endblock) {
7500: return 'B';
7501: }
7502: }
7503: }
1.765 albertel 7504: if ($result eq 'ok') {
1.766 albertel 7505: return 'F';
1.765 albertel 7506: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7507: return 'A';
1.765 albertel 7508: }
1.766 albertel 7509: return '';
1.765 albertel 7510: }
7511:
7512: sub get_portfolio_access {
1.1270 raeburn 7513: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7514:
7515: if (!ref($access_hash)) {
7516: my $current_perms = &get_portfile_permissions($udom,$unum);
7517: my %access_controls = &get_access_controls($current_perms,$group,
7518: $file_name);
7519: $access_hash = $access_controls{$file_name};
7520: }
7521:
1.1270 raeburn 7522: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7523: my $now = time;
7524: if (ref($access_hash) eq 'HASH') {
7525: foreach my $key (keys(%{$access_hash})) {
7526: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7527: if ($start > $now) {
7528: next;
7529: }
7530: if ($end && $end<$now) {
7531: next;
7532: }
7533: if ($scope eq 'public') {
7534: $public = $key;
7535: last;
7536: } elsif ($scope eq 'guest') {
7537: $guest = $key;
7538: } elsif ($scope eq 'domains') {
7539: push(@domains,$key);
7540: } elsif ($scope eq 'users') {
7541: push(@users,$key);
7542: } elsif ($scope eq 'course') {
7543: push(@courses,$key);
7544: } elsif ($scope eq 'group') {
7545: push(@groups,$key);
1.1270 raeburn 7546: } elsif ($scope eq 'ip') {
7547: push(@ips,$key);
1.765 albertel 7548: }
7549: }
7550: if ($public) {
7551: return 'ok';
1.1270 raeburn 7552: } elsif (@ips > 0) {
7553: my $allowed;
7554: foreach my $ipkey (@ips) {
7555: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7556: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7557: $allowed = 1;
7558: last;
7559: }
7560: }
7561: }
7562: if ($allowed) {
7563: return 'ok';
7564: }
1.765 albertel 7565: }
7566: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7567: if ($guest) {
7568: return $guest;
7569: }
7570: } else {
7571: if (@domains > 0) {
7572: foreach my $domkey (@domains) {
7573: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7574: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7575: return 'ok';
7576: }
7577: }
7578: }
7579: }
7580: if (@users > 0) {
7581: foreach my $userkey (@users) {
1.865 raeburn 7582: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7583: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7584: if (ref($item) eq 'HASH') {
7585: if (($item->{'uname'} eq $env{'user.name'}) &&
7586: ($item->{'udom'} eq $env{'user.domain'})) {
7587: return 'ok';
7588: }
7589: }
7590: }
7591: }
1.765 albertel 7592: }
7593: }
7594: my %roleshash;
7595: my @courses_and_groups = @courses;
7596: push(@courses_and_groups,@groups);
7597: if (@courses_and_groups > 0) {
7598: my (%allgroups,%allroles);
7599: my ($start,$end,$role,$sec,$group);
7600: foreach my $envkey (%env) {
1.1060 raeburn 7601: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7602: my $cid = $2.'_'.$3;
7603: if ($1 eq 'gr') {
7604: $group = $4;
7605: $allgroups{$cid}{$group} = $env{$envkey};
7606: } else {
7607: if ($4 eq '') {
7608: $sec = 'none';
7609: } else {
7610: $sec = $4;
7611: }
7612: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7613: }
1.811 albertel 7614: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7615: my $cid = $2.'_'.$3;
7616: if ($4 eq '') {
7617: $sec = 'none';
7618: } else {
7619: $sec = $4;
7620: }
7621: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7622: }
7623: }
7624: if (keys(%allroles) == 0) {
7625: return;
7626: }
7627: foreach my $key (@courses_and_groups) {
7628: my %content = %{$$access_hash{$key}};
7629: my $cnum = $content{'number'};
7630: my $cdom = $content{'domain'};
7631: my $cid = $cdom.'_'.$cnum;
7632: if (!exists($allroles{$cid})) {
7633: next;
7634: }
7635: foreach my $role_id (keys(%{$content{'roles'}})) {
7636: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7637: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7638: my @status = @{$content{'roles'}{$role_id}{'access'}};
7639: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7640: foreach my $role (keys(%{$allroles{$cid}})) {
7641: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7642: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7643: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7644: if (grep/^all$/,@sections) {
7645: return 'ok';
7646: } else {
7647: if (grep/^$sec$/,@sections) {
7648: return 'ok';
7649: }
7650: }
7651: }
7652: }
7653: if (keys(%{$allgroups{$cid}}) == 0) {
7654: if (grep/^none$/,@groups) {
7655: return 'ok';
7656: }
7657: } else {
7658: if (grep/^all$/,@groups) {
7659: return 'ok';
7660: }
7661: foreach my $group (keys(%{$allgroups{$cid}})) {
7662: if (grep/^$group$/,@groups) {
7663: return 'ok';
7664: }
7665: }
7666: }
7667: }
7668: }
7669: }
7670: }
7671: }
7672: if ($guest) {
7673: return $guest;
7674: }
7675: }
7676: }
7677: return;
7678: }
7679:
7680: sub course_group_datechecker {
7681: my ($dates,$now,$status) = @_;
7682: my ($start,$end) = split(/\./,$dates);
7683: if (!$start && !$end) {
7684: return 'ok';
7685: }
7686: if (grep/^active$/,@{$status}) {
7687: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7688: return 'ok';
7689: }
7690: }
7691: if (grep/^previous$/,@{$status}) {
7692: if ($end > $now ) {
7693: return 'ok';
7694: }
7695: }
7696: if (grep/^future$/,@{$status}) {
7697: if ($start > $now) {
7698: return 'ok';
7699: }
7700: }
7701: return;
7702: }
7703:
7704: sub parse_portfolio_url {
7705: my ($url) = @_;
7706:
7707: my ($type,$udom,$unum,$group,$file_name);
7708:
1.823 albertel 7709: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7710: $type = 1;
7711: $udom = $1;
7712: $unum = $2;
7713: $file_name = $3;
1.823 albertel 7714: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7715: $type = 2;
7716: $udom = $1;
7717: $unum = $2;
7718: $group = $3;
7719: $file_name = $3.'/'.$4;
7720: }
7721: if (wantarray) {
7722: return ($type,$udom,$unum,$file_name,$group);
7723: }
7724: return $type;
7725: }
7726:
7727: sub is_portfolio_url {
7728: my ($url) = @_;
7729: return scalar(&parse_portfolio_url($url));
7730: }
7731:
1.798 raeburn 7732: sub is_portfolio_file {
7733: my ($file) = @_;
1.820 raeburn 7734: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7735: return 1;
7736: }
7737: return;
7738: }
7739:
1.976 raeburn 7740: sub usertools_access {
1.1084 raeburn 7741: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7742: my ($access,%tools);
7743: if ($context eq '') {
7744: $context = 'tools';
7745: }
7746: if ($context eq 'requestcourses') {
7747: %tools = (
7748: official => 1,
7749: unofficial => 1,
1.1006 raeburn 7750: community => 1,
1.1246 raeburn 7751: textbook => 1,
1.1305 raeburn 7752: placement => 1,
1.1368 raeburn 7753: lti => 1,
1.985 raeburn 7754: );
1.1183 raeburn 7755: } elsif ($context eq 'requestauthor') {
7756: %tools = (
7757: requestauthor => 1,
7758: );
1.985 raeburn 7759: } else {
7760: %tools = (
7761: aboutme => 1,
7762: blog => 1,
1.1177 raeburn 7763: webdav => 1,
1.985 raeburn 7764: portfolio => 1,
7765: );
7766: }
1.976 raeburn 7767: return if (!defined($tools{$tool}));
7768:
1.1242 raeburn 7769: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7770: $udom = $env{'user.domain'};
7771: $uname = $env{'user.name'};
7772: }
7773:
1.978 raeburn 7774: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7775: if ($action ne 'reload') {
1.985 raeburn 7776: if ($context eq 'requestcourses') {
7777: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7778: } elsif ($context eq 'requestauthor') {
7779: return $env{'environment.canrequest.author'};
1.985 raeburn 7780: } else {
7781: return $env{'environment.availabletools.'.$tool};
7782: }
7783: }
1.976 raeburn 7784: }
7785:
1.1183 raeburn 7786: my ($toolstatus,$inststatus,$envkey);
7787: if ($context eq 'requestauthor') {
7788: $envkey = $context;
7789: } else {
7790: $envkey = $context.'.'.$tool;
7791: }
1.976 raeburn 7792:
1.985 raeburn 7793: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7794: ($action ne 'reload')) {
1.1183 raeburn 7795: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7796: $inststatus = $env{'environment.inststatus'};
7797: } else {
1.1084 raeburn 7798: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7799: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7800: $inststatus = $userenvref->{'inststatus'};
7801: } else {
1.1183 raeburn 7802: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7803: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7804: $inststatus = $userenv{'inststatus'};
7805: }
1.976 raeburn 7806: }
7807:
7808: if ($toolstatus ne '') {
7809: if ($toolstatus) {
7810: $access = 1;
7811: } else {
7812: $access = 0;
7813: }
7814: return $access;
7815: }
7816:
1.1084 raeburn 7817: my ($is_adv,%domdef);
7818: if (ref($is_advref) eq 'HASH') {
7819: $is_adv = $is_advref->{'is_adv'};
7820: } else {
7821: $is_adv = &is_advanced_user($udom,$uname);
7822: }
7823: if (ref($domdefref) eq 'HASH') {
7824: %domdef = %{$domdefref};
7825: } else {
7826: %domdef = &get_domain_defaults($udom);
7827: }
1.976 raeburn 7828: if (ref($domdef{$tool}) eq 'HASH') {
7829: if ($is_adv) {
7830: if ($domdef{$tool}{'_LC_adv'} ne '') {
7831: if ($domdef{$tool}{'_LC_adv'}) {
7832: $access = 1;
7833: } else {
7834: $access = 0;
7835: }
7836: return $access;
7837: }
7838: }
7839: if ($inststatus ne '') {
7840: my ($hasaccess,$hasnoaccess);
7841: foreach my $affiliation (split(/:/,$inststatus)) {
7842: if ($domdef{$tool}{$affiliation} ne '') {
7843: if ($domdef{$tool}{$affiliation}) {
7844: $hasaccess = 1;
7845: } else {
7846: $hasnoaccess = 1;
7847: }
7848: }
7849: }
7850: if ($hasaccess || $hasnoaccess) {
7851: if ($hasaccess) {
7852: $access = 1;
7853: } elsif ($hasnoaccess) {
7854: $access = 0;
7855: }
7856: return $access;
7857: }
7858: } else {
7859: if ($domdef{$tool}{'default'} ne '') {
7860: if ($domdef{$tool}{'default'}) {
7861: $access = 1;
7862: } elsif ($domdef{$tool}{'default'} == 0) {
7863: $access = 0;
7864: }
7865: return $access;
7866: }
7867: }
7868: } else {
1.1177 raeburn 7869: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7870: $access = 1;
7871: } else {
7872: $access = 0;
7873: }
1.976 raeburn 7874: return $access;
7875: }
7876: }
7877:
1.1050 raeburn 7878: sub is_course_owner {
7879: my ($cdom,$cnum,$udom,$uname) = @_;
7880: if (($udom eq '') || ($uname eq '')) {
7881: $udom = $env{'user.domain'};
7882: $uname = $env{'user.name'};
7883: }
7884: unless (($udom eq '') || ($uname eq '')) {
7885: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7886: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7887: return 1;
7888: } else {
7889: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7890: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7891: return 1;
7892: }
7893: }
7894: }
7895: }
7896: return;
7897: }
7898:
1.976 raeburn 7899: sub is_advanced_user {
7900: my ($udom,$uname) = @_;
1.1085 raeburn 7901: if ($udom ne '' && $uname ne '') {
7902: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7903: if (wantarray) {
7904: return ($env{'user.adv'},$env{'user.author'});
7905: } else {
7906: return $env{'user.adv'};
7907: }
1.1085 raeburn 7908: }
7909: }
1.976 raeburn 7910: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7911: my %allroles;
1.1128 raeburn 7912: my ($is_adv,$is_author);
1.976 raeburn 7913: foreach my $role (keys(%roleshash)) {
7914: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7915: my $area = '/'.$tdomain.'/'.$trest;
7916: if ($sec ne '') {
7917: $area .= '/'.$sec;
7918: }
7919: if (($area ne '') && ($trole ne '')) {
7920: my $spec=$trole.'.'.$area;
7921: if ($trole =~ /^cr\//) {
7922: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7923: } elsif ($trole ne 'gr') {
7924: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7925: }
1.1128 raeburn 7926: if ($trole eq 'au') {
7927: $is_author = 1;
7928: }
1.976 raeburn 7929: }
7930: }
7931: foreach my $role (keys(%allroles)) {
7932: last if ($is_adv);
7933: foreach my $item (split(/:/,$allroles{$role})) {
7934: if ($item ne '') {
7935: my ($privilege,$restrictions)=split(/&/,$item);
7936: if ($privilege eq 'adv') {
7937: $is_adv = 1;
7938: last;
7939: }
7940: }
7941: }
7942: }
1.1128 raeburn 7943: if (wantarray) {
7944: return ($is_adv,$is_author);
7945: }
1.976 raeburn 7946: return $is_adv;
7947: }
1.798 raeburn 7948:
1.1035 raeburn 7949: sub check_can_request {
1.1368 raeburn 7950: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 7951: my $canreq = 0;
1.1368 raeburn 7952: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7953: $uname = $env{'user.name'};
7954: $udom = $env{'user.domain'};
7955: }
1.1035 raeburn 7956: my ($types,$typename) = &Apache::loncommon::course_types();
7957: my @options = ('approval','validate','autolimit');
7958: my $optregex = join('|',@options);
7959: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7960: foreach my $type (@{$types}) {
1.1368 raeburn 7961: if (&usertools_access($uname,$udom,$type,undef,
7962: 'requestcourses')) {
1.1035 raeburn 7963: $canreq ++;
1.1036 raeburn 7964: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 7965: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 7966: }
1.1368 raeburn 7967: if ($dom eq $udom) {
1.1035 raeburn 7968: $can_request->{$type} = 1;
7969: }
7970: }
1.1368 raeburn 7971: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
7972: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 7973: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7974: if (@curr > 0) {
1.1036 raeburn 7975: foreach my $item (@curr) {
7976: if (ref($request_domains) eq 'HASH') {
7977: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7978: if ($otherdom ne '') {
7979: if (ref($request_domains->{$type}) eq 'ARRAY') {
7980: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7981: push(@{$request_domains->{$type}},$otherdom);
7982: }
7983: } else {
7984: push(@{$request_domains->{$type}},$otherdom);
7985: }
7986: }
7987: }
7988: }
1.1368 raeburn 7989: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 7990: $canreq ++;
1.1035 raeburn 7991: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7992: $can_request->{$type} = 1;
7993: }
7994: }
7995: }
7996: }
7997: }
7998: }
7999: return $canreq;
8000: }
8001:
1.341 www 8002: # ---------------------------------------------- Custom access rule evaluation
8003:
8004: sub customaccess {
8005: my ($priv,$uri)=@_;
1.807 albertel 8006: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8007: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8008: $udom = &LONCAPA::clean_domain($udom);
8009: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8010: my $access=0;
1.800 albertel 8011: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8012: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8013: if ($type eq 'user') {
8014: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8015: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8016: if ($tdom) {
8017: if ($tdom ne $env{'user.domain'}) { next; }
8018: }
1.896 albertel 8019: if ($tuname) {
8020: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8021: }
8022: $access=($effect eq 'allow');
8023: last;
8024: }
8025: } else {
8026: if ($role) {
8027: if ($role ne $urole) { next; }
8028: }
8029: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8030: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8031: if ($tdom) {
8032: if ($tdom ne $udom) { next; }
8033: }
8034: if ($tcrs) {
8035: if ($tcrs ne $ucrs) { next; }
8036: }
8037: if ($tsec) {
8038: if ($tsec ne $usec) { next; }
8039: }
8040: $access=($effect eq 'allow');
8041: last;
8042: }
8043: if ($realm eq '' && $role eq '') {
8044: $access=($effect eq 'allow');
8045: }
1.402 bowersj2 8046: }
1.341 www 8047: }
8048: return $access;
8049: }
8050:
1.103 harris41 8051: # ------------------------------------------------- Check for a user privilege
1.12 www 8052:
8053: sub allowed {
1.1424 raeburn 8054: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 8055: my $ver_orguri=$uri;
1.439 www 8056: $uri=&deversion($uri);
1.152 www 8057: my $orguri=$uri;
1.52 www 8058: $uri=&declutter($uri);
1.809 raeburn 8059:
1.810 raeburn 8060: if ($priv eq 'evb') {
8061: # Evade communication block restrictions for specified role in a course
8062: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8063: return $1;
8064: } else {
8065: return;
8066: }
8067: }
8068:
1.620 albertel 8069: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8070: # Free bre access to adm and meta resources
1.1343 raeburn 8071: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 8072: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8073: && ($priv eq 'bre')) {
1.14 www 8074: return 'F';
1.159 www 8075: }
8076:
1.545 banghart 8077: # Free bre access to user's own portfolio contents
1.714 raeburn 8078: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8079: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8080: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8081: my %setters;
8082: my ($startblock,$endblock) =
8083: &Apache::loncommon::blockcheck(\%setters,'port');
8084: if ($startblock && $endblock) {
8085: return 'B';
8086: } else {
8087: return 'F';
8088: }
1.545 banghart 8089: }
8090:
1.762 raeburn 8091: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8092: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8093: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8094: if (exists($env{'request.course.id'})) {
8095: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8096: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8097: if (($domain eq $cdom) && ($name eq $cnum)) {
8098: my $courseprivid=$env{'request.course.id'};
8099: $courseprivid=~s/\_/\//;
8100: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8101: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8102: return $1;
1.762 raeburn 8103: } else {
8104: if ($env{'request.course.sec'}) {
8105: $courseprivid.='/'.$env{'request.course.sec'};
8106: }
8107: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8108: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8109: return $2;
8110: }
1.714 raeburn 8111: }
8112: }
8113: }
8114: }
8115:
1.159 www 8116: # Free bre to public access
8117:
8118: if ($priv eq 'bre') {
1.1362 raeburn 8119: my $copyright;
8120: unless ($uri =~ /ext\.tool/) {
8121: $copyright=&metadata($uri,'copyright');
8122: }
1.620 albertel 8123: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8124: return 'F';
8125: }
1.238 www 8126: if ($copyright eq 'priv') {
8127: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8128: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8129: return '';
8130: }
8131: }
8132: if ($copyright eq 'domain') {
8133: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8134: unless (($env{'user.domain'} eq $1) ||
8135: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8136: return '';
8137: }
1.262 matthew 8138: }
1.620 albertel 8139: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8140: # Library role, so allow browsing of resources in this domain.
8141: return 'F';
1.238 www 8142: }
1.341 www 8143: if ($copyright eq 'custom') {
8144: unless (&customaccess($priv,$uri)) { return ''; }
8145: }
1.14 www 8146: }
1.264 matthew 8147: # Domain coordinator is trying to create a course
1.620 albertel 8148: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8149: # uri is the requested domain in this case.
8150: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8151: # a role of dc for the domain in question.
1.620 albertel 8152: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8153: }
1.29 www 8154:
1.52 www 8155: my $thisallowed='';
8156: my $statecond=0;
8157: my $courseprivid='';
8158:
1.1039 raeburn 8159: my $ownaccess;
1.1043 raeburn 8160: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8161: if (($priv eq 'bro') && ($env{'user.author'})) {
8162: if ($uri eq '') {
8163: $ownaccess = 1;
8164: } else {
8165: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8166: my $udom = $env{'user.domain'};
8167: my $uname = $env{'user.name'};
8168: if ($uri =~ m{^\Q$udom\E/?$}) {
8169: $ownaccess = 1;
1.1040 raeburn 8170: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8171: unless ($uri =~ m{\.\./}) {
8172: $ownaccess = 1;
8173: }
8174: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8175: my $now = time;
8176: if ($uri =~ m{^([^/]+)/?$}) {
8177: my $adom = $1;
8178: foreach my $key (keys(%env)) {
1.1042 raeburn 8179: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 8180: my ($start,$end) = split('.',$env{$key});
8181: if (($now >= $start) && (!$end || $end < $now)) {
8182: $ownaccess = 1;
8183: last;
8184: }
8185: }
8186: }
8187: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8188: my $adom = $1;
8189: my $aname = $2;
1.1042 raeburn 8190: foreach my $role ('ca','aa') {
8191: if ($env{"user.role.$role./$adom/$aname"}) {
8192: my ($start,$end) =
8193: split('.',$env{"user.role.$role./$adom/$aname"});
8194: if (($now >= $start) && (!$end || $end < $now)) {
8195: $ownaccess = 1;
8196: last;
8197: }
1.1039 raeburn 8198: }
8199: }
8200: }
8201: }
8202: }
8203: }
8204: }
8205:
1.52 www 8206: # Course
8207:
1.620 albertel 8208: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8209: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8210: $thisallowed.=$1;
8211: }
1.52 www 8212: }
1.29 www 8213:
1.52 www 8214: # Domain
8215:
1.620 albertel 8216: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8217: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8218: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8219: $thisallowed.=$1;
8220: }
1.12 www 8221: }
1.52 www 8222:
1.1141 raeburn 8223: # User who is not author or co-author might still be able to edit
8224: # resource of an author in the domain (e.g., if Domain Coordinator).
8225: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8226: (&allowed('mdc',$env{'request.course.id'}))) {
8227: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8228: $thisallowed.=$1;
8229: }
8230: }
8231:
1.52 www 8232: # Course: uri itself is a course
1.66 www 8233: my $courseuri=$uri;
8234: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8235: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8236:
1.620 albertel 8237: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8238: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8239: if ($priv eq 'mip') {
8240: my $rem = $1;
8241: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8242: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8243: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8244: if ($cdom ne '') {
1.1410 raeburn 8245: my %passwdconf = &get_passwdconf($cdom);
8246: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8247: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8248: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8249: my @inststatuses = split(':',$env{'environment.inststatus'});
8250: unless (@inststatuses) {
8251: @inststatuses = ('default');
8252: }
8253: foreach my $status (@inststatuses) {
8254: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8255: $thisallowed.=$rem;
8256: }
8257: }
8258: }
8259: }
1.1409 raeburn 8260: }
8261: }
8262: }
8263: } else {
8264: unless (($priv eq 'bro') && (!$ownaccess)) {
8265: $thisallowed.=$1;
8266: }
1.1039 raeburn 8267: }
1.12 www 8268: }
1.29 www 8269:
1.665 albertel 8270: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8271: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8272: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8273: $thisallowed='';
1.671 raeburn 8274: my ($match)=&is_on_map($uri);
8275: if ($match) {
8276: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8277: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8278: my $value = $1;
1.1402 raeburn 8279: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8280: if ($deeplinkblock) {
8281: $thisallowed='D';
8282: } elsif ($noblockcheck) {
1.1281 raeburn 8283: $thisallowed.=$value;
1.1162 raeburn 8284: } else {
1.1424 raeburn 8285: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8286: if (@blockers > 0) {
8287: $thisallowed = 'B';
8288: } else {
8289: $thisallowed.=$value;
8290: }
1.1162 raeburn 8291: }
1.671 raeburn 8292: }
8293: } else {
1.705 albertel 8294: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8295: if ($refuri) {
8296: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8297: $thisallowed='F';
1.671 raeburn 8298: } else {
8299: $refuri=&declutter($refuri);
8300: my ($match) = &is_on_map($refuri);
8301: if ($match) {
1.1402 raeburn 8302: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8303: if ($deeplinkblock) {
8304: $thisallowed='D';
8305: } elsif ($noblockcheck) {
1.1281 raeburn 8306: $thisallowed='F';
1.1162 raeburn 8307: } else {
1.1426 raeburn 8308: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8309: if (@blockers > 0) {
8310: $thisallowed = 'B';
8311: } else {
8312: $thisallowed='F';
8313: }
1.1162 raeburn 8314: }
1.671 raeburn 8315: }
1.669 raeburn 8316: }
1.671 raeburn 8317: }
8318: }
1.314 www 8319: }
1.492 albertel 8320:
1.766 albertel 8321: if ($priv eq 'bre'
8322: && $thisallowed ne 'F'
8323: && $thisallowed ne '2'
8324: && &is_portfolio_url($uri)) {
1.1270 raeburn 8325: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8326: }
1.1250 raeburn 8327:
1.52 www 8328: # Full access at system, domain or course-wide level? Exit.
1.29 www 8329: if ($thisallowed=~/F/) {
8330: return 'F';
8331: }
8332:
1.52 www 8333: # If this is generating or modifying users, exit with special codes
1.29 www 8334:
1.643 www 8335: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8336: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8337: my ($audom,$auname)=split('/',$uri);
1.643 www 8338: # no author name given, so this just checks on the general right to make a co-author in this domain
8339: unless ($auname) { return $thisallowed; }
8340: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8341: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8342: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8343: ($audom ne $env{'request.role.domain'}))) { return ''; }
8344: }
1.52 www 8345: return $thisallowed;
8346: }
8347: #
1.103 harris41 8348: # Gathered so far: system, domain and course wide privileges
1.52 www 8349: #
8350: # Course: See if uri or referer is an individual resource that is part of
8351: # the course
8352:
1.620 albertel 8353: if ($env{'request.course.id'}) {
1.232 www 8354:
1.1409 raeburn 8355: # If this is modifying password (internal auth) domains must match for user and user's role.
8356:
8357: if ($priv eq 'mip') {
8358: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8359: return $thisallowed;
8360: } else {
8361: return '';
8362: }
8363: }
8364:
1.620 albertel 8365: $courseprivid=$env{'request.course.id'};
8366: if ($env{'request.course.sec'}) {
8367: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8368: }
8369: $courseprivid=~s/\_/\//;
8370: my $checkreferer=1;
1.232 www 8371: my ($match,$cond)=&is_on_map($uri);
8372: if ($match) {
8373: $statecond=$cond;
1.620 albertel 8374: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8375: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8376: my $value = $1;
8377: if ($priv eq 'bre') {
1.1281 raeburn 8378: if ($noblockcheck) {
8379: $thisallowed.=$value;
1.1162 raeburn 8380: } else {
1.1424 raeburn 8381: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8382: if (@blockers > 0) {
8383: $thisallowed = 'B';
8384: } else {
8385: $thisallowed.=$value;
8386: }
1.1162 raeburn 8387: }
8388: } else {
8389: $thisallowed.=$value;
8390: }
1.52 www 8391: $checkreferer=0;
8392: }
1.29 www 8393: }
1.1424 raeburn 8394:
1.148 www 8395: if ($checkreferer) {
1.620 albertel 8396: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8397: unless ($refuri) {
1.800 albertel 8398: foreach my $key (keys(%env)) {
8399: if ($key=~/^httpref\..*\*/) {
8400: my $pattern=$key;
1.156 www 8401: $pattern=~s/^httpref\.\/res\///;
1.148 www 8402: $pattern=~s/\*/\[\^\/\]\+/g;
8403: $pattern=~s/\//\\\//g;
1.152 www 8404: if ($orguri=~/$pattern/) {
1.800 albertel 8405: $refuri=$env{$key};
1.148 www 8406: }
8407: }
1.191 harris41 8408: }
1.148 www 8409: }
1.232 www 8410:
1.148 www 8411: if ($refuri) {
1.152 www 8412: $refuri=&declutter($refuri);
1.232 www 8413: my ($match,$cond)=&is_on_map($refuri);
8414: if ($match) {
8415: my $refstatecond=$cond;
1.620 albertel 8416: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8417: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8418: my $value = $1;
8419: if ($priv eq 'bre') {
1.1402 raeburn 8420: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8421: if ($deeplinkblock) {
8422: $thisallowed = 'D';
8423: } elsif ($noblockcheck) {
1.1281 raeburn 8424: $thisallowed.=$value;
1.1162 raeburn 8425: } else {
1.1426 raeburn 8426: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8427: if (@blockers > 0) {
8428: $thisallowed = 'B';
8429: } else {
8430: $thisallowed.=$value;
8431: }
1.1162 raeburn 8432: }
8433: } else {
8434: $thisallowed.=$value;
8435: }
1.53 www 8436: $uri=$refuri;
8437: $statecond=$refstatecond;
1.52 www 8438: }
8439: }
1.148 www 8440: }
1.29 www 8441: }
1.52 www 8442: }
1.29 www 8443:
1.52 www 8444: #
1.103 harris41 8445: # Gathered now: all privileges that could apply, and condition number
1.52 www 8446: #
8447: #
8448: # Full or no access?
8449: #
1.29 www 8450:
1.52 www 8451: if ($thisallowed=~/F/) {
8452: return 'F';
8453: }
1.29 www 8454:
1.52 www 8455: unless ($thisallowed) {
8456: return '';
8457: }
1.29 www 8458:
1.52 www 8459: # Restrictions exist, deal with them
8460: #
8461: # C:according to course preferences
8462: # R:according to resource settings
8463: # L:unless locked
8464: # X:according to user session state
8465: #
8466:
8467: # Possibly locked functionality, check all courses
1.54 www 8468: # Locks might take effect only after 10 minutes cache expiration for other
8469: # courses, and 2 minutes for current course
1.52 www 8470:
8471: my $envkey;
8472: if ($thisallowed=~/L/) {
1.1000 raeburn 8473: foreach $envkey (keys(%env)) {
1.54 www 8474: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8475: my $courseid=$2;
8476: my $roleid=$1.'.'.$2;
1.92 www 8477: $courseid=~s/^\///;
1.54 www 8478: my $expiretime=600;
1.620 albertel 8479: if ($env{'request.role'} eq $roleid) {
1.54 www 8480: $expiretime=120;
8481: }
8482: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8483: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8484: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8485: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8486: }
1.620 albertel 8487: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8488: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8489: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8490: &log($env{'user.domain'},$env{'user.name'},
8491: $env{'user.home'},
1.57 www 8492: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8493: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8494: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8495: return '';
8496: }
8497: }
1.620 albertel 8498: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8499: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8500: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8501: &log($env{'user.domain'},$env{'user.name'},
8502: $env{'user.home'},
1.57 www 8503: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8504: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8505: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8506: return '';
8507: }
8508: }
8509: }
1.29 www 8510: }
1.52 www 8511: }
1.1424 raeburn 8512:
1.52 www 8513: #
8514: # Rest of the restrictions depend on selected course
8515: #
8516:
1.620 albertel 8517: unless ($env{'request.course.id'}) {
1.766 albertel 8518: if ($thisallowed eq 'A') {
8519: return 'A';
1.814 raeburn 8520: } elsif ($thisallowed eq 'B') {
8521: return 'B';
1.766 albertel 8522: } else {
8523: return '1';
8524: }
1.52 www 8525: }
1.29 www 8526:
1.52 www 8527: #
8528: # Now user is definitely in a course
8529: #
1.53 www 8530:
8531:
8532: # Course preferences
8533:
8534: if ($thisallowed=~/C/) {
1.620 albertel 8535: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8536: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8537: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8538: =~/\Q$rolecode\E/) {
1.1304 raeburn 8539: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8540: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8541: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8542: $env{'request.course.id'});
8543: }
1.237 www 8544: return '';
8545: }
8546:
1.620 albertel 8547: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8548: =~/\Q$unamedom\E/) {
1.1304 raeburn 8549: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8550: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8551: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8552: $env{'request.course.id'});
8553: }
1.54 www 8554: return '';
8555: }
1.53 www 8556: }
8557:
8558: # Resource preferences
8559:
8560: if ($thisallowed=~/R/) {
1.620 albertel 8561: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8562: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8563: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8564: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8565: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8566: }
8567: return '';
1.54 www 8568: }
1.53 www 8569: }
1.30 www 8570:
1.246 www 8571: # Restricted by state or randomout?
1.30 www 8572:
1.52 www 8573: if ($thisallowed=~/X/) {
1.620 albertel 8574: if ($env{'acc.randomout'}) {
1.579 albertel 8575: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8576: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8577: return '';
8578: }
1.247 www 8579: }
8580: if (&condval($statecond)) {
1.52 www 8581: return '2';
8582: } else {
8583: return '';
8584: }
8585: }
1.30 www 8586:
1.766 albertel 8587: if ($thisallowed eq 'A') {
8588: return 'A';
1.814 raeburn 8589: } elsif ($thisallowed eq 'B') {
8590: return 'B';
1.1402 raeburn 8591: } elsif ($thisallowed eq 'D') {
8592: return 'D';
1.766 albertel 8593: }
1.52 www 8594: return 'F';
1.232 www 8595: }
1.1162 raeburn 8596:
1.1192 raeburn 8597: # ------------------------------------------- Check construction space access
8598:
8599: sub constructaccess {
8600: my ($url,$setpriv)=@_;
8601:
8602: # We do not allow editing of previous versions of files
8603: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8604:
8605: # Get username and domain from URL
8606: my ($ownername,$ownerdomain,$ownerhome);
8607:
8608: ($ownerdomain,$ownername) =
1.1325 raeburn 8609: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8610:
8611: # The URL does not really point to any authorspace, forget it
8612: unless (($ownername) && ($ownerdomain)) { return ''; }
8613:
8614: # Now we need to see if the user has access to the authorspace of
8615: # $ownername at $ownerdomain
8616:
8617: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8618: # Real author for this?
8619: $ownerhome = $env{'user.home'};
8620: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8621: return ($ownername,$ownerdomain,$ownerhome);
8622: }
8623: } else {
8624: # Co-author for this?
8625: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8626: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8627: $ownerhome = &homeserver($ownername,$ownerdomain);
8628: return ($ownername,$ownerdomain,$ownerhome);
8629: }
1.1312 raeburn 8630: if ($env{'request.course.id'}) {
8631: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8632: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8633: if (&allowed('mdc',$env{'request.course.id'})) {
8634: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8635: return ($ownername,$ownerdomain,$ownerhome);
8636: }
8637: }
8638: }
1.1192 raeburn 8639: }
8640:
8641: # We don't have any access right now. If we are not possibly going to do anything about this,
8642: # we might as well leave
8643: unless ($setpriv) { return ''; }
8644:
8645: # Backdoor access?
8646: my $allowed=&allowed('eco',$ownerdomain);
8647: # Nope
8648: unless ($allowed) { return ''; }
8649: # Looks like we may have access, but could be locked by the owner of the construction space
8650: if ($allowed eq 'U') {
8651: my %blocked=&get('environment',['domcoord.author'],
8652: $ownerdomain,$ownername);
8653: # Is blocked by owner
8654: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8655: }
8656: if (($allowed eq 'F') || ($allowed eq 'U')) {
8657: # Grant temporary access
8658: my $then=$env{'user.login.time'};
1.1209 raeburn 8659: my $update=$env{'user.update.time'};
1.1192 raeburn 8660: if (!$update) { $update = $then; }
8661: my $refresh=$env{'user.refresh.time'};
8662: if (!$refresh) { $refresh = $update; }
8663: my $now = time;
8664: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8665: $now,'ca','constructaccess');
8666: $ownerhome = &homeserver($ownername,$ownerdomain);
8667: return($ownername,$ownerdomain,$ownerhome);
8668: }
8669: # No business here
8670: return '';
8671: }
8672:
1.1282 raeburn 8673: # ----------------------------------------------------------- Content Blocking
8674:
8675: {
8676: # Caches for faster Course Contents display where content blocking
8677: # is in operation (i.e., interval param set) for timed quiz.
8678: #
8679: # User for whom data are being temporarily cached.
8680: my $cacheduser='';
1.1424 raeburn 8681: # Course for which data are being temporarily cached.
8682: my $cachedcid='';
1.1282 raeburn 8683: # Cached blockers for this user (a hash of blocking items).
8684: my %cachedblockers=();
8685: # When the data were last cached.
8686: my $cachedlast='';
8687:
8688: sub load_all_blockers {
1.1427 raeburn 8689: my ($uname,$udom)=@_;
1.1282 raeburn 8690: if (($uname ne '') && ($udom ne '')) {
8691: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 8692: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 8693: (abs($cachedlast-time)<5)) {
1.1282 raeburn 8694: return;
8695: }
8696: }
8697: $cachedlast=time;
8698: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 8699: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 8700: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 8701: return;
1.1282 raeburn 8702: }
8703:
1.1162 raeburn 8704: sub get_comm_blocks {
8705: my ($cdom,$cnum) = @_;
8706: if ($cdom eq '' || $cnum eq '') {
8707: return unless ($env{'request.course.id'});
8708: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8709: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8710: }
8711: my %commblocks;
8712: my $hashid=$cdom.'_'.$cnum;
8713: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8714: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8715: %commblocks = %{$blocksref};
8716: } else {
8717: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8718: my $cachetime = 600;
8719: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8720: }
8721: return %commblocks;
8722: }
8723:
1.1282 raeburn 8724: sub get_commblock_resources {
8725: my ($blocks) = @_;
8726: my %blockers = ();
8727: return %blockers unless ($env{'request.course.id'});
8728: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8729: my %commblocks;
8730: if (ref($blocks) eq 'HASH') {
8731: %commblocks = %{$blocks};
8732: } else {
8733: %commblocks = &get_comm_blocks();
8734: }
1.1282 raeburn 8735: return %blockers unless (keys(%commblocks) > 0);
8736: my $navmap = Apache::lonnavmaps::navmap->new();
8737: return %blockers unless (ref($navmap));
1.1162 raeburn 8738: my $now = time;
8739: foreach my $block (keys(%commblocks)) {
8740: if ($block =~ /^(\d+)____(\d+)$/) {
8741: my ($start,$end) = ($1,$2);
8742: if ($start <= $now && $end >= $now) {
8743: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8744: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8745: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8746: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8747: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8748: }
8749: }
8750: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8751: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8752: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8753: }
8754: }
8755: }
8756: }
8757: }
8758: } elsif ($block =~ /^firstaccess____(.+)$/) {
8759: my $item = $1;
1.1163 raeburn 8760: my @to_test;
1.1162 raeburn 8761: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8762: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8763: my @interval;
8764: my $type = 'map';
8765: if ($item eq 'course') {
8766: $type = 'course';
8767: @interval=&EXT("resource.0.interval");
8768: } else {
8769: if ($item =~ /___\d+___/) {
8770: $type = 'resource';
8771: @interval=&EXT("resource.0.interval",$item);
8772: if (ref($navmap)) {
8773: my $res = $navmap->getBySymb($item);
8774: push(@to_test,$res);
8775: }
1.1162 raeburn 8776: } else {
1.1282 raeburn 8777: my $mapsymb = &symbread($item,1);
8778: if ($mapsymb) {
8779: if (ref($navmap)) {
8780: my $mapres = $navmap->getBySymb($mapsymb);
1.1428 raeburn 8781: if (ref($mapres)) {
8782: my $first = $mapres->map_start();
8783: my $finish = $mapres->map_finish();
8784: my $it = $navmap->getIterator($first,$finish,undef,0,0);
1.1429 raeburn 8785: if (ref($it)) {
8786: my $res;
8787: while ($res = $it->next(undef,1)) {
8788: next unless (ref($res));
8789: my $symb = $res->symb();
8790: next if (($symb eq $mapsymb) || ($symb eq ''));
8791: @interval=&EXT("resource.0.interval",$symb);
8792: if ($interval[1] eq 'map') {
8793: if ($res->answerable()) {
8794: push(@to_test,$res);
8795: last;
8796: }
1.1428 raeburn 8797: }
1.1162 raeburn 8798: }
8799: }
8800: }
8801: }
8802: }
8803: }
1.1282 raeburn 8804: }
1.1310 raeburn 8805: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8806: my $timelimit = $1;
1.1282 raeburn 8807: my $first_access;
8808: if ($type eq 'resource') {
8809: $first_access=&get_first_access($interval[1],$item);
8810: } elsif ($type eq 'map') {
8811: $first_access=&get_first_access($interval[1],undef,$item);
8812: } else {
8813: $first_access=&get_first_access($interval[1]);
8814: }
8815: if ($first_access) {
1.1292 raeburn 8816: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8817: if ($timesup > $now) {
8818: my $activeblock;
8819: foreach my $res (@to_test) {
1.1283 raeburn 8820: if ($res->answerable()) {
1.1282 raeburn 8821: $activeblock = 1;
8822: last;
8823: }
8824: }
8825: if ($activeblock) {
8826: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8827: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8828: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8829: }
8830: }
8831: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8832: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8833: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8834: }
1.1162 raeburn 8835: }
8836: }
8837: }
8838: }
8839: }
8840: }
8841: }
8842: }
8843: }
1.1282 raeburn 8844: return %blockers;
1.1162 raeburn 8845: }
8846:
1.1282 raeburn 8847: sub has_comm_blocking {
1.1427 raeburn 8848: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 8849: my @blockers;
8850: return unless ($env{'request.course.id'});
8851: return unless ($priv eq 'bre');
8852: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8853: return if ($env{'request.state'} eq 'construct');
1.1427 raeburn 8854: my %blockinfo;
8855: if (ref($blocks) eq 'HASH') {
8856: %blockinfo = &get_commblock_resources($blocks);
8857: } else {
8858: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8859: %blockinfo = %cachedblockers;
8860: }
8861: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 8862: my (%possibles,@symbs);
8863: if (!$symb) {
1.1427 raeburn 8864: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8865: }
1.1282 raeburn 8866: if ($symb) {
8867: @symbs = ($symb);
8868: } elsif (keys(%possibles)) {
8869: @symbs = keys(%possibles);
8870: }
8871: my $noblock;
8872: foreach my $symb (@symbs) {
8873: last if ($noblock);
8874: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 8875: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 8876: if ($block =~ /^firstaccess____(.+)$/) {
8877: my $item = $1;
1.1424 raeburn 8878: unless ($blocked) {
8879: if (($item eq $map) || ($item eq $symb)) {
8880: $noblock = 1;
8881: last;
8882: }
1.1282 raeburn 8883: }
8884: }
1.1427 raeburn 8885: if (ref($blockinfo{$block}) eq 'HASH') {
8886: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8887: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 8888: unless (grep(/^\Q$block\E$/,@blockers)) {
8889: push(@blockers,$block);
8890: }
8891: }
8892: }
1.1427 raeburn 8893: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8894: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 8895: unless (grep(/^\Q$block\E$/,@blockers)) {
8896: push(@blockers,$block);
8897: }
1.1282 raeburn 8898: }
8899: }
1.1162 raeburn 8900: }
8901: }
8902: }
1.1424 raeburn 8903: unless ($noblock) {
8904: return @blockers;
8905: }
8906: return;
1.1282 raeburn 8907: }
1.1162 raeburn 8908: }
8909:
1.1402 raeburn 8910: sub deeplink_check {
8911: my ($priv,$symb,$uri) = @_;
8912: return unless ($env{'request.course.id'});
8913: return unless ($priv eq 'bre');
8914: return if ($env{'request.state'} eq 'construct');
8915: return if ($env{'request.role.adv'});
8916: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8917: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8918: my (%possibles,@symbs);
8919: if (!$symb) {
8920: $symb = &symbread($uri,1,1,1,\%possibles);
8921: }
8922: if ($symb) {
8923: @symbs = ($symb);
8924: } elsif (keys(%possibles)) {
8925: @symbs = keys(%possibles);
8926: }
8927:
8928: my ($login,$switchrole,$allow);
8929: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8930: my $key = $1;
8931: my $tinyurl;
8932: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8933: if (defined($cached)) {
8934: $tinyurl = $result;
8935: } else {
8936: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8937: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8938: if ($currtiny{$key} ne '') {
8939: $tinyurl = $currtiny{$key};
8940: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8941: }
8942: }
8943: if ($tinyurl ne '') {
8944: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8945: if ($cnumreq eq $cnum) {
8946: $login = $posslogin;
8947: } else {
8948: $switchrole = 1;
8949: }
8950: }
8951: }
8952: foreach my $symb (@symbs) {
8953: last if ($allow);
8954: my $deeplink = &EXT("resource.0.deeplink",$symb);
8955: if ($deeplink eq '') {
8956: $allow = 1;
8957: } else {
8958: my ($listed,$scope,$access) = split(/,/,$deeplink);
8959: if ($access eq 'any') {
8960: $allow = 1;
8961: } elsif ($login) {
8962: if ($access eq 'only') {
8963: if ($scope eq 'res') {
8964: if ($symb eq $login) {
8965: $allow = 1;
8966: }
8967: } elsif ($scope eq 'map') {
8968: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
8969: } elsif ($scope eq 'rec') {
8970: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
8971: }
8972: } else {
8973: my ($acctype,$item) = split(/:/,$access);
8974: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
8975: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
8976: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8977: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
8978: $allow = 1;
8979: }
8980: }
8981: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
8982: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
8983: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8984: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
8985: $allow = 1;
8986: }
8987: }
8988: }
8989: }
8990: }
8991: }
8992: }
8993: return if ($allow);
8994: return 1;
8995: }
8996:
1.1282 raeburn 8997: # -------------------------------- Deversion and split uri into path an filename
8998:
1.1133 foxr 8999: #
1.1282 raeburn 9000: # Removes the version from a URI and
1.1133 foxr 9001: # splits it in to its filename and path to the filename.
9002: # Seems like File::Basename could have done this more clearly.
9003: # Parameters:
9004: # $uri - input URI
9005: # Returns:
9006: # Two element list consisting of
9007: # $pathname - the URI up to and excluding the trailing /
9008: # $filename - The part of the URI following the last /
9009: # NOTE:
9010: # Another realization of this is simply:
9011: # use File::Basename;
9012: # ...
9013: # $uri = shift;
9014: # $filename = basename($uri);
9015: # $path = dirname($uri);
9016: # return ($filename, $path);
9017: #
9018: # The implementation below is probably faster however.
9019: #
1.710 albertel 9020: sub split_uri_for_cond {
9021: my $uri=&deversion(&declutter(shift));
9022: my @uriparts=split(/\//,$uri);
9023: my $filename=pop(@uriparts);
9024: my $pathname=join('/',@uriparts);
9025: return ($pathname,$filename);
9026: }
1.232 www 9027: # --------------------------------------------------- Is a resource on the map?
9028:
9029: sub is_on_map {
1.710 albertel 9030: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9031: #Trying to find the conditional for the file
1.620 albertel 9032: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9033: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9034: if ($match) {
1.289 bowersj2 9035: return (1,$1);
9036: } else {
1.434 www 9037: return (0,0);
1.289 bowersj2 9038: }
1.12 www 9039: }
9040:
1.427 www 9041: # --------------------------------------------------------- Get symb from alias
9042:
9043: sub get_symb_from_alias {
9044: my $symb=shift;
9045: my ($map,$resid,$url)=&decode_symb($symb);
9046: # Already is a symb
9047: if ($url) { return $symb; }
9048: # Must be an alias
9049: my $aliassymb='';
9050: my %bighash;
1.620 albertel 9051: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9052: &GDBM_READER(),0640)) {
9053: my $rid=$bighash{'mapalias_'.$symb};
9054: if ($rid) {
9055: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9056: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9057: $resid,$bighash{'src_'.$rid});
1.427 www 9058: }
9059: untie %bighash;
9060: }
9061: return $aliassymb;
9062: }
9063:
1.12 www 9064: # ----------------------------------------------------------------- Define Role
9065:
9066: sub definerole {
9067: if (allowed('mcr','/')) {
1.1326 raeburn 9068: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9069: foreach my $role (split(':',$sysrole)) {
9070: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9071: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9072: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9073: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9074: return "refused:s:$crole&$cqual";
9075: }
9076: }
1.191 harris41 9077: }
1.800 albertel 9078: foreach my $role (split(':',$domrole)) {
9079: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9080: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9081: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9082: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9083: return "refused:d:$crole&$cqual";
9084: }
9085: }
1.191 harris41 9086: }
1.800 albertel 9087: foreach my $role (split(':',$courole)) {
9088: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9089: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9090: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9091: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9092: return "refused:c:$crole&$cqual";
9093: }
9094: }
1.191 harris41 9095: }
1.1326 raeburn 9096: my $uhome;
9097: if (($uname ne '') && ($udom ne '')) {
9098: $uhome = &homeserver($uname,$udom);
9099: return $uhome if ($uhome eq 'no_host');
9100: } else {
9101: $uname = $env{'user.name'};
9102: $udom = $env{'user.domain'};
9103: $uhome = $env{'user.home'};
9104: }
1.620 albertel 9105: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9106: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9107: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9108: return reply($command,$uhome);
1.12 www 9109: } else {
9110: return 'refused';
9111: }
1.105 harris41 9112: }
9113:
9114: # ---------------- Make a metadata query against the network of library servers
9115:
9116: sub metadata_query {
1.1237 raeburn 9117: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9118: my %rhash;
1.845 albertel 9119: my %libserv = &all_library();
1.244 matthew 9120: my @server_list = (defined($server_array) ? @$server_array
9121: : keys(%libserv) );
9122: for my $server (@server_list) {
1.1237 raeburn 9123: my $domains = '';
9124: if (ref($domains_hash) eq 'HASH') {
9125: $domains = $domains_hash->{$server};
9126: }
1.118 harris41 9127: unless ($custom or $customshow) {
1.1237 raeburn 9128: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9129: $rhash{$server}=$reply;
9130: }
9131: else {
9132: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9133: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9134: $server);
9135: $rhash{$server}=$reply;
9136: }
1.112 harris41 9137: }
1.118 harris41 9138: return \%rhash;
1.240 www 9139: }
9140:
9141: # ----------------------------------------- Send log queries and wait for reply
9142:
9143: sub log_query {
9144: my ($uname,$udom,$query,%filters)=@_;
9145: my $uhome=&homeserver($uname,$udom);
9146: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9147: my $uhost=&hostname($uhome);
1.800 albertel 9148: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9149: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9150: $uhome);
1.479 albertel 9151: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9152: return get_query_reply($queryid);
9153: }
9154:
1.818 raeburn 9155: # -------------------------- Update MySQL table for portfolio file
9156:
9157: sub update_portfolio_table {
1.821 raeburn 9158: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9159: if ($group ne '') {
9160: $file_name =~s /^\Q$group\E//;
9161: }
1.818 raeburn 9162: my $homeserver = &homeserver($uname,$udom);
9163: my $queryid=
1.821 raeburn 9164: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9165: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9166: my $reply = &get_query_reply($queryid);
9167: return $reply;
9168: }
9169:
1.899 raeburn 9170: # -------------------------- Update MySQL allusers table
9171:
9172: sub update_allusers_table {
9173: my ($uname,$udom,$names) = @_;
9174: my $homeserver = &homeserver($uname,$udom);
9175: my $queryid=
9176: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9177: 'lastname='.&escape($names->{'lastname'}).'%%'.
9178: 'firstname='.&escape($names->{'firstname'}).'%%'.
9179: 'middlename='.&escape($names->{'middlename'}).'%%'.
9180: 'generation='.&escape($names->{'generation'}).'%%'.
9181: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9182: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9183: return;
1.899 raeburn 9184: }
9185:
1.508 raeburn 9186: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9187:
9188: sub fetch_enrollment_query {
1.511 raeburn 9189: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9190: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9191: my $maxtries = 1;
1.508 raeburn 9192: if ($context eq 'automated') {
9193: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9194: $sleep = 2;
9195: $loopmax = 100;
1.547 raeburn 9196: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9197: } else {
9198: $homeserver = &homeserver($cnum,$dom);
9199: }
1.838 albertel 9200: my $host=&hostname($homeserver);
1.506 raeburn 9201: my $cmd = '';
1.1000 raeburn 9202: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9203: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9204: }
9205: $cmd =~ s/%%$//;
9206: $cmd = &escape($cmd);
9207: my $query = 'fetchenrollment';
1.620 albertel 9208: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9209: unless ($queryid=~/^\Q$host\E\_/) {
9210: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9211: return 'error: '.$queryid;
9212: }
1.1317 raeburn 9213: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9214: my $tries = 1;
9215: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9216: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9217: $tries ++;
9218: }
1.526 raeburn 9219: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9220: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9221: } else {
1.901 albertel 9222: my @responses = split(/:/,$reply);
1.1322 raeburn 9223: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9224: foreach my $line (@responses) {
9225: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9226: $$replyref{$key} = $value;
9227: }
9228: } else {
1.1117 foxr 9229: my $pathname = LONCAPA::tempdir();
1.800 albertel 9230: foreach my $line (@responses) {
9231: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9232: $$replyref{$key} = $value;
9233: if ($value > 0) {
1.800 albertel 9234: foreach my $item (@{$$affiliatesref{$key}}) {
9235: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9236: my $destname = $pathname.'/'.$filename;
9237: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9238: if ($xml_classlist =~ /^error/) {
9239: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9240: } else {
1.1359 raeburn 9241: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9242: print FILE &unescape($xml_classlist);
9243: close(FILE);
1.526 raeburn 9244: } else {
9245: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9246: }
9247: }
9248: }
9249: }
9250: }
9251: }
9252: return 'ok';
9253: }
9254: return 'error';
9255: }
9256:
1.242 www 9257: sub get_query_reply {
1.1317 raeburn 9258: my ($queryid,$sleep,$loopmax) = @_;;
9259: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9260: $sleep = 0.2;
9261: }
9262: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9263: $loopmax = 100;
9264: }
1.1117 foxr 9265: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9266: my $reply='';
1.1317 raeburn 9267: for (1..$loopmax) {
9268: sleep($sleep);
1.240 www 9269: if (-e $replyfile.'.end') {
1.1359 raeburn 9270: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9271: $reply = join('',<$fh>);
9272: close($fh);
1.240 www 9273: } else { return 'error: reply_file_error'; }
1.242 www 9274: return &unescape($reply);
9275: }
1.240 www 9276: }
1.242 www 9277: return 'timeout:'.$queryid;
1.240 www 9278: }
9279:
9280: sub courselog_query {
1.241 www 9281: #
9282: # possible filters:
9283: # url: url or symb
9284: # username
9285: # domain
9286: # action: view, submit, grade
9287: # start: timestamp
9288: # end: timestamp
9289: #
1.240 www 9290: my (%filters)=@_;
1.620 albertel 9291: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9292: if ($filters{'url'}) {
9293: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9294: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9295: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9296: }
1.620 albertel 9297: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9298: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9299: return &log_query($cname,$cdom,'courselog',%filters);
9300: }
9301:
9302: sub userlog_query {
1.858 raeburn 9303: #
9304: # possible filters:
9305: # action: log check role
9306: # start: timestamp
9307: # end: timestamp
9308: #
1.240 www 9309: my ($uname,$udom,%filters)=@_;
9310: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9311: }
9312:
1.506 raeburn 9313: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9314:
9315: sub auto_run {
1.508 raeburn 9316: my ($cnum,$cdom) = @_;
1.876 raeburn 9317: my $response = 0;
9318: my $settings;
9319: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9320: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9321: $settings = $domconfig{'autoenroll'};
9322: if ($settings->{'run'} eq '1') {
9323: $response = 1;
9324: }
9325: } else {
1.934 raeburn 9326: my $homeserver;
9327: if (&is_course($cdom,$cnum)) {
9328: $homeserver = &homeserver($cnum,$cdom);
9329: } else {
9330: $homeserver = &domain($cdom,'primary');
9331: }
9332: if ($homeserver ne 'no_host') {
9333: $response = &reply('autorun:'.$cdom,$homeserver);
9334: }
1.876 raeburn 9335: }
1.506 raeburn 9336: return $response;
9337: }
1.776 albertel 9338:
1.506 raeburn 9339: sub auto_get_sections {
1.508 raeburn 9340: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9341: my $homeserver;
9342: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9343: $homeserver = &homeserver($cnum,$cdom);
9344: }
9345: if (!defined($homeserver)) {
9346: if ($cdom =~ /^$match_domain$/) {
9347: $homeserver = &domain($cdom,'primary');
9348: }
9349: }
9350: my @secs;
9351: if (defined($homeserver)) {
9352: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9353: unless ($response eq 'refused') {
9354: @secs = split(/:/,$response);
9355: }
1.506 raeburn 9356: }
9357: return @secs;
9358: }
1.776 albertel 9359:
1.506 raeburn 9360: sub auto_new_course {
1.1099 raeburn 9361: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9362: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9363: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9364: return $response;
9365: }
1.776 albertel 9366:
1.506 raeburn 9367: sub auto_validate_courseID {
1.508 raeburn 9368: my ($cnum,$cdom,$inst_course_id) = @_;
9369: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9370: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9371: return $response;
9372: }
1.776 albertel 9373:
1.1007 raeburn 9374: sub auto_validate_instcode {
1.1020 raeburn 9375: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9376: my ($homeserver,$response);
9377: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9378: $homeserver = &homeserver($cnum,$cdom);
9379: }
9380: if (!defined($homeserver)) {
9381: if ($cdom =~ /^$match_domain$/) {
9382: $homeserver = &domain($cdom,'primary');
9383: }
9384: }
1.1065 raeburn 9385: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9386: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9387: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9388: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9389: }
9390:
1.506 raeburn 9391: sub auto_create_password {
1.873 raeburn 9392: my ($cnum,$cdom,$authparam,$udom) = @_;
9393: my ($homeserver,$response);
1.506 raeburn 9394: my $create_passwd = 0;
9395: my $authchk = '';
1.873 raeburn 9396: if ($udom =~ /^$match_domain$/) {
9397: $homeserver = &domain($udom,'primary');
9398: }
9399: if ($homeserver eq '') {
9400: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9401: $homeserver = &homeserver($cnum,$cdom);
9402: }
9403: }
9404: if ($homeserver eq '') {
9405: $authchk = 'nodomain';
1.506 raeburn 9406: } else {
1.873 raeburn 9407: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9408: if ($response eq 'refused') {
9409: $authchk = 'refused';
9410: } else {
1.901 albertel 9411: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9412: }
1.506 raeburn 9413: }
9414: return ($authparam,$create_passwd,$authchk);
9415: }
9416:
1.706 raeburn 9417: sub auto_photo_permission {
9418: my ($cnum,$cdom,$students) = @_;
9419: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9420: my ($outcome,$perm_reqd,$conditions) =
9421: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9422: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9423: return (undef,undef);
9424: }
1.706 raeburn 9425: return ($outcome,$perm_reqd,$conditions);
9426: }
9427:
9428: sub auto_checkphotos {
9429: my ($uname,$udom,$pid) = @_;
9430: my $homeserver = &homeserver($uname,$udom);
9431: my ($result,$resulttype);
9432: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9433: &escape($uname).':'.&escape($pid),
9434: $homeserver));
1.709 albertel 9435: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9436: return (undef,undef);
9437: }
1.706 raeburn 9438: if ($outcome) {
9439: ($result,$resulttype) = split(/:/,$outcome);
9440: }
9441: return ($result,$resulttype);
9442: }
9443:
9444: sub auto_photochoice {
9445: my ($cnum,$cdom) = @_;
9446: my $homeserver = &homeserver($cnum,$cdom);
9447: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9448: &escape($cdom),
9449: $homeserver)));
1.709 albertel 9450: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9451: return (undef,undef);
9452: }
1.706 raeburn 9453: return ($update,$comment);
9454: }
9455:
9456: sub auto_photoupdate {
9457: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9458: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9459: my $host=&hostname($homeserver);
1.706 raeburn 9460: my $cmd = '';
9461: my $maxtries = 1;
1.800 albertel 9462: foreach my $affiliate (keys(%{$affiliatesref})) {
9463: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9464: }
9465: $cmd =~ s/%%$//;
9466: $cmd = &escape($cmd);
9467: my $query = 'institutionalphotos';
9468: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9469: unless ($queryid=~/^\Q$host\E\_/) {
9470: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9471: return 'error: '.$queryid;
9472: }
9473: my $reply = &get_query_reply($queryid);
9474: my $tries = 1;
9475: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9476: $reply = &get_query_reply($queryid);
9477: $tries ++;
9478: }
9479: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9480: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9481: } else {
9482: my @responses = split(/:/,$reply);
9483: my $outcome = shift(@responses);
9484: foreach my $item (@responses) {
9485: my ($key,$value) = split(/=/,$item);
9486: $$photo{$key} = $value;
9487: }
9488: return $outcome;
9489: }
9490: return 'error';
9491: }
9492:
1.521 raeburn 9493: sub auto_instcode_format {
1.793 albertel 9494: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9495: $cat_order) = @_;
1.521 raeburn 9496: my $courses = '';
1.772 raeburn 9497: my @homeservers;
1.521 raeburn 9498: if ($caller eq 'global') {
1.841 albertel 9499: my %servers = &get_servers($codedom,'library');
9500: foreach my $tryserver (keys(%servers)) {
9501: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9502: push(@homeservers,$tryserver);
9503: }
1.584 raeburn 9504: }
1.1022 raeburn 9505: } elsif ($caller eq 'requests') {
9506: if ($codedom =~ /^$match_domain$/) {
9507: my $chome = &domain($codedom,'primary');
9508: unless ($chome eq 'no_host') {
9509: push(@homeservers,$chome);
9510: }
9511: }
1.521 raeburn 9512: } else {
1.772 raeburn 9513: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9514: }
1.793 albertel 9515: foreach my $code (keys(%{$instcodes})) {
9516: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9517: }
9518: chop($courses);
1.772 raeburn 9519: my $ok_response = 0;
9520: my $response;
9521: while (@homeservers > 0 && $ok_response == 0) {
9522: my $server = shift(@homeservers);
9523: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9524: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9525: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9526: split(/:/,$response);
1.772 raeburn 9527: %{$codes} = (%{$codes},&str2hash($codes_str));
9528: push(@{$codetitles},&str2array($codetitles_str));
9529: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9530: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9531: $ok_response = 1;
9532: }
9533: }
9534: if ($ok_response) {
1.521 raeburn 9535: return 'ok';
1.772 raeburn 9536: } else {
9537: return $response;
1.521 raeburn 9538: }
9539: }
9540:
1.792 raeburn 9541: sub auto_instcode_defaults {
9542: my ($domain,$returnhash,$code_order) = @_;
9543: my @homeservers;
1.841 albertel 9544:
9545: my %servers = &get_servers($domain,'library');
9546: foreach my $tryserver (keys(%servers)) {
9547: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9548: push(@homeservers,$tryserver);
9549: }
1.792 raeburn 9550: }
1.841 albertel 9551:
1.792 raeburn 9552: my $response;
1.841 albertel 9553: foreach my $server (@homeservers) {
1.792 raeburn 9554: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9555: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9556:
9557: foreach my $pair (split(/\&/,$response)) {
9558: my ($name,$value)=split(/\=/,$pair);
9559: if ($name eq 'code_order') {
9560: @{$code_order} = split(/\&/,&unescape($value));
9561: } else {
9562: $returnhash->{&unescape($name)}=&unescape($value);
9563: }
9564: }
9565: return 'ok';
1.792 raeburn 9566: }
1.841 albertel 9567:
9568: return $response;
1.1003 raeburn 9569: }
9570:
9571: sub auto_possible_instcodes {
1.1007 raeburn 9572: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9573: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9574: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9575: return;
9576: }
1.1003 raeburn 9577: my (@homeservers,$uhome);
9578: if (defined(&domain($domain,'primary'))) {
9579: $uhome=&domain($domain,'primary');
9580: push(@homeservers,&domain($domain,'primary'));
9581: } else {
9582: my %servers = &get_servers($domain,'library');
9583: foreach my $tryserver (keys(%servers)) {
9584: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9585: push(@homeservers,$tryserver);
9586: }
9587: }
9588: }
9589: my $response;
9590: foreach my $server (@homeservers) {
9591: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9592: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9593: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9594: split(':',$response);
9595: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9596: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9597: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9598: my ($name,$value)=split('=',$item);
9599: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9600: }
9601: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9602: my ($name,$value)=split('=',$item);
9603: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9604: }
9605: return 'ok';
9606: }
9607: return $response;
9608: }
1.792 raeburn 9609:
1.1010 raeburn 9610: sub auto_courserequest_checks {
9611: my ($dom) = @_;
1.1020 raeburn 9612: my ($homeserver,%validations);
9613: if ($dom =~ /^$match_domain$/) {
9614: $homeserver = &domain($dom,'primary');
9615: }
9616: unless ($homeserver eq 'no_host') {
9617: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9618: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9619: my @items = split(/&/,$response);
9620: foreach my $item (@items) {
9621: my ($key,$value) = split('=',$item);
9622: $validations{&unescape($key)} = &thaw_unescape($value);
9623: }
9624: }
9625: }
1.1010 raeburn 9626: return %validations;
9627: }
9628:
1.1020 raeburn 9629: sub auto_courserequest_validation {
1.1255 raeburn 9630: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9631: my ($homeserver,$response);
9632: if ($dom =~ /^$match_domain$/) {
9633: $homeserver = &domain($dom,'primary');
9634: }
1.1255 raeburn 9635: unless ($homeserver eq 'no_host') {
9636: my $customdata;
9637: if (ref($custominfo) eq 'HASH') {
9638: $customdata = &freeze_escape($custominfo);
9639: }
1.1020 raeburn 9640: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9641: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9642: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9643: $customdata,$homeserver));
1.1020 raeburn 9644: }
9645: return $response;
9646: }
9647:
1.777 albertel 9648: sub auto_validate_class_sec {
1.918 raeburn 9649: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9650: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9651: my $ownerlist;
9652: if (ref($owners) eq 'ARRAY') {
9653: $ownerlist = join(',',@{$owners});
9654: } else {
9655: $ownerlist = $owners;
9656: }
1.773 raeburn 9657: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9658: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9659: return $response;
9660: }
9661:
1.1367 raeburn 9662: sub auto_validate_instclasses {
9663: my ($cdom,$cnum,$owners,$classesref) = @_;
9664: my ($homeserver,%validations);
9665: $homeserver = &homeserver($cnum,$cdom);
9666: unless ($homeserver eq 'no_host') {
9667: my $ownerlist;
9668: if (ref($owners) eq 'ARRAY') {
9669: $ownerlist = join(',',@{$owners});
9670: } else {
9671: $ownerlist = $owners;
9672: }
9673: if (ref($classesref) eq 'HASH') {
9674: my $classes = &freeze_escape($classesref);
9675: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9676: ':'.$cdom.':'.$classes,$homeserver);
9677: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9678: my @items = split(/&/,$response);
9679: foreach my $item (@items) {
9680: my ($key,$value) = split('=',$item);
9681: $validations{&unescape($key)} = &thaw_unescape($value);
9682: }
9683: }
9684: }
9685: }
9686: return %validations;
9687: }
9688:
1.1248 raeburn 9689: sub auto_crsreq_update {
9690: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9691: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9692: my ($homeserver,%crsreqresponse);
9693: if ($cdom =~ /^$match_domain$/) {
9694: $homeserver = &domain($cdom,'primary');
9695: }
9696: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9697: my $info;
9698: if (ref($inbound) eq 'HASH') {
9699: $info = &freeze_escape($inbound);
9700: }
9701: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9702: ':'.&escape($action).':'.&escape($ownername).':'.
9703: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9704: &escape($title).':'.&escape($code).':'.
9705: &escape($accessstart).':'.&escape($accessend).':'.$info,
9706: $homeserver);
1.1248 raeburn 9707: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9708: my @items = split(/&/,$response);
9709: foreach my $item (@items) {
9710: my ($key,$value) = split('=',$item);
9711: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9712: }
9713: }
9714: }
9715: return \%crsreqresponse;
9716: }
9717:
1.1305 raeburn 9718: sub auto_export_grades {
1.1309 raeburn 9719: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9720: my ($homeserver,%exportresponse);
9721: if ($cdom =~ /^$match_domain$/) {
9722: $homeserver = &domain($cdom,'primary');
9723: }
9724: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9725: my $info;
9726: if (ref($inforef) eq 'HASH') {
9727: $info = &freeze_escape($inforef);
9728: }
9729: if (ref($gradesref) eq 'HASH') {
9730: my $grades = &freeze_escape($gradesref);
9731: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9732: $info.':'.$grades,$homeserver);
9733: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9734: my @items = split(/&/,$response);
9735: foreach my $item (@items) {
9736: my ($key,$value) = split('=',$item);
9737: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9738: }
9739: }
9740: }
9741: }
9742: return \%exportresponse;
1.1305 raeburn 9743: }
9744:
1.1287 raeburn 9745: sub check_instcode_cloning {
9746: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9747: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9748: return;
9749: }
9750: my $canclone;
9751: if (@{$code_order} > 0) {
9752: my $instcoderegexp ='^';
9753: my @clonecodes = split(/\&/,$cloner);
9754: foreach my $item (@{$code_order}) {
9755: if (grep(/^\Q$item\E=/,@clonecodes)) {
9756: foreach my $pair (@clonecodes) {
9757: my ($key,$val) = split(/\=/,$pair,2);
9758: $val = &unescape($val);
9759: if ($key eq $item) {
9760: $instcoderegexp .= '('.$val.')';
9761: last;
9762: }
9763: }
9764: } else {
9765: $instcoderegexp .= $codedefaults->{$item};
9766: }
9767: }
9768: $instcoderegexp .= '$';
9769: my (@from,@to);
9770: eval {
9771: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9772: (@to) = ($clonetocode =~ /$instcoderegexp/);
9773: };
9774: if ((@from > 0) && (@to > 0)) {
9775: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9776: if (!@diffs) {
9777: $canclone = 1;
9778: }
9779: }
9780: }
9781: return $canclone;
9782: }
9783:
9784: sub default_instcode_cloning {
9785: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9786: my (%codedefaults,@code_order,$canclone);
9787: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9788: %codedefaults = %{$codedefaultsref};
9789: @code_order = @{$codeorderref};
9790: } elsif ($clonedom) {
9791: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9792: }
9793: if (($domdefclone) && (@code_order)) {
9794: my @clonecodes = split(/\+/,$domdefclone);
9795: my $instcoderegexp ='^';
9796: foreach my $item (@code_order) {
9797: if (grep(/^\Q$item\E$/,@clonecodes)) {
9798: $instcoderegexp .= '('.$codedefaults{$item}.')';
9799: } else {
9800: $instcoderegexp .= $codedefaults{$item};
9801: }
9802: }
9803: $instcoderegexp .= '$';
9804: my (@from,@to);
9805: eval {
9806: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9807: (@to) = ($clonetocode =~ /$instcoderegexp/);
9808: };
9809: if ((@from > 0) && (@to > 0)) {
9810: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9811: if (!@diffs) {
9812: $canclone = 1;
9813: }
9814: }
9815: }
9816: return $canclone;
9817: }
9818:
1.679 raeburn 9819: # ------------------------------------------------------- Course Group routines
9820:
9821: sub get_coursegroups {
1.809 raeburn 9822: my ($cdom,$cnum,$group,$namespace) = @_;
9823: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9824: }
9825:
1.679 raeburn 9826: sub modify_coursegroup {
9827: my ($cdom,$cnum,$groupsettings) = @_;
9828: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9829: }
9830:
1.809 raeburn 9831: sub toggle_coursegroup_status {
9832: my ($cdom,$cnum,$group,$action) = @_;
9833: my ($from_namespace,$to_namespace);
9834: if ($action eq 'delete') {
9835: $from_namespace = 'coursegroups';
9836: $to_namespace = 'deleted_groups';
9837: } else {
9838: $from_namespace = 'deleted_groups';
9839: $to_namespace = 'coursegroups';
9840: }
9841: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9842: if (my $tmp = &error(%curr_group)) {
9843: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9844: return ('read error',$tmp);
9845: } else {
9846: my %savedsettings = %curr_group;
1.809 raeburn 9847: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9848: my $deloutcome;
9849: if ($result eq 'ok') {
1.809 raeburn 9850: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9851: } else {
9852: return ('write error',$result);
9853: }
9854: if ($deloutcome eq 'ok') {
9855: return 'ok';
9856: } else {
9857: return ('delete error',$deloutcome);
9858: }
9859: }
9860: }
9861:
1.679 raeburn 9862: sub modify_group_roles {
1.957 raeburn 9863: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9864: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9865: my $role = 'gr/'.&escape($userprivs);
9866: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9867: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9868: if ($result eq 'ok') {
9869: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9870: }
1.679 raeburn 9871: return $result;
9872: }
9873:
9874: sub modify_coursegroup_membership {
9875: my ($cdom,$cnum,$membership) = @_;
9876: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9877: return $result;
9878: }
9879:
1.682 raeburn 9880: sub get_active_groups {
9881: my ($udom,$uname,$cdom,$cnum) = @_;
9882: my $now = time;
9883: my %groups = ();
9884: foreach my $key (keys(%env)) {
1.811 albertel 9885: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9886: my ($start,$end) = split(/\./,$env{$key});
9887: if (($end!=0) && ($end<$now)) { next; }
9888: if (($start!=0) && ($start>$now)) { next; }
9889: if ($1 eq $cdom && $2 eq $cnum) {
9890: $groups{$3} = $env{$key} ;
9891: }
9892: }
9893: }
9894: return %groups;
9895: }
9896:
1.683 raeburn 9897: sub get_group_membership {
9898: my ($cdom,$cnum,$group) = @_;
9899: return(&dump('groupmembership',$cdom,$cnum,$group));
9900: }
9901:
9902: sub get_users_groups {
9903: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9904: my @usersgroups;
1.683 raeburn 9905: my $cachetime=1800;
9906:
9907: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9908: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9909: if (defined($cached)) {
1.734 albertel 9910: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9911: } else {
9912: $grouplist = '';
1.816 raeburn 9913: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9914: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9915: my $access_end = $env{'course.'.$courseid.
9916: '.default_enrollment_end_date'};
9917: my $now = time;
9918: foreach my $key (keys(%roleshash)) {
9919: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9920: my $group = $1;
9921: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9922: my $start = $2;
9923: my $end = $1;
9924: if ($start == -1) { next; } # deleted from group
9925: if (($start!=0) && ($start>$now)) { next; }
9926: if (($end!=0) && ($end<$now)) {
9927: if ($access_end && $access_end < $now) {
9928: if ($access_end - $end < 86400) {
9929: push(@usersgroups,$group);
1.733 raeburn 9930: }
9931: }
1.817 raeburn 9932: next;
1.733 raeburn 9933: }
1.817 raeburn 9934: push(@usersgroups,$group);
1.683 raeburn 9935: }
9936: }
9937: }
1.817 raeburn 9938: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9939: $grouplist = join(':',@usersgroups);
9940: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9941: }
1.733 raeburn 9942: return @usersgroups;
1.683 raeburn 9943: }
9944:
9945: sub devalidate_getgroups_cache {
9946: my ($udom,$uname,$cdom,$cnum)=@_;
9947: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9948:
1.683 raeburn 9949: my $hashid="$udom:$uname:$courseid";
9950: &devalidate_cache_new('getgroups',$hashid);
9951: }
9952:
1.12 www 9953: # ------------------------------------------------------------------ Plain Text
9954:
9955: sub plaintext {
1.988 raeburn 9956: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9957: if ($short =~ m{^cr/}) {
1.758 albertel 9958: return (split('/',$short))[-1];
9959: }
1.742 raeburn 9960: if (!defined($cid)) {
9961: $cid = $env{'request.course.id'};
9962: }
9963: my %rolenames = (
1.1008 raeburn 9964: Course => 'std',
9965: Community => 'alt1',
1.1305 raeburn 9966: Placement => 'std',
1.742 raeburn 9967: );
1.1037 raeburn 9968: if ($cid ne '') {
9969: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9970: unless ($forcedefault) {
9971: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9972: &Apache::lonlocal::mt_escape(\$roletext);
9973: return &Apache::lonlocal::mt($roletext);
9974: }
9975: }
9976: }
9977: if ((defined($type)) && (defined($rolenames{$type})) &&
9978: (defined($rolenames{$type})) &&
9979: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9980: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9981: } elsif ($cid ne '') {
9982: my $crstype = $env{'course.'.$cid.'.type'};
9983: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9984: (defined($prp{$short}{$rolenames{$crstype}}))) {
9985: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9986: }
1.742 raeburn 9987: }
1.1037 raeburn 9988: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9989: }
9990:
9991: # ----------------------------------------------------------------- Assign Role
9992:
9993: sub assignrole {
1.957 raeburn 9994: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9995: $context)=@_;
1.21 www 9996: my $mrole;
9997: if ($role =~ /^cr\//) {
1.393 www 9998: my $cwosec=$url;
1.811 albertel 9999: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10000: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10001: my $refused = 1;
10002: if ($context eq 'requestcourses') {
10003: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10004: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10005: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10006: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10007: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10008: if ($crsenv{'internal.courseowner'} eq
10009: $env{'user.name'}.':'.$env{'user.domain'}) {
10010: $refused = '';
10011: }
10012: }
10013: }
10014: }
10015: }
10016: if ($refused) {
10017: &logthis('Refused custom assignrole: '.
10018: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10019: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10020: return 'refused';
10021: }
1.104 www 10022: }
1.21 www 10023: $mrole='cr';
1.678 raeburn 10024: } elsif ($role =~ /^gr\//) {
10025: my $cwogrp=$url;
1.811 albertel 10026: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10027: unless (&allowed('mdg',$cwogrp)) {
10028: &logthis('Refused group assignrole: '.
10029: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10030: $env{'user.name'}.' at '.$env{'user.domain'});
10031: return 'refused';
10032: }
10033: $mrole='gr';
1.21 www 10034: } else {
1.82 www 10035: my $cwosec=$url;
1.811 albertel 10036: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10037: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10038: my $refused;
10039: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10040: if (!(&allowed('c'.$role,$url))) {
10041: $refused = 1;
10042: }
10043: } else {
10044: $refused = 1;
10045: }
1.947 raeburn 10046: if ($refused) {
1.1045 raeburn 10047: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10048: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10049: my %crsenv;
10050: if ($role eq 'cc' || $role eq 'co') {
10051: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10052: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10053: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10054: if ($crsenv{'internal.courseowner'} eq
10055: $env{'user.name'}.':'.$env{'user.domain'}) {
10056: $refused = '';
10057: }
10058: }
10059: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10060: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10061: if ($crsenv{'internal.courseowner'} eq
10062: $env{'user.name'}.':'.$env{'user.domain'}) {
10063: $refused = '';
10064: }
10065: }
10066: }
10067: }
1.1368 raeburn 10068: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10069: if ($role eq 'st') {
10070: $refused = '';
1.1377 raeburn 10071: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10072: $refused = '';
10073: }
1.1017 raeburn 10074: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10075: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10076: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10077: my $wrongcc;
10078: if ($cnum =~ /^$match_community$/) {
10079: $wrongcc = 1 if ($role eq 'cc');
10080: } else {
10081: $wrongcc = 1 if ($role eq 'co');
10082: }
10083: unless ($wrongcc) {
10084: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10085: if ($crsenv{'internal.courseowner'} eq
10086: $env{'user.name'}.':'.$env{'user.domain'}) {
10087: $refused = '';
10088: }
1.1017 raeburn 10089: }
10090: }
1.1183 raeburn 10091: } elsif ($context eq 'requestauthor') {
10092: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10093: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10094: if ($env{'environment.requestauthor'} eq 'automatic') {
10095: $refused = '';
10096: } else {
10097: my %domdefaults = &get_domain_defaults($udom);
10098: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10099: my $checkbystatus;
10100: if ($env{'user.adv'}) {
10101: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10102: if ($disposition eq 'automatic') {
10103: $refused = '';
10104: } elsif ($disposition eq '') {
10105: $checkbystatus = 1;
10106: }
10107: } else {
10108: $checkbystatus = 1;
10109: }
10110: if ($checkbystatus) {
10111: if ($env{'environment.inststatus'}) {
10112: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10113: foreach my $type (@inststatuses) {
10114: if (($type ne '') &&
10115: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10116: $refused = '';
10117: }
10118: }
10119: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10120: $refused = '';
10121: }
10122: }
10123: }
10124: }
10125: }
1.1017 raeburn 10126: }
10127: if ($refused) {
1.947 raeburn 10128: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10129: ' '.$role.' '.$end.' '.$start.' by '.
10130: $env{'user.name'}.' at '.$env{'user.domain'});
10131: return 'refused';
10132: }
1.932 raeburn 10133: }
1.1131 raeburn 10134: } elsif ($role eq 'au') {
10135: if ($url ne '/'.$udom.'/') {
10136: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10137: ' to assign author role for '.$uname.':'.$udom.
10138: ' in domain: '.$url.' refused (wrong domain).');
10139: return 'refused';
10140: }
1.104 www 10141: }
1.21 www 10142: $mrole=$role;
10143: }
1.620 albertel 10144: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10145: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10146: if ($end) { $command.='_'.$end; }
1.21 www 10147: if ($start) {
10148: if ($end) {
1.81 www 10149: $command.='_'.$start;
1.21 www 10150: } else {
1.81 www 10151: $command.='_0_'.$start;
1.21 www 10152: }
10153: }
1.739 raeburn 10154: my $origstart = $start;
10155: my $origend = $end;
1.957 raeburn 10156: my $delflag;
1.357 www 10157: # actually delete
10158: if ($deleteflag) {
1.373 www 10159: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10160: # modify command to delete the role
1.620 albertel 10161: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10162: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10163: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10164: # set start and finish to negative values for userrolelog
10165: $start=-1;
10166: $end=-1;
1.957 raeburn 10167: $delflag = 1;
1.357 www 10168: }
10169: }
10170: # send command
1.349 www 10171: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10172: # log new user role if status is ok
1.349 www 10173: if ($answer eq 'ok') {
1.663 raeburn 10174: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10175: if (($role eq 'cc') || ($role eq 'in') ||
10176: ($role eq 'ep') || ($role eq 'ad') ||
10177: ($role eq 'ta') || ($role eq 'st') ||
10178: ($role=~/^cr/) || ($role eq 'gr') ||
10179: ($role eq 'co')) {
1.1200 raeburn 10180: # for course roles, perform group memberships changes triggered by role change.
10181: unless ($role =~ /^gr/) {
10182: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10183: $origstart,$selfenroll,$context);
10184: }
1.1184 raeburn 10185: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10186: $selfenroll,$context);
10187: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10188: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10189: ($role eq 'da')) {
1.1184 raeburn 10190: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10191: $context);
10192: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10193: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10194: $context);
10195: }
1.1053 raeburn 10196: if ($role eq 'cc') {
10197: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10198: }
1.349 www 10199: }
10200: return $answer;
1.169 harris41 10201: }
10202:
1.1053 raeburn 10203: sub autoupdate_coowners {
10204: my ($url,$end,$start,$uname,$udom) = @_;
10205: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10206: if (($cdom ne '') && ($cnum ne '')) {
10207: my $now = time;
10208: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10209: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10210: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10211: my $instcode = $coursehash{'internal.coursecode'};
10212: if ($instcode ne '') {
1.1056 raeburn 10213: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10214: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10215: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10216: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10217: if ($result eq 'valid') {
10218: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10219: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10220: push(@newcoowners,$coowner);
10221: }
10222: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10223: push(@newcoowners,$uname.':'.$udom);
10224: }
10225: @newcoowners = sort(@newcoowners);
10226: } else {
10227: push(@newcoowners,$uname.':'.$udom);
10228: }
10229: } else {
10230: if ($coursehash{'internal.co-owners'}) {
10231: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10232: unless ($coowner eq $uname.':'.$udom) {
10233: push(@newcoowners,$coowner);
10234: }
10235: }
10236: unless (@newcoowners > 0) {
10237: $delcoowners = 1;
10238: $coowners = '';
10239: }
10240: }
10241: }
10242: if (@newcoowners || $delcoowners) {
10243: &store_coowners($cdom,$cnum,$coursehash{'home'},
10244: $delcoowners,@newcoowners);
10245: }
10246: }
10247: }
10248: }
10249: }
10250: }
10251: }
10252:
10253: sub store_coowners {
10254: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10255: my $cid = $cdom.'_'.$cnum;
10256: my ($coowners,$delresult,$putresult);
10257: if (@newcoowners) {
10258: $coowners = join(',',@newcoowners);
10259: my %coownershash = (
10260: 'internal.co-owners' => $coowners,
10261: );
10262: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10263: if ($putresult eq 'ok') {
10264: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10265: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10266: }
10267: }
10268: }
10269: if ($delcoowners) {
10270: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10271: if ($delresult eq 'ok') {
10272: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10273: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10274: }
10275: }
10276: }
10277: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10278: my %crsinfo =
10279: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10280: if (ref($crsinfo{$cid}) eq 'HASH') {
10281: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10282: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10283: }
10284: }
10285: }
10286:
1.169 harris41 10287: # -------------------------------------------------- Modify user authentication
1.197 www 10288: # Overrides without validation
10289:
1.169 harris41 10290: sub modifyuserauth {
10291: my ($udom,$uname,$umode,$upass)=@_;
10292: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10293: my $allowed;
10294: if (&allowed('mau',$udom)) {
10295: $allowed = 1;
10296: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10297: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10298: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10299: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10300: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10301: if (($cdom ne '') && ($cnum ne '')) {
10302: my $is_owner = &is_course_owner($cdom,$cnum);
10303: if ($is_owner) {
10304: $allowed = 1;
10305: }
10306: }
10307: }
10308: unless ($allowed) { return 'refused'; }
1.197 www 10309: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10310: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10311: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10312: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10313: &escape($upass),$uhome);
1.620 albertel 10314: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10315: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10316: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10317: &log($udom,,$uname,$uhome,
1.620 albertel 10318: 'Authentication changed by '.$env{'user.domain'}.', '.
10319: $env{'user.name'}.', '.$umode.
1.197 www 10320: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 10321: unless ($reply eq 'ok') {
1.197 www 10322: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10323: return 'error: '.$reply;
10324: }
1.170 harris41 10325: return 'ok';
1.80 www 10326: }
10327:
1.81 www 10328: # --------------------------------------------------------------- Modify a user
1.80 www 10329:
1.81 www 10330: sub modifyuser {
1.206 matthew 10331: my ($udom, $uname, $uid,
10332: $umode, $upass, $first,
10333: $middle, $last, $gene,
1.1058 raeburn 10334: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10335: $udom= &LONCAPA::clean_domain($udom);
10336: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10337: my $showcandelete = 'none';
10338: if (ref($candelete) eq 'ARRAY') {
10339: if (@{$candelete} > 0) {
10340: $showcandelete = join(', ',@{$candelete});
10341: }
10342: }
1.81 www 10343: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10344: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10345: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10346: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10347: ' desiredhome not specified').
1.620 albertel 10348: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10349: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10350: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10351: my $newuser;
10352: if ($uhome eq 'no_host') {
10353: $newuser = 1;
1.1368 raeburn 10354: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10355: ($umode eq 'lti')) {
10356: return 'error: more information needed to create new user';
10357: }
1.1075 raeburn 10358: }
1.80 www 10359: # ----------------------------------------------------------------- Create User
1.406 albertel 10360: if (($uhome eq 'no_host') &&
1.1368 raeburn 10361: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10362: my $unhome='';
1.844 albertel 10363: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10364: $unhome = $desiredhome;
1.620 albertel 10365: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10366: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10367: } else { # load balancing routine for determining $unhome
1.81 www 10368: my $loadm=10000000;
1.841 albertel 10369: my %servers = &get_servers($udom,'library');
10370: foreach my $tryserver (keys(%servers)) {
10371: my $answer=reply('load',$tryserver);
10372: if (($answer=~/\d+/) && ($answer<$loadm)) {
10373: $loadm=$answer;
10374: $unhome=$tryserver;
10375: }
1.80 www 10376: }
10377: }
10378: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10379: return 'error: unable to find a home server for '.$uname.
10380: ' in domain '.$udom;
1.80 www 10381: }
10382: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10383: &escape($upass),$unhome);
10384: unless ($reply eq 'ok') {
10385: return 'error: '.$reply;
10386: }
1.230 stredwic 10387: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10388: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10389: return 'error: unable verify users home machine.';
1.80 www 10390: }
1.209 matthew 10391: } # End of creation of new user
1.80 www 10392: # ---------------------------------------------------------------------- Add ID
10393: if ($uid) {
10394: $uid=~tr/A-Z/a-z/;
10395: my %uidhash=&idrget($udom,$uname);
1.196 www 10396: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10397: && (!$forceid)) {
1.80 www 10398: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10399: return 'error: user id "'.$uid.'" does not match '.
10400: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10401: }
10402: } else {
1.1300 raeburn 10403: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10404: }
10405: }
10406: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10407: my @tmp=&get('environment',
1.899 raeburn 10408: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10409: 'permanentemail','inststatus'],
1.134 albertel 10410: $udom,$uname);
1.1075 raeburn 10411: my (%names,%oldnames);
1.313 matthew 10412: if ($tmp[0] =~ m/^error:.*/) {
10413: %names=();
10414: } else {
10415: %names = @tmp;
1.1075 raeburn 10416: %oldnames = %names;
1.313 matthew 10417: }
1.388 www 10418: #
1.1058 raeburn 10419: # If name, email and/or uid are blank (e.g., because an uploaded file
10420: # of users did not contain them), do not overwrite existing values
10421: # unless field is in $candelete array ref.
10422: #
10423:
10424: my @fields = ('firstname','middlename','lastname','generation',
10425: 'permanentemail','id');
10426: my %newvalues;
10427: if (ref($candelete) eq 'ARRAY') {
10428: foreach my $field (@fields) {
10429: if (grep(/^\Q$field\E$/,@{$candelete})) {
10430: if ($field eq 'firstname') {
10431: $names{$field} = $first;
10432: } elsif ($field eq 'middlename') {
10433: $names{$field} = $middle;
10434: } elsif ($field eq 'lastname') {
10435: $names{$field} = $last;
10436: } elsif ($field eq 'generation') {
10437: $names{$field} = $gene;
10438: } elsif ($field eq 'permanentemail') {
10439: $names{$field} = $email;
10440: } elsif ($field eq 'id') {
10441: $names{$field} = $uid;
10442: }
10443: }
10444: }
10445: }
1.388 www 10446: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10447: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10448: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10449: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10450: if ($email) {
10451: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10452: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10453: }
1.899 raeburn 10454: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10455: if (defined($inststatus)) {
10456: $names{'inststatus'} = '';
10457: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10458: if (ref($usertypes) eq 'HASH') {
10459: my @okstatuses;
10460: foreach my $item (split(/:/,$inststatus)) {
10461: if (defined($usertypes->{$item})) {
10462: push(@okstatuses,$item);
10463: }
10464: }
10465: if (@okstatuses) {
10466: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10467: }
10468: }
10469: }
1.1075 raeburn 10470: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10471: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10472: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10473: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10474: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10475: } else {
10476: $logmsg .= ' during self creation';
10477: }
1.1075 raeburn 10478: my $changed;
10479: if ($newuser) {
10480: $changed = 1;
10481: } else {
10482: foreach my $field (@fields) {
10483: if ($names{$field} ne $oldnames{$field}) {
10484: $changed = 1;
10485: last;
10486: }
10487: }
10488: }
10489: unless ($changed) {
10490: $logmsg = 'No changes in user information needed for: '.$logmsg;
10491: &logthis($logmsg);
10492: return 'ok';
10493: }
10494: my $reply = &put('environment', \%names, $udom,$uname);
10495: if ($reply ne 'ok') {
10496: return 'error: '.$reply;
10497: }
1.1087 raeburn 10498: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10499: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10500: }
1.1075 raeburn 10501: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10502: &devalidate_cache_new('namescache',$uname.':'.$udom);
10503: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10504: &logthis($logmsg);
1.134 albertel 10505: return 'ok';
1.80 www 10506: }
10507:
1.81 www 10508: # -------------------------------------------------------------- Modify student
1.80 www 10509:
1.81 www 10510: sub modifystudent {
10511: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10512: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10513: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10514: if (!$cid) {
1.620 albertel 10515: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10516: return 'not_in_class';
10517: }
1.80 www 10518: }
10519: # --------------------------------------------------------------- Make the user
1.81 www 10520: my $reply=&modifyuser
1.209 matthew 10521: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10522: $desiredhome,$email,$inststatus);
1.80 www 10523: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10524: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10525: # student's environment
1.297 matthew 10526: $uid = undef if (!$forceid);
1.455 albertel 10527: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10528: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10529: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10530: return $reply;
10531: }
10532:
10533: sub modify_student_enrollment {
1.1216 raeburn 10534: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10535: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10536: my ($cdom,$cnum,$chome);
10537: if (!$cid) {
1.620 albertel 10538: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10539: return 'not_in_class';
10540: }
1.620 albertel 10541: $cdom=$env{'course.'.$cid.'.domain'};
10542: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10543: } else {
10544: ($cdom,$cnum)=split(/_/,$cid);
10545: }
1.620 albertel 10546: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10547: if (!$chome) {
1.457 raeburn 10548: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10549: }
1.455 albertel 10550: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10551: # Make sure the user exists
1.81 www 10552: my $uhome=&homeserver($uname,$udom);
10553: if (($uhome eq '') || ($uhome eq 'no_host')) {
10554: return 'error: no such user';
10555: }
1.297 matthew 10556: # Get student data if we were not given enough information
10557: if (!defined($first) || $first eq '' ||
10558: !defined($last) || $last eq '' ||
10559: !defined($uid) || $uid eq '' ||
10560: !defined($middle) || $middle eq '' ||
10561: !defined($gene) || $gene eq '') {
1.294 matthew 10562: # They did not supply us with enough data to enroll the student, so
10563: # we need to pick up more information.
1.297 matthew 10564: my %tmp = &get('environment',
1.294 matthew 10565: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10566: ,$udom,$uname);
10567:
1.800 albertel 10568: #foreach my $key (keys(%tmp)) {
10569: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10570: #}
1.294 matthew 10571: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10572: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10573: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10574: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10575: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10576: }
1.556 albertel 10577: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10578: my $user = "$uname:$udom";
10579: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10580: my $reply=cput('classlist',
1.1148 raeburn 10581: {$user =>
1.1314 raeburn 10582: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10583: $cdom,$cnum);
1.1148 raeburn 10584: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10585: &devalidate_getsection_cache($udom,$uname,$cid);
10586: } else {
1.81 www 10587: return 'error: '.$reply;
10588: }
1.297 matthew 10589: # Add student role to user
1.83 www 10590: my $uurl='/'.$cid;
1.81 www 10591: $uurl=~s/\_/\//g;
10592: if ($usec) {
10593: $uurl.='/'.$usec;
10594: }
1.1148 raeburn 10595: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10596: $selfenroll,$context);
10597: if ($result ne 'ok') {
10598: if ($old_entry{$user} ne '') {
10599: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10600: } else {
10601: $reply = &del('classlist',[$user],$cdom,$cnum);
10602: }
10603: }
10604: return $result;
1.21 www 10605: }
10606:
1.556 albertel 10607: sub format_name {
10608: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10609: my $name;
10610: if ($first ne 'lastname') {
10611: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10612: } else {
10613: if ($lastname=~/\S/) {
10614: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10615: $name=~s/\s+,/,/;
10616: } else {
10617: $name.= $firstname.' '.$middlename.' '.$generation;
10618: }
10619: }
10620: $name=~s/^\s+//;
10621: $name=~s/\s+$//;
10622: $name=~s/\s+/ /g;
10623: return $name;
10624: }
10625:
1.84 www 10626: # ------------------------------------------------- Write to course preferences
10627:
10628: sub writecoursepref {
10629: my ($courseid,%prefs)=@_;
10630: $courseid=~s/^\///;
10631: $courseid=~s/\_/\//g;
10632: my ($cdomain,$cnum)=split(/\//,$courseid);
10633: my $chome=homeserver($cnum,$cdomain);
10634: if (($chome eq '') || ($chome eq 'no_host')) {
10635: return 'error: no such course';
10636: }
10637: my $cstring='';
1.800 albertel 10638: foreach my $pref (keys(%prefs)) {
10639: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10640: }
1.84 www 10641: $cstring=~s/\&$//;
10642: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10643: }
10644:
10645: # ---------------------------------------------------------- Make/modify course
10646:
10647: sub createcourse {
1.741 raeburn 10648: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 10649: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10650: $url=&declutter($url);
10651: my $cid='';
1.1028 raeburn 10652: if ($context eq 'requestcourses') {
10653: my $can_create = 0;
10654: my ($ownername,$ownerdom) = split(':',$course_owner);
10655: if ($udom eq $ownerdom) {
1.1423 raeburn 10656: my $reload;
10657: if (($callercontext eq 'auto') &&
10658: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10659: $reload = 'reload';
10660: }
10661: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 10662: $context)) {
10663: $can_create = 1;
10664: }
10665: } else {
10666: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10667: $category);
10668: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10669: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10670: if (@curr > 0) {
10671: my @options = qw(approval validate autolimit);
10672: my $optregex = join('|',@options);
10673: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10674: $can_create = 1;
10675: }
10676: }
10677: }
10678: }
10679: if ($can_create) {
10680: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10681: unless (&allowed('ccc',$udom)) {
10682: return 'refused';
10683: }
1.1017 raeburn 10684: }
10685: } else {
10686: return 'refused';
10687: }
1.1028 raeburn 10688: } elsif (!&allowed('ccc',$udom)) {
10689: return 'refused';
1.84 www 10690: }
1.1011 raeburn 10691: # --------------------------------------------------------------- Get Unique ID
10692: my $uname;
10693: if ($cnum =~ /^$match_courseid$/) {
10694: my $chome=&homeserver($cnum,$udom,'true');
10695: if (($chome eq '') || ($chome eq 'no_host')) {
10696: $uname = $cnum;
10697: } else {
1.1038 raeburn 10698: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10699: }
10700: } else {
1.1038 raeburn 10701: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10702: }
10703: return $uname if ($uname =~ /^error/);
10704: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10705: if (!defined($course_server)) {
10706: if (defined(&domain($udom,'primary'))) {
10707: $course_server = &domain($udom,'primary');
10708: } else {
10709: $course_server = $env{'user.home'};
10710: }
10711: }
10712: my %host_servers =
10713: &Apache::lonnet::get_servers($udom,'library');
10714: unless ($host_servers{$course_server}) {
10715: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10716: }
1.84 www 10717: # ------------------------------------------------------------- Make the course
10718: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10719: $course_server);
1.84 www 10720: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10721: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10722: if (($uhome eq '') || ($uhome eq 'no_host')) {
10723: return 'error: no such course';
10724: }
1.271 www 10725: # ----------------------------------------------------------------- Course made
1.516 raeburn 10726: # log existence
1.1029 raeburn 10727: my $now = time;
1.918 raeburn 10728: my $newcourse = {
10729: $udom.'_'.$uname => {
1.921 raeburn 10730: description => $description,
10731: inst_code => $inst_code,
10732: owner => $course_owner,
10733: type => $crstype,
1.1029 raeburn 10734: creator => $env{'user.name'}.':'.
10735: $env{'user.domain'},
10736: created => $now,
10737: context => $context,
1.918 raeburn 10738: },
10739: };
1.921 raeburn 10740: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10741: # set toplevel url
1.271 www 10742: my $topurl=$url;
10743: unless ($nonstandard) {
10744: # ------------------------------------------ For standard courses, make top url
10745: my $mapurl=&clutter($url);
1.278 www 10746: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10747: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10748: <map>
10749: <resource id="1" type="start"></resource>
10750: <resource id="2" src="$mapurl"></resource>
10751: <resource id="3" type="finish"></resource>
10752: <link index="1" from="1" to="2"></link>
10753: <link index="2" from="2" to="3"></link>
10754: </map>
10755: ENDINITMAP
10756: $topurl=&declutter(
1.638 albertel 10757: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10758: );
10759: }
10760: # ----------------------------------------------------------- Write preferences
1.84 www 10761: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10762: ('description' => $description,
10763: 'url' => $topurl,
10764: 'internal.creator' => $env{'user.name'}.':'.
10765: $env{'user.domain'},
10766: 'internal.created' => $now,
10767: 'internal.creationcontext' => $context)
10768: );
1.84 www 10769: return '/'.$udom.'/'.$uname;
10770: }
10771:
1.1011 raeburn 10772: # ------------------------------------------------------------------- Create ID
10773: sub generate_coursenum {
1.1038 raeburn 10774: my ($udom,$crstype) = @_;
1.1011 raeburn 10775: my $domdesc = &domain($udom);
10776: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10777: my $first;
10778: if ($crstype eq 'Community') {
10779: $first = '0';
10780: } else {
10781: $first = int(1+rand(9));
10782: }
10783: my $uname=$first.
1.1011 raeburn 10784: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10785: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10786: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10787: # ----------------------------------------------- Make sure that does not exist
10788: my $uhome=&homeserver($uname,$udom,'true');
10789: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10790: if ($crstype eq 'Community') {
10791: $first = '0';
10792: } else {
10793: $first = int(1+rand(9));
10794: }
10795: $uname=$first.
1.1011 raeburn 10796: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10797: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10798: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10799: $uhome=&homeserver($uname,$udom,'true');
10800: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10801: return 'error: unable to generate unique course-ID';
10802: }
10803: }
10804: return $uname;
10805: }
10806:
1.813 albertel 10807: sub is_course {
1.1167 droeschl 10808: my ($cdom, $cnum) = scalar(@_) == 1 ?
10809: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10810:
1.1381 raeburn 10811: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10812: my $uhome=&homeserver($cnum,$cdom);
10813: my $iscourse;
10814: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 10815: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 10816: } else {
10817: my $hashid = $cdom.':'.$cnum;
10818: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10819: unless (defined($cached)) {
10820: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10821: $cnum,undef,undef,'.');
10822: $iscourse = 0;
10823: if (exists($courses{$cdom.'_'.$cnum})) {
10824: $iscourse = 1;
10825: }
10826: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10827: }
10828: }
10829: return unless ($iscourse);
1.1167 droeschl 10830: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10831: }
10832:
1.1015 raeburn 10833: sub store_userdata {
10834: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10835: my $result;
1.1016 raeburn 10836: if ($datakey ne '') {
1.1013 raeburn 10837: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10838: if ($udom eq '' || $uname eq '') {
10839: $udom = $env{'user.domain'};
10840: $uname = $env{'user.name'};
10841: }
10842: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10843: if (($uhome eq '') || ($uhome eq 'no_host')) {
10844: $result = 'error: no_host';
10845: } else {
10846: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10847: $storehash->{'host'} = $perlvar{'lonHostID'};
10848:
10849: my $namevalue='';
10850: foreach my $key (keys(%{$storehash})) {
10851: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10852: }
10853: $namevalue=~s/\&$//;
1.1224 raeburn 10854: unless ($namespace eq 'courserequests') {
10855: $datakey = &escape($datakey);
10856: }
1.1105 raeburn 10857: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10858: $namevalue,$uhome);
1.1013 raeburn 10859: }
10860: } else {
10861: $result = 'error: data to store was not a hash reference';
10862: }
10863: } else {
10864: $result= 'error: invalid requestkey';
10865: }
10866: return $result;
10867: }
10868:
1.21 www 10869: # ---------------------------------------------------------- Assign Custom Role
10870:
10871: sub assigncustomrole {
1.957 raeburn 10872: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10873: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10874: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10875: }
10876:
10877: # ----------------------------------------------------------------- Revoke Role
10878:
10879: sub revokerole {
1.957 raeburn 10880: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10881: my $now=time;
1.965 raeburn 10882: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10883: }
10884:
10885: # ---------------------------------------------------------- Revoke Custom Role
10886:
10887: sub revokecustomrole {
1.957 raeburn 10888: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10889: my $now=time;
1.357 www 10890: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10891: $deleteflag,$selfenroll,$context);
1.17 www 10892: }
10893:
1.533 banghart 10894: # ------------------------------------------------------------ Disk usage
1.535 albertel 10895: sub diskusage {
1.955 raeburn 10896: my ($udom,$uname,$directorypath,$getpropath)=@_;
10897: $directorypath =~ s/\/$//;
10898: my $listing=&reply('du2:'.&escape($directorypath).':'
10899: .&escape($getpropath).':'.&escape($uname).':'
10900: .&escape($udom),homeserver($uname,$udom));
10901: if ($listing eq 'unknown_cmd') {
10902: if ($getpropath) {
10903: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10904: }
10905: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10906: }
1.514 albertel 10907: return $listing;
1.512 banghart 10908: }
10909:
1.566 banghart 10910: sub is_locked {
1.1096 raeburn 10911: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10912: my @check;
10913: my $is_locked;
1.1093 raeburn 10914: push (@check,$file_name);
1.613 albertel 10915: my %locked = &get('file_permissions',\@check,
1.620 albertel 10916: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10917: my ($tmp)=keys(%locked);
10918: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10919:
1.566 banghart 10920: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10921: $is_locked = 'false';
10922: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10923: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10924: $is_locked = 'true';
1.1096 raeburn 10925: if (ref($which) eq 'ARRAY') {
10926: push(@{$which},$entry);
10927: } else {
10928: last;
10929: }
1.745 raeburn 10930: }
10931: }
1.566 banghart 10932: } else {
10933: $is_locked = 'false';
10934: }
1.1093 raeburn 10935: return $is_locked;
1.566 banghart 10936: }
10937:
1.759 albertel 10938: sub declutter_portfile {
10939: my ($file) = @_;
1.833 albertel 10940: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10941: return $file;
10942: }
10943:
1.559 banghart 10944: # ------------------------------------------------------------- Mark as Read Only
10945:
10946: sub mark_as_readonly {
10947: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10948: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10949: my ($tmp)=keys(%current_permissions);
10950: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10951: foreach my $file (@{$files}) {
1.759 albertel 10952: $file = &declutter_portfile($file);
1.561 banghart 10953: push(@{$current_permissions{$file}},$what);
1.559 banghart 10954: }
1.613 albertel 10955: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10956: return;
10957: }
10958:
1.572 banghart 10959: # ------------------------------------------------------------Save Selected Files
10960:
10961: sub save_selected_files {
10962: my ($user, $path, @files) = @_;
10963: my $filename = $user."savedfiles";
1.573 banghart 10964: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 10965: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10966: foreach my $file (@files) {
1.620 albertel 10967: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10968: }
10969: foreach my $file (@other_files) {
1.574 banghart 10970: print (OUT $file."\n");
1.572 banghart 10971: }
1.574 banghart 10972: close (OUT);
1.572 banghart 10973: return 'ok';
10974: }
10975:
1.574 banghart 10976: sub clear_selected_files {
10977: my ($user) = @_;
10978: my $filename = $user."savedfiles";
1.1359 raeburn 10979: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10980: print (OUT undef);
10981: close (OUT);
10982: return ("ok");
10983: }
10984:
1.572 banghart 10985: sub files_in_path {
10986: my ($user, $path) = @_;
10987: my $filename = $user."savedfiles";
10988: my %return_files;
1.1359 raeburn 10989: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10990: while (my $line_in = <IN>) {
1.574 banghart 10991: chomp ($line_in);
10992: my @paths_and_file = split (m!/!, $line_in);
10993: my $file_part = pop (@paths_and_file);
10994: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10995: $path_part.='/';
10996: my $path_and_file = $path_part.$file_part;
10997: if ($path_part eq $path) {
10998: $return_files{$file_part}= 'selected';
10999: }
11000: }
1.574 banghart 11001: close (IN);
11002: return (\%return_files);
1.572 banghart 11003: }
11004:
11005: # called in portfolio select mode, to show files selected NOT in current directory
11006: sub files_not_in_path {
11007: my ($user, $path) = @_;
11008: my $filename = $user."savedfiles";
11009: my @return_files;
11010: my $path_part;
1.1359 raeburn 11011: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11012: while (my $line = <IN>) {
1.572 banghart 11013: #ok, I know it's clunky, but I want it to work
1.800 albertel 11014: my @paths_and_file = split(m|/|, $line);
11015: my $file_part = pop(@paths_and_file);
11016: chomp($file_part);
11017: my $path_part = join('/', @paths_and_file);
1.572 banghart 11018: $path_part .= '/';
11019: my $path_and_file = $path_part.$file_part;
11020: if ($path_part ne $path) {
1.800 albertel 11021: push(@return_files, ($path_and_file));
1.572 banghart 11022: }
11023: }
1.800 albertel 11024: close(OUT);
1.574 banghart 11025: return (@return_files);
1.572 banghart 11026: }
11027:
1.1273 raeburn 11028: #------------------------------Submitted/Handedback Portfolio Files Versioning
11029:
11030: sub portfiles_versioning {
11031: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11032: my $portfolio_root = '/userfiles/portfolio';
11033: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11034: foreach my $file (@{$portfiles}) {
11035: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11036: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11037: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11038: my $getpropath = 1;
11039: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11040: $stu_name,$getpropath);
11041: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11042: my $new_answer =
11043: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11044: if ($new_answer ne 'problem getting file') {
11045: push(@{$versioned_portfiles}, $directory.$new_answer);
11046: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11047: [$symb,$env{'request.course.id'},'graded']);
11048: }
11049: }
11050: }
11051:
11052: sub get_next_version {
11053: my ($answer_name, $answer_ext, $dir_list) = @_;
11054: my $version;
11055: if (ref($dir_list) eq 'ARRAY') {
11056: foreach my $row (@{$dir_list}) {
11057: my ($file) = split(/\&/,$row,2);
11058: my ($file_name,$file_version,$file_ext) =
11059: &file_name_version_ext($file);
11060: if (($file_name eq $answer_name) &&
11061: ($file_ext eq $answer_ext)) {
11062: # gets here if filename and extension match,
11063: # regardless of version
11064: if ($file_version ne '') {
11065: # a versioned file is found so save it for later
11066: if ($file_version > $version) {
11067: $version = $file_version;
11068: }
11069: }
11070: }
11071: }
11072: }
11073: $version ++;
11074: return($version);
11075: }
11076:
11077: sub version_selected_portfile {
11078: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11079: my ($answer_name,$answer_ver,$answer_ext) =
11080: &file_name_version_ext($file_name);
11081: my $new_answer;
11082: $env{'form.copy'} =
11083: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11084: if($env{'form.copy'} eq '-1') {
11085: $new_answer = 'problem getting file';
11086: } else {
11087: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11088: my $copy_result =
11089: &finishuserfileupload($stu_name,$domain,'copy',
11090: '/portfolio'.$directory.$new_answer);
11091: }
11092: undef($env{'form.copy'});
11093: return ($new_answer);
11094: }
11095:
11096: sub file_name_version_ext {
11097: my ($file)=@_;
11098: my @file_parts = split(/\./, $file);
11099: my ($name,$version,$ext);
11100: if (@file_parts > 1) {
11101: $ext=pop(@file_parts);
11102: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11103: $version=pop(@file_parts);
11104: }
11105: $name=join('.',@file_parts);
11106: } else {
11107: $name=join('.',@file_parts);
11108: }
11109: return($name,$version,$ext);
11110: }
11111:
1.745 raeburn 11112: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11113:
1.745 raeburn 11114: sub get_portfile_permissions {
11115: my ($domain,$user) = @_;
1.613 albertel 11116: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11117: my ($tmp)=keys(%current_permissions);
11118: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11119: return \%current_permissions;
11120: }
11121:
11122: #---------------------------------------------Get portfolio file access controls
11123:
1.749 raeburn 11124: sub get_access_controls {
1.745 raeburn 11125: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11126: my %access;
11127: my $real_file = $file;
11128: $file =~ s/\.meta$//;
1.745 raeburn 11129: if (defined($file)) {
1.749 raeburn 11130: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11131: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11132: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11133: }
11134: }
1.745 raeburn 11135: } else {
1.749 raeburn 11136: foreach my $key (keys(%{$current_permissions})) {
11137: if ($key =~ /\0accesscontrol$/) {
11138: if (defined($group)) {
11139: if ($key !~ m-^\Q$group\E/-) {
11140: next;
11141: }
11142: }
11143: my ($fullpath) = split(/\0/,$key);
11144: if (ref($$current_permissions{$key}) eq 'HASH') {
11145: foreach my $control (keys(%{$$current_permissions{$key}})) {
11146: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11147: }
11148: }
11149: }
11150: }
11151: }
11152: return %access;
11153: }
11154:
11155: sub modify_access_controls {
11156: my ($file_name,$changes,$domain,$user)=@_;
11157: my ($outcome,$deloutcome);
11158: my %store_permissions;
11159: my %new_values;
11160: my %new_control;
11161: my %translation;
11162: my @deletions = ();
11163: my $now = time;
11164: if (exists($$changes{'activate'})) {
11165: if (ref($$changes{'activate'}) eq 'HASH') {
11166: my @newitems = sort(keys(%{$$changes{'activate'}}));
11167: my $numnew = scalar(@newitems);
11168: for (my $i=0; $i<$numnew; $i++) {
11169: my $newkey = $newitems[$i];
11170: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11171: if ($newkey =~ /^\d+:/) {
11172: $newkey =~ s/^(\d+)/$newid/;
11173: $translation{$1} = $newid;
11174: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11175: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11176: $translation{$1} = $newid;
11177: }
1.749 raeburn 11178: $new_values{$file_name."\0".$newkey} =
11179: $$changes{'activate'}{$newitems[$i]};
11180: $new_control{$newkey} = $now;
11181: }
11182: }
11183: }
11184: my %todelete;
11185: my %changed_items;
11186: foreach my $action ('delete','update') {
11187: if (exists($$changes{$action})) {
11188: if (ref($$changes{$action}) eq 'HASH') {
11189: foreach my $key (keys(%{$$changes{$action}})) {
11190: my ($itemnum) = ($key =~ /^([^:]+):/);
11191: if ($action eq 'delete') {
11192: $todelete{$itemnum} = 1;
11193: } else {
11194: $changed_items{$itemnum} = $key;
11195: }
11196: }
1.745 raeburn 11197: }
11198: }
1.749 raeburn 11199: }
11200: # get lock on access controls for file.
11201: my $lockhash = {
11202: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11203: ':'.$env{'user.domain'},
11204: };
11205: my $tries = 0;
11206: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11207:
1.1288 damieng 11208: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11209: $tries ++;
1.1289 damieng 11210: sleep(0.1);
1.749 raeburn 11211: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11212: }
11213: if ($gotlock eq 'ok') {
11214: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11215: my ($tmp)=keys(%curr_permissions);
11216: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11217: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11218: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11219: if (ref($curr_controls) eq 'HASH') {
11220: foreach my $control_item (keys(%{$curr_controls})) {
11221: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11222: if (defined($todelete{$itemnum})) {
11223: push(@deletions,$file_name."\0".$control_item);
11224: } else {
11225: if (defined($changed_items{$itemnum})) {
11226: $new_control{$changed_items{$itemnum}} = $now;
11227: push(@deletions,$file_name."\0".$control_item);
11228: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11229: } else {
11230: $new_control{$control_item} = $$curr_controls{$control_item};
11231: }
11232: }
1.745 raeburn 11233: }
11234: }
11235: }
1.970 raeburn 11236: my ($group);
11237: if (&is_course($domain,$user)) {
11238: ($group,my $file) = split(/\//,$file_name,2);
11239: }
1.749 raeburn 11240: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11241: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11242: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11243: # remove lock
11244: my @del_lock = ($file_name."\0".'locked_access_records');
11245: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11246: my $sqlresult =
1.970 raeburn 11247: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11248: $group);
1.749 raeburn 11249: } else {
11250: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11251: }
1.749 raeburn 11252: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11253: }
11254:
1.827 raeburn 11255: sub make_public_indefinitely {
1.1271 raeburn 11256: my (@requrl) = @_;
11257: return &automated_portfile_access('public',\@requrl);
11258: }
11259:
11260: sub automated_portfile_access {
11261: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11262: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11263: return 'invalid';
11264: }
1.1271 raeburn 11265: my %urls;
11266: if (ref($addsref) eq 'ARRAY') {
11267: foreach my $requrl (@{$addsref}) {
11268: if (&is_portfolio_url($requrl)) {
11269: unless (exists($urls{$requrl})) {
11270: $urls{$requrl} = 'add';
11271: }
11272: }
11273: }
11274: }
11275: if (ref($delsref) eq 'ARRAY') {
11276: foreach my $requrl (@{$delsref}) {
11277: if (&is_portfolio_url($requrl)) {
11278: unless (exists($urls{$requrl})) {
11279: $urls{$requrl} = 'delete';
11280: }
11281: }
11282: }
11283: }
11284: unless (keys(%urls)) {
11285: return 'invalid';
11286: }
11287: my $ip;
11288: if ($accesstype eq 'ip') {
11289: if (ref($info) eq 'HASH') {
11290: if ($info->{'ip'} ne '') {
11291: $ip = $info->{'ip'};
11292: }
11293: }
11294: if ($ip eq '') {
11295: return 'invalid';
11296: }
11297: }
11298: my $errors;
1.827 raeburn 11299: my $now = time;
1.1271 raeburn 11300: my %current_perms;
11301: foreach my $requrl (sort(keys(%urls))) {
11302: my $action;
11303: if ($urls{$requrl} eq 'add') {
11304: $action = 'activate';
11305: } else {
11306: $action = 'none';
11307: }
11308: my $aclnum = 0;
1.827 raeburn 11309: my (undef,$udom,$unum,$file_name,$group) =
11310: &parse_portfolio_url($requrl);
1.1271 raeburn 11311: unless (exists($current_perms{$unum.':'.$udom})) {
11312: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11313: }
11314: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11315: $group,$file_name);
11316: foreach my $key (keys(%{$access_controls{$file_name}})) {
11317: my ($num,$scope,$end,$start) =
11318: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11319: if ($scope eq $accesstype) {
11320: if (($start <= $now) && ($end == 0)) {
11321: if ($accesstype eq 'ip') {
11322: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11323: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11324: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11325: if ($urls{$requrl} eq 'add') {
11326: $action = 'none';
11327: last;
11328: } else {
11329: $action = 'delete';
11330: $aclnum = $num;
11331: last;
11332: }
11333: }
11334: }
11335: }
11336: } elsif ($accesstype eq 'public') {
11337: if ($urls{$requrl} eq 'add') {
11338: $action = 'none';
11339: last;
11340: } else {
11341: $action = 'delete';
11342: $aclnum = $num;
11343: last;
11344: }
11345: }
11346: } elsif ($accesstype eq 'public') {
1.827 raeburn 11347: $action = 'update';
11348: $aclnum = $num;
1.1271 raeburn 11349: last;
1.827 raeburn 11350: }
11351: }
11352: }
11353: if ($action eq 'none') {
1.1271 raeburn 11354: next;
1.827 raeburn 11355: } else {
11356: my %changes;
11357: my $newend = 0;
11358: my $newstart = $now;
1.1271 raeburn 11359: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11360: $changes{$action}{$newkey} = {
1.1271 raeburn 11361: type => $accesstype,
1.827 raeburn 11362: time => {
11363: start => $newstart,
11364: end => $newend,
11365: },
11366: };
1.1271 raeburn 11367: if ($accesstype eq 'ip') {
11368: $changes{$action}{$newkey}{'ip'} = [$ip];
11369: }
1.827 raeburn 11370: my ($outcome,$deloutcome,$new_values,$translation) =
11371: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11372: unless ($outcome eq 'ok') {
11373: $errors .= $outcome.' ';
11374: }
1.827 raeburn 11375: }
1.1271 raeburn 11376: }
11377: if ($errors) {
11378: $errors =~ s/\s$//;
11379: return $errors;
1.827 raeburn 11380: } else {
1.1271 raeburn 11381: return 'ok';
1.827 raeburn 11382: }
11383: }
11384:
1.745 raeburn 11385: #------------------------------------------------------Get Marked as Read Only
11386:
11387: sub get_marked_as_readonly {
11388: my ($domain,$user,$what,$group) = @_;
11389: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11390: my @readonly_files;
1.629 banghart 11391: my $cmp1=$what;
11392: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11393: while (my ($file_name,$value) = each(%{$current_permissions})) {
11394: if (defined($group)) {
11395: if ($file_name !~ m-^\Q$group\E/-) {
11396: next;
11397: }
11398: }
1.561 banghart 11399: if (ref($value) eq "ARRAY"){
11400: foreach my $stored_what (@{$value}) {
1.629 banghart 11401: my $cmp2=$stored_what;
1.759 albertel 11402: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11403: $cmp2=join('',@{$stored_what});
1.745 raeburn 11404: }
1.629 banghart 11405: if ($cmp1 eq $cmp2) {
1.561 banghart 11406: push(@readonly_files, $file_name);
1.745 raeburn 11407: last;
1.563 banghart 11408: } elsif (!defined($what)) {
11409: push(@readonly_files, $file_name);
1.745 raeburn 11410: last;
1.561 banghart 11411: }
11412: }
1.745 raeburn 11413: }
1.561 banghart 11414: }
11415: return @readonly_files;
11416: }
1.577 banghart 11417: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11418:
1.577 banghart 11419: sub get_marked_as_readonly_hash {
1.745 raeburn 11420: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11421: my %readonly_files;
1.745 raeburn 11422: while (my ($file_name,$value) = each(%{$current_permissions})) {
11423: if (defined($group)) {
11424: if ($file_name !~ m-^\Q$group\E/-) {
11425: next;
11426: }
11427: }
1.577 banghart 11428: if (ref($value) eq "ARRAY"){
11429: foreach my $stored_what (@{$value}) {
1.745 raeburn 11430: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11431: foreach my $lock_descriptor(@{$stored_what}) {
11432: if ($lock_descriptor eq 'graded') {
11433: $readonly_files{$file_name} = 'graded';
11434: } elsif ($lock_descriptor eq 'handback') {
11435: $readonly_files{$file_name} = 'handback';
11436: } else {
11437: if (!exists($readonly_files{$file_name})) {
11438: $readonly_files{$file_name} = 'locked';
11439: }
11440: }
1.745 raeburn 11441: }
1.750 banghart 11442: }
1.577 banghart 11443: }
11444: }
11445: }
11446: return %readonly_files;
11447: }
1.559 banghart 11448: # ------------------------------------------------------------ Unmark as Read Only
11449:
11450: sub unmark_as_readonly {
1.629 banghart 11451: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11452: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11453: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11454: $file_name = &declutter_portfile($file_name);
1.634 albertel 11455: my $symb_crs = $what;
11456: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11457: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11458: my ($tmp)=keys(%current_permissions);
11459: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11460: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11461: foreach my $file (@readonly_files) {
1.759 albertel 11462: my $clean_file = &declutter_portfile($file);
11463: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11464: my $current_locks = $current_permissions{$file};
1.563 banghart 11465: my @new_locks;
11466: my @del_keys;
11467: if (ref($current_locks) eq "ARRAY"){
11468: foreach my $locker (@{$current_locks}) {
1.632 albertel 11469: my $compare=$locker;
1.749 raeburn 11470: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11471: $compare=join('',@{$locker});
1.746 raeburn 11472: if ($compare ne $symb_crs) {
11473: push(@new_locks, $locker);
11474: }
1.563 banghart 11475: }
11476: }
1.650 albertel 11477: if (scalar(@new_locks) > 0) {
1.563 banghart 11478: $current_permissions{$file} = \@new_locks;
11479: } else {
11480: push(@del_keys, $file);
1.613 albertel 11481: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11482: delete($current_permissions{$file});
1.563 banghart 11483: }
11484: }
1.561 banghart 11485: }
1.613 albertel 11486: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11487: return;
11488: }
1.512 banghart 11489:
1.17 www 11490: # ------------------------------------------------------------ Directory lister
11491:
11492: sub dirlist {
1.955 raeburn 11493: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11494: $uri=~s/^\///;
11495: $uri=~s/\/$//;
1.253 stredwic 11496: my ($udom, $uname);
1.955 raeburn 11497: if ($getuserdir) {
1.253 stredwic 11498: $udom = $userdomain;
11499: $uname = $username;
1.955 raeburn 11500: } else {
11501: (undef,$udom,$uname)=split(/\//,$uri);
11502: if(defined($userdomain)) {
11503: $udom = $userdomain;
11504: }
11505: if(defined($username)) {
11506: $uname = $username;
11507: }
1.253 stredwic 11508: }
1.955 raeburn 11509: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11510:
1.955 raeburn 11511: $dirRoot = $perlvar{'lonDocRoot'};
11512: if (defined($getpropath)) {
11513: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11514: $dirRoot =~ s/\/$//;
1.955 raeburn 11515: } elsif (defined($getuserdir)) {
11516: my $subdir=$uname.'__';
11517: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11518: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11519: ."/$udom/$subdir/$uname";
11520: } elsif (defined($alternateRoot)) {
11521: $dirRoot = $alternateRoot;
1.751 banghart 11522: }
1.253 stredwic 11523:
11524: if($udom) {
11525: if($uname) {
1.1135 raeburn 11526: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11527: if ($uhome eq 'no_host') {
11528: return ([],'no_host');
11529: }
1.955 raeburn 11530: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11531: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11532: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11533: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11534: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11535: } else {
11536: @listing_results = map { &unescape($_); } split(/:/,$listing);
11537: }
1.605 matthew 11538: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11539: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11540: @listing_results = split(/:/,$listing);
11541: } else {
11542: @listing_results = map { &unescape($_); } split(/:/,$listing);
11543: }
1.1135 raeburn 11544: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11545: ($listing eq 'rejected') || ($listing eq 'refused') ||
11546: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11547: return ([],$listing);
11548: } else {
11549: return (\@listing_results);
1.1135 raeburn 11550: }
1.955 raeburn 11551: } elsif(!$alternateRoot) {
1.1136 raeburn 11552: my (%allusers,%listerror);
1.841 albertel 11553: my %servers = &get_servers($udom,'library');
1.955 raeburn 11554: foreach my $tryserver (keys(%servers)) {
11555: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11556: &escape($udom),$tryserver);
11557: if ($listing eq 'unknown_cmd') {
11558: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11559: $udom, $tryserver);
11560: } else {
11561: @listing_results = map { &unescape($_); } split(/:/,$listing);
11562: }
1.841 albertel 11563: if ($listing eq 'unknown_cmd') {
11564: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11565: $udom, $tryserver);
11566: @listing_results = split(/:/,$listing);
11567: } else {
11568: @listing_results =
11569: map { &unescape($_); } split(/:/,$listing);
11570: }
1.1136 raeburn 11571: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11572: ($listing eq 'rejected') || ($listing eq 'refused') ||
11573: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11574: $listerror{$tryserver} = $listing;
11575: } else {
1.841 albertel 11576: foreach my $line (@listing_results) {
11577: my ($entry) = split(/&/,$line,2);
11578: $allusers{$entry} = 1;
11579: }
11580: }
1.253 stredwic 11581: }
1.1136 raeburn 11582: my @alluserslist=();
1.800 albertel 11583: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11584: push(@alluserslist,$user.'&user');
1.253 stredwic 11585: }
1.1318 droeschl 11586:
11587: if (!%listerror) {
11588: # no errors
11589: return (\@alluserslist);
11590: } elsif (scalar(keys(%servers)) == 1) {
11591: # one library server, one error
11592: my ($key) = keys(%listerror);
11593: return (\@alluserslist, $listerror{$key});
11594: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11595: # con_lost indicates that we might miss data from at least one
11596: # library server
11597: return (\@alluserslist, 'con_lost');
11598: } else {
11599: # multiple library servers and no con_lost -> data should be
11600: # complete.
11601: return (\@alluserslist);
11602: }
11603:
1.253 stredwic 11604: } else {
1.1136 raeburn 11605: return ([],'missing username');
1.253 stredwic 11606: }
1.955 raeburn 11607: } elsif(!defined($getpropath)) {
1.1136 raeburn 11608: my $path = $perlvar{'lonDocRoot'}.'/res/';
11609: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11610: return (\@all_domains);
1.955 raeburn 11611: } else {
1.1136 raeburn 11612: return ([],'missing domain');
1.275 stredwic 11613: }
11614: }
11615:
11616: # --------------------------------------------- GetFileTimestamp
11617: # This function utilizes dirlist and returns the date stamp for
11618: # when it was last modified. It will also return an error of -1
11619: # if an error occurs
11620:
11621: sub GetFileTimestamp {
1.955 raeburn 11622: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11623: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11624: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11625: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11626: undef,$getuserdir);
11627: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11628: return -1;
11629: }
11630: if (ref($fileref) eq 'ARRAY') {
11631: my @stats = split('&',$fileref->[0]);
1.375 matthew 11632: # @stats contains first the filename, then the stat output
11633: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11634: } else {
11635: return -1;
1.253 stredwic 11636: }
1.26 www 11637: }
11638:
1.712 albertel 11639: sub stat_file {
11640: my ($uri) = @_;
1.787 albertel 11641: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11642:
1.955 raeburn 11643: my ($udom,$uname,$file);
1.712 albertel 11644: if ($uri =~ m-^/(uploaded|editupload)/-) {
11645: ($udom,$uname,$file) =
1.811 albertel 11646: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11647: $file = 'userfiles/'.$file;
11648: }
11649: if ($uri =~ m-^/res/-) {
11650: ($udom,$uname) =
1.807 albertel 11651: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11652: $file = $uri;
11653: }
11654:
11655: if (!$udom || !$uname || !$file) {
11656: # unable to handle the uri
11657: return ();
11658: }
1.956 raeburn 11659: my $getpropath;
11660: if ($file =~ /^userfiles\//) {
11661: $getpropath = 1;
11662: }
1.1136 raeburn 11663: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11664: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11665: return ();
11666: } else {
11667: if (ref($listref) eq 'ARRAY') {
11668: my @stats = split('&',$listref->[0]);
11669: shift(@stats); #filename is first
11670: return @stats;
11671: }
1.712 albertel 11672: }
11673: return ();
11674: }
11675:
1.1313 raeburn 11676: # --------------------------------------------------------- recursedirs
11677: # Recursive function to traverse either a specific user's Authoring Space
11678: # or corresponding Published Resource Space, and populate the hash ref:
11679: # $dirhashref with URLs of all directories, and if $filehashref hash
11680: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11681: # or .rights files in resource space, and .meta, .save, .log, and .bak
11682: # files in Authoring Space.
11683: #
11684: # Inputs:
11685: #
11686: # $is_home - true if current server is home server for user's space
11687: # $context - either: priv, or res respectively for Authoring or Resource Space.
11688: # $docroot - Document root (i.e., /home/httpd/html
11689: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11690: # $relpath - Current path (relative to top level).
11691: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11692: # $filehashref - reference to hash to populate with URLs of files (Optional)
11693: #
11694: # Returns: nothing
11695: #
11696: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11697: #
11698: # Currently used by interface/londocs.pm to create linked select boxes for
11699: # directory and filename to import a Course "Author" resource into a course, and
11700: # also to create linked select boxes for Authoring Space and Directory to choose
11701: # save location for creation of a new "standard" problem from the Course Editor.
11702: #
11703:
11704: sub recursedirs {
11705: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11706: return unless (ref($dirhashref) eq 'HASH');
11707: my $currpath = $docroot.$toppath;
11708: if ($relpath) {
11709: $currpath .= "/$relpath";
11710: }
11711: my $savefile;
11712: if (ref($filehashref)) {
11713: $savefile = 1;
11714: }
11715: if ($is_home) {
11716: if (opendir(my $dirh,$currpath)) {
11717: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11718: next if ($item eq '');
11719: if (-d "$currpath/$item") {
11720: my $newpath;
11721: if ($relpath) {
11722: $newpath = "$relpath/$item";
11723: } else {
11724: $newpath = $item;
11725: }
11726: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11727: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11728: } elsif ($savefile) {
11729: if ($context eq 'priv') {
11730: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11731: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11732: }
11733: } else {
11734: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11735: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11736: }
11737: }
11738: }
11739: }
11740: closedir($dirh);
11741: }
11742: } else {
11743: my ($dirlistref,$listerror) =
11744: &dirlist($toppath.$relpath);
11745: my @dir_lines;
11746: my $dirptr=16384;
11747: if (ref($dirlistref) eq 'ARRAY') {
11748: foreach my $dir_line (sort
11749: {
11750: my ($afile)=split('&',$a,2);
11751: my ($bfile)=split('&',$b,2);
11752: return (lc($afile) cmp lc($bfile));
11753: } (@{$dirlistref})) {
11754: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11755: split(/\&/,$dir_line,16);
11756: $item =~ s/\s+$//;
11757: next if (($item =~ /^\.\.?$/) || ($obs));
11758: if ($dirptr&$testdir) {
11759: my $newpath;
11760: if ($relpath) {
11761: $newpath = "$relpath/$item";
11762: } else {
11763: $relpath = '/';
11764: $newpath = $item;
11765: }
11766: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11767: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11768: } elsif ($savefile) {
11769: if ($context eq 'priv') {
11770: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11771: $filehashref->{$relpath}{$item} = 1;
11772: }
11773: } else {
11774: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11775: $filehashref->{$relpath}{$item} = 1;
11776: }
11777: }
11778: }
11779: }
11780: }
11781: }
11782: return;
11783: }
11784:
1.26 www 11785: # -------------------------------------------------------- Value of a Condition
11786:
1.713 albertel 11787: # gets the value of a specific preevaluated condition
11788: # stored in the string $env{user.state.<cid>}
11789: # or looks up a condition reference in the bighash and if if hasn't
11790: # already been evaluated recurses into docondval to get the value of
11791: # the condition, then memoizing it to
11792: # $env{user.state.<cid>.<condition>}
1.40 www 11793: sub directcondval {
11794: my $number=shift;
1.620 albertel 11795: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11796: &Apache::lonuserstate::evalstate();
11797: }
1.713 albertel 11798: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11799: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11800: } elsif ($number =~ /^_/) {
11801: my $sub_condition;
11802: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11803: &GDBM_READER(),0640)) {
11804: $sub_condition=$bighash{'conditions'.$number};
11805: untie(%bighash);
11806: }
11807: my $value = &docondval($sub_condition);
1.949 raeburn 11808: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11809: return $value;
11810: }
1.620 albertel 11811: if ($env{'user.state.'.$env{'request.course.id'}}) {
11812: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11813: } else {
11814: return 2;
11815: }
11816: }
11817:
1.713 albertel 11818: # get the collection of conditions for this resource
1.26 www 11819: sub condval {
11820: my $condidx=shift;
1.54 www 11821: my $allpathcond='';
1.713 albertel 11822: foreach my $cond (split(/\|/,$condidx)) {
11823: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11824: $allpathcond.=
11825: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11826: }
1.191 harris41 11827: }
1.54 www 11828: $allpathcond=~s/\|$//;
1.713 albertel 11829: return &docondval($allpathcond);
11830: }
11831:
11832: #evaluates an expression of conditions
11833: sub docondval {
11834: my ($allpathcond) = @_;
11835: my $result=0;
11836: if ($env{'request.course.id'}
11837: && defined($allpathcond)) {
11838: my $operand='|';
11839: my @stack;
11840: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11841: if ($chunk eq '(') {
11842: push @stack,($operand,$result);
11843: } elsif ($chunk eq ')') {
11844: my $before=pop @stack;
11845: if (pop @stack eq '&') {
11846: $result=$result>$before?$before:$result;
11847: } else {
11848: $result=$result>$before?$result:$before;
11849: }
11850: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11851: $operand=$chunk;
11852: } else {
11853: my $new=directcondval($chunk);
11854: if ($operand eq '&') {
11855: $result=$result>$new?$new:$result;
11856: } else {
11857: $result=$result>$new?$result:$new;
11858: }
11859: }
11860: }
1.26 www 11861: }
11862: return $result;
1.421 albertel 11863: }
11864:
11865: # ---------------------------------------------------- Devalidate courseresdata
11866:
11867: sub devalidatecourseresdata {
11868: my ($coursenum,$coursedomain)=@_;
11869: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11870: &devalidate_cache_new('courseres',$hashid);
1.28 www 11871: }
11872:
1.763 www 11873:
1.200 www 11874: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11875: #
11876: # Parameters:
11877: # $coursenum - Number of the course.
11878: # $coursedomain - Domain at which the course was created.
11879: # Returns:
11880: # A hash of the course parameters along (I think) with timestamps
11881: # and version info.
1.877 foxr 11882:
1.624 albertel 11883: sub get_courseresdata {
11884: my ($coursenum,$coursedomain)=@_;
1.200 www 11885: my $coursehom=&homeserver($coursenum,$coursedomain);
11886: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11887: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11888: my %dumpreply;
1.417 albertel 11889: unless (defined($cached)) {
1.624 albertel 11890: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11891: $result=\%dumpreply;
1.251 albertel 11892: my ($tmp) = keys(%dumpreply);
11893: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11894: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11895: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11896: return $tmp;
1.416 albertel 11897: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11898: $result=undef;
1.599 albertel 11899: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11900: }
11901: }
1.624 albertel 11902: return $result;
11903: }
11904:
1.633 albertel 11905: sub devalidateuserresdata {
11906: my ($uname,$udom)=@_;
11907: my $hashid="$udom:$uname";
11908: &devalidate_cache_new('userres',$hashid);
11909: }
11910:
1.624 albertel 11911: sub get_userresdata {
11912: my ($uname,$udom)=@_;
11913: #most student don\'t have any data set, check if there is some data
11914: if (&EXT_cache_status($udom,$uname)) { return undef; }
11915:
11916: my $hashid="$udom:$uname";
11917: my ($result,$cached)=&is_cached_new('userres',$hashid);
11918: if (!defined($cached)) {
11919: my %resourcedata=&dump('resourcedata',$udom,$uname);
11920: $result=\%resourcedata;
11921: &do_cache_new('userres',$hashid,$result,600);
11922: }
11923: my ($tmp)=keys(%$result);
11924: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11925: return $result;
11926: }
11927: #error 2 occurs when the .db doesn't exist
11928: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11929: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11930: &logthis("<font color=\"blue\">WARNING:".
11931: " Trying to get resource data for ".
11932: $uname." at ".$udom.": ".
11933: $tmp."</font>");
11934: }
1.624 albertel 11935: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11936: #&EXT_cache_set($udom,$uname);
11937: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11938: undef($tmp); # not really an error so don't send it back
1.624 albertel 11939: }
11940: return $tmp;
11941: }
1.879 foxr 11942: #----------------------------------------------- resdata - return resource data
11943: # Purpose:
11944: # Return resource data for either users or for a course.
11945: # Parameters:
11946: # $name - Course/user name.
11947: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11948: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11949: # $mapp - decluttered URL of enclosing map
11950: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11951: # $recurseup - Ref to array of map URLs, starting with map containing
11952: # $mapp up through hierarchy of nested maps to top level map.
11953: # $courseid - CourseID (first part of param identifier).
11954: # $modifier - Middle part of param identifier.
11955: # $what - Last part of param identifier.
1.879 foxr 11956: # @which - Array of names of resources desired.
11957: # Returns:
11958: # The value of the first reasource in @which that is found in the
11959: # resource hash.
11960: # Exceptional Conditions:
11961: # If the $type passed in is not valid (not the string 'course' or
11962: # 'user', an undefined reference is returned.
11963: # If none of the resources are found, an undef is returned
1.624 albertel 11964: sub resdata {
1.1301 raeburn 11965: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11966: $modifier,$what,@which)=@_;
1.624 albertel 11967: my $result;
11968: if ($type eq 'course') {
11969: $result=&get_courseresdata($name,$domain);
11970: } elsif ($type eq 'user') {
11971: $result=&get_userresdata($name,$domain);
11972: }
11973: if (!ref($result)) { return $result; }
1.251 albertel 11974: foreach my $item (@which) {
1.1301 raeburn 11975: if ($item->[1] eq 'course') {
11976: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11977: unless ($$recursed) {
1.1302 raeburn 11978: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11979: $$recursed = 1;
11980: }
11981: foreach my $item (@${recurseup}) {
11982: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11983: last if (defined($result->{$norecursechk}));
11984: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11985: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11986: }
11987: }
11988: }
11989: if (defined($result->{$item->[0]})) {
1.927 albertel 11990: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11991: }
1.250 albertel 11992: }
1.291 albertel 11993: return undef;
1.200 www 11994: }
11995:
1.1360 raeburn 11996: sub get_domain_lti {
11997: my ($cdom,$context) = @_;
11998: my ($name,%lti);
11999: if ($context eq 'consumer') {
12000: $name = 'ltitools';
12001: } elsif ($context eq 'provider') {
12002: $name = 'lti';
12003: } else {
12004: return %lti;
12005: }
12006: my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298 raeburn 12007: if (defined($cached)) {
12008: if (ref($result) eq 'HASH') {
1.1360 raeburn 12009: %lti = %{$result};
1.1298 raeburn 12010: }
12011: } else {
1.1360 raeburn 12012: my %domconfig = &get_dom('configuration',[$name],$cdom);
12013: if (ref($domconfig{$name}) eq 'HASH') {
12014: %lti = %{$domconfig{$name}};
12015: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12016: if (ref($encdomconfig{$name}) eq 'HASH') {
12017: foreach my $id (keys(%lti)) {
12018: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344 raeburn 12019: foreach my $item ('key','secret') {
1.1360 raeburn 12020: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344 raeburn 12021: }
12022: }
12023: }
12024: }
1.1298 raeburn 12025: }
12026: my $cachetime = 24*60*60;
1.1360 raeburn 12027: &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298 raeburn 12028: }
1.1360 raeburn 12029: return %lti;
1.1298 raeburn 12030: }
12031:
1.1236 raeburn 12032: sub get_numsuppfiles {
12033: my ($cnum,$cdom,$ignorecache)=@_;
12034: my $hashid=$cnum.':'.$cdom;
12035: my ($suppcount,$cached);
12036: unless ($ignorecache) {
12037: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12038: }
12039: unless (defined($cached)) {
12040: my $chome=&homeserver($cnum,$cdom);
12041: unless ($chome eq 'no_host') {
1.1366 raeburn 12042: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 12043: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 12044: ($suppcount,$supptools,$errors) =
12045: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12046: $supptools,$errors);
1.1236 raeburn 12047: }
12048: &do_cache_new('suppcount',$hashid,$suppcount,600);
12049: }
12050: return $suppcount;
12051: }
12052:
1.379 matthew 12053: #
12054: # EXT resource caching routines
12055: #
12056:
1.1302 raeburn 12057: {
12058: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12059: #
12060: # The course for which we cache
12061: my $cachedmapkey='';
12062: # The cached recursive maps for this course
12063: my %cachedmaps=();
12064: # When this was last done
12065: my $cachedmaptime='';
12066:
1.379 matthew 12067: sub clear_EXT_cache_status {
1.383 albertel 12068: &delenv('cache.EXT.');
1.379 matthew 12069: }
12070:
12071: sub EXT_cache_status {
12072: my ($target_domain,$target_user) = @_;
1.383 albertel 12073: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12074: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12075: # We know already the user has no data
12076: return 1;
12077: } else {
12078: return 0;
12079: }
12080: }
12081:
12082: sub EXT_cache_set {
12083: my ($target_domain,$target_user) = @_;
1.383 albertel 12084: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12085: #&appenv({$cachename => time});
1.379 matthew 12086: }
12087:
1.28 www 12088: # --------------------------------------------------------- Value of a Variable
1.58 www 12089: sub EXT {
1.715 albertel 12090:
1.1228 raeburn 12091: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 12092: unless ($varname) { return ''; }
1.218 albertel 12093: #get real user name/domain, courseid and symb
12094: my $courseid;
1.359 albertel 12095: my $publicuser;
1.427 www 12096: if ($symbparm) {
12097: $symbparm=&get_symb_from_alias($symbparm);
12098: }
1.218 albertel 12099: if (!($uname && $udom)) {
1.790 albertel 12100: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12101: if (!$symbparm) { $symbparm=$cursymb; }
12102: } else {
1.620 albertel 12103: $courseid=$env{'request.course.id'};
1.218 albertel 12104: }
1.48 www 12105: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12106: my $rest;
1.320 albertel 12107: if (defined($therest[0])) {
1.48 www 12108: $rest=join('.',@therest);
12109: } else {
12110: $rest='';
12111: }
1.320 albertel 12112:
1.57 www 12113: my $qualifierrest=$qualifier;
12114: if ($rest) { $qualifierrest.='.'.$rest; }
12115: my $spacequalifierrest=$space;
12116: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12117: if ($realm eq 'user') {
1.48 www 12118: # --------------------------------------------------------------- user.resource
12119: if ($space eq 'resource') {
1.651 albertel 12120: if ( (defined($Apache::lonhomework::parsing_a_problem)
12121: || defined($Apache::lonhomework::parsing_a_task))
12122: &&
1.744 albertel 12123: ($symbparm eq &symbread()) ) {
12124: # if we are in the middle of processing the resource the
12125: # get the value we are planning on committing
12126: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12127: return $Apache::lonhomework::results{$qualifierrest};
12128: } else {
12129: return $Apache::lonhomework::history{$qualifierrest};
12130: }
1.335 albertel 12131: } else {
1.359 albertel 12132: my %restored;
1.620 albertel 12133: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12134: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12135: } else {
12136: %restored=&restore($symbparm,$courseid,$udom,$uname);
12137: }
1.335 albertel 12138: return $restored{$qualifierrest};
12139: }
1.48 www 12140: # ----------------------------------------------------------------- user.access
12141: } elsif ($space eq 'access') {
1.218 albertel 12142: # FIXME - not supporting calls for a specific user
1.48 www 12143: return &allowed($qualifier,$rest);
12144: # ------------------------------------------ user.preferences, user.environment
12145: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12146: if (($uname eq $env{'user.name'}) &&
12147: ($udom eq $env{'user.domain'})) {
12148: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12149: } else {
1.359 albertel 12150: my %returnhash;
12151: if (!$publicuser) {
12152: %returnhash=&userenvironment($udom,$uname,
12153: $qualifierrest);
12154: }
1.218 albertel 12155: return $returnhash{$qualifierrest};
12156: }
1.48 www 12157: # ----------------------------------------------------------------- user.course
12158: } elsif ($space eq 'course') {
1.218 albertel 12159: # FIXME - not supporting calls for a specific user
1.620 albertel 12160: return $env{join('.',('request.course',$qualifier))};
1.48 www 12161: # ------------------------------------------------------------------- user.role
12162: } elsif ($space eq 'role') {
1.218 albertel 12163: # FIXME - not supporting calls for a specific user
1.620 albertel 12164: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12165: if ($qualifier eq 'value') {
12166: return $role;
12167: } elsif ($qualifier eq 'extent') {
12168: return $where;
12169: }
12170: # ----------------------------------------------------------------- user.domain
12171: } elsif ($space eq 'domain') {
1.218 albertel 12172: return $udom;
1.48 www 12173: # ------------------------------------------------------------------- user.name
12174: } elsif ($space eq 'name') {
1.218 albertel 12175: return $uname;
1.48 www 12176: # ---------------------------------------------------- Any other user namespace
1.29 www 12177: } else {
1.359 albertel 12178: my %reply;
12179: if (!$publicuser) {
12180: %reply=&get($space,[$qualifierrest],$udom,$uname);
12181: }
12182: return $reply{$qualifierrest};
1.48 www 12183: }
1.236 www 12184: } elsif ($realm eq 'query') {
12185: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12186: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12187: [$spacequalifierrest]);
1.620 albertel 12188: return $env{'form.'.$spacequalifierrest};
1.236 www 12189: } elsif ($realm eq 'request') {
1.48 www 12190: # ------------------------------------------------------------- request.browser
12191: if ($space eq 'browser') {
1.1145 bisitz 12192: return $env{'browser.'.$qualifier};
1.57 www 12193: # ------------------------------------------------------------ request.filename
12194: } else {
1.620 albertel 12195: return $env{'request.'.$spacequalifierrest};
1.29 www 12196: }
1.28 www 12197: } elsif ($realm eq 'course') {
1.48 www 12198: # ---------------------------------------------------------- course.description
1.620 albertel 12199: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12200: } elsif ($realm eq 'resource') {
1.165 www 12201:
1.620 albertel 12202: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12203: if (!$symbparm) { $symbparm=&symbread(); }
12204: }
1.693 albertel 12205:
1.1232 raeburn 12206: if ($qualifier eq '') {
12207: if ($space eq 'title') {
12208: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12209: return &gettitle($symbparm);
12210: }
1.693 albertel 12211:
1.1232 raeburn 12212: if ($space eq 'map') {
12213: my ($map) = &decode_symb($symbparm);
12214: return &symbread($map);
12215: }
12216: if ($space eq 'maptitle') {
12217: my ($map) = &decode_symb($symbparm);
12218: return &gettitle($map);
12219: }
12220: if ($space eq 'filename') {
12221: if ($symbparm) {
12222: return &clutter((&decode_symb($symbparm))[2]);
12223: }
12224: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12225: }
1.1232 raeburn 12226:
1.1233 raeburn 12227: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12228: if ($space eq 'visibleparts') {
12229: my $navmap = Apache::lonnavmaps::navmap->new();
12230: my $item;
12231: if (ref($navmap)) {
12232: my $res = $navmap->getBySymb($symbparm);
12233: my $parts = $res->parts();
12234: if (ref($parts) eq 'ARRAY') {
12235: $item = join(',',@{$parts});
12236: }
12237: undef($navmap);
1.1232 raeburn 12238: }
1.1233 raeburn 12239: return $item;
1.1232 raeburn 12240: }
12241: }
12242: }
1.693 albertel 12243:
1.1301 raeburn 12244: my ($section, $group, @groups, @recurseup, $recursed);
12245: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12246: if (($courseid eq '') && ($cid)) {
12247: $courseid = $cid;
12248: }
12249: if (($symbparm && $courseid) &&
12250: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12251:
1.218 albertel 12252: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12253:
1.60 www 12254: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12255: my $symbp=$symbparm;
1.1301 raeburn 12256: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12257: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12258: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12259: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12260: if (($env{'user.name'} eq $uname) &&
12261: ($env{'user.domain'} eq $udom)) {
12262: $section=$env{'request.course.sec'};
1.733 raeburn 12263: @groups = split(/:/,$env{'request.course.groups'});
12264: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12265: } else {
1.539 albertel 12266: if (! defined($usection)) {
1.551 albertel 12267: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12268: } else {
12269: $section = $usection;
12270: }
1.733 raeburn 12271: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12272: }
12273:
12274: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12275: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12276: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12277: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12278:
1.593 albertel 12279: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12280: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12281: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12282: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12283:
1.60 www 12284: # ----------------------------------------------------------- first, check user
1.624 albertel 12285:
1.1301 raeburn 12286: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12287: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12288: ([$courselevelr,'resource'],
12289: [$courselevelm,'map' ],
1.1301 raeburn 12290: [$courseleveli,'map' ],
1.927 albertel 12291: [$courselevel, 'course' ]));
1.931 albertel 12292: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12293:
1.594 albertel 12294: # ------------------------------------------------ second, check some of course
1.684 raeburn 12295: my $coursereply;
1.691 raeburn 12296: if (@groups > 0) {
12297: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12298: $recurseparm,$mapparm,$spacequalifierrest,
12299: $mapp,\$recursed,\@recurseup);
12300: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12301: }
1.96 www 12302:
1.684 raeburn 12303: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12304: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12305: 'course',$mapp,\$recursed,\@recurseup,
12306: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12307: ([$seclevelr, 'resource'],
12308: [$seclevelm, 'map' ],
1.1301 raeburn 12309: [$secleveli, 'map' ],
1.927 albertel 12310: [$seclevel, 'course' ],
12311: [$courselevelr,'resource']));
12312: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12313:
1.60 www 12314: # ------------------------------------------------------ third, check map parms
1.218 albertel 12315: my %parmhash=();
12316: my $thisparm='';
12317: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12318: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12319: &GDBM_READER(),0640)) {
1.218 albertel 12320: $thisparm=$parmhash{$symbparm};
12321: untie(%parmhash);
12322: }
1.927 albertel 12323: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12324: }
1.594 albertel 12325: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12326:
12327: my $what = $spacequalifierrest;
12328: $what=~s/\./\_/;
1.282 albertel 12329: my $filename;
12330: if (!$symbparm) { $symbparm=&symbread(); }
12331: if ($symbparm) {
1.409 www 12332: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12333: } else {
1.620 albertel 12334: $filename=$env{'request.filename'};
1.282 albertel 12335: }
1.1362 raeburn 12336: my $toolsymb;
12337: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12338: $toolsymb = $symbparm;
12339: }
12340: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12341: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12342: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12343: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12344:
1.1301 raeburn 12345: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12346: if ($symbparm && defined($courseid) &&
1.620 albertel 12347: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12348: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12349: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12350: 'course',$mapp,\$recursed,\@recurseup,
12351: $courseid,'.',$spacequalifierrest,
1.927 albertel 12352: ([$courselevelm,'map' ],
1.1301 raeburn 12353: [$courseleveli,'map' ],
1.927 albertel 12354: [$courselevel, 'course']));
12355: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12356: }
1.145 www 12357: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12358: unless ($space eq '0') {
1.336 albertel 12359: my @parts=split(/_/,$space);
12360: my $id=pop(@parts);
12361: my $part=join('_',@parts);
12362: if ($part eq '') { $part='0'; }
1.927 albertel 12363: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12364: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12365: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12366: }
1.395 albertel 12367: if ($recurse) { return undef; }
1.1362 raeburn 12368: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12369: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12370: # ---------------------------------------------------- Any other user namespace
12371: } elsif ($realm eq 'environment') {
12372: # ----------------------------------------------------------------- environment
1.620 albertel 12373: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12374: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12375: } else {
1.770 albertel 12376: if ($uname eq 'anonymous' && $udom eq '') {
12377: return '';
12378: }
1.219 albertel 12379: my %returnhash=&userenvironment($udom,$uname,
12380: $spacequalifierrest);
12381: return $returnhash{$spacequalifierrest};
12382: }
1.28 www 12383: } elsif ($realm eq 'system') {
1.48 www 12384: # ----------------------------------------------------------------- system.time
12385: if ($space eq 'time') {
12386: return time;
12387: }
1.696 albertel 12388: } elsif ($realm eq 'server') {
12389: # ----------------------------------------------------------------- system.time
12390: if ($space eq 'name') {
12391: return $ENV{'SERVER_NAME'};
12392: }
1.1415 raeburn 12393: } elsif ($realm eq 'client') {
12394: if ($space eq 'remote_addr') {
12395: return $ENV{'REMOTE_ADDR'};
12396: }
1.28 www 12397: }
1.48 www 12398: return '';
1.61 www 12399: }
12400:
1.927 albertel 12401: sub get_reply {
12402: my ($reply_value) = @_;
1.940 raeburn 12403: if (ref($reply_value) eq 'ARRAY') {
12404: if (wantarray) {
12405: return @$reply_value;
12406: }
12407: return $reply_value->[0];
12408: } else {
12409: return $reply_value;
1.927 albertel 12410: }
12411: }
12412:
1.691 raeburn 12413: sub check_group_parms {
1.1301 raeburn 12414: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12415: $recursed,$recurseupref) = @_;
12416: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12417: [$what,'course']);
12418: my $coursereply;
1.691 raeburn 12419: foreach my $group (@{$groups}) {
1.1301 raeburn 12420: my @groupitems = ();
1.691 raeburn 12421: foreach my $level (@levels) {
1.927 albertel 12422: my $item = $courseid.'.['.$group.'].'.$level->[0];
12423: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12424: }
1.1301 raeburn 12425: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12426: $env{'course.'.$courseid.'.domain'},
12427: 'course',$mapp,$recursed,$recurseupref,
12428: $courseid,'.['.$group.'].',$what,
12429: @groupitems);
12430: last if (defined($coursereply));
1.691 raeburn 12431: }
12432: return $coursereply;
12433: }
12434:
1.1301 raeburn 12435: sub get_map_hierarchy {
1.1302 raeburn 12436: my ($mapname,$courseid) = @_;
12437: my @recurseup = ();
1.1301 raeburn 12438: if ($mapname) {
1.1302 raeburn 12439: if (($cachedmapkey eq $courseid) &&
12440: (abs($cachedmaptime-time)<5)) {
12441: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12442: return @{$cachedmaps{$mapname}};
12443: }
12444: }
1.1301 raeburn 12445: my $navmap = Apache::lonnavmaps::navmap->new();
12446: if (ref($navmap)) {
12447: @recurseup = $navmap->recurseup_maps($mapname);
12448: undef($navmap);
1.1302 raeburn 12449: $cachedmaps{$mapname} = \@recurseup;
12450: $cachedmaptime=time;
12451: $cachedmapkey=$courseid;
1.1301 raeburn 12452: }
12453: }
12454: return @recurseup;
12455: }
12456:
1.1302 raeburn 12457: }
12458:
1.691 raeburn 12459: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12460: my ($courseid,@groups) = @_;
12461: @groups = sort(@groups);
1.691 raeburn 12462: return @groups;
12463: }
12464:
1.395 albertel 12465: sub packages_tab_default {
1.1362 raeburn 12466: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12467: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12468:
12469: my (@extension,@specifics,$do_default);
1.1362 raeburn 12470: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12471: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12472: if ($pack_type eq 'default') {
12473: $do_default=1;
12474: } elsif ($pack_type eq 'extension') {
12475: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12476: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12477: # only look at packages defaults for packages that this id is
1.738 albertel 12478: push(@specifics,[$package,$pack_type,$pack_part]);
12479: }
12480: }
12481: # first look for a package that matches the requested part id
12482: foreach my $package (@specifics) {
12483: my (undef,$pack_type,$pack_part)=@{$package};
12484: next if ($pack_part ne $part);
12485: if (defined($packagetab{"$pack_type&$name&default"})) {
12486: return $packagetab{"$pack_type&$name&default"};
12487: }
12488: }
12489: # look for any possible matching non extension_ package
12490: foreach my $package (@specifics) {
12491: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12492: if (defined($packagetab{"$pack_type&$name&default"})) {
12493: return $packagetab{"$pack_type&$name&default"};
12494: }
1.585 albertel 12495: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12496: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12497: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12498: }
12499: }
1.738 albertel 12500: # look for any posible extension_ match
12501: foreach my $package (@extension) {
12502: my ($package,$pack_type)=@{$package};
12503: if (defined($packagetab{"$pack_type&$name&default"})) {
12504: return $packagetab{"$pack_type&$name&default"};
12505: }
12506: if (defined($packagetab{$package."&$name&default"})) {
12507: return $packagetab{$package."&$name&default"};
12508: }
12509: }
12510: # look for a global default setting
12511: if ($do_default && defined($packagetab{"default&$name&default"})) {
12512: return $packagetab{"default&$name&default"};
12513: }
1.395 albertel 12514: return undef;
12515: }
12516:
1.334 albertel 12517: sub add_prefix_and_part {
12518: my ($prefix,$part)=@_;
12519: my $keyroot;
12520: if (defined($prefix) && $prefix !~ /^__/) {
12521: # prefix that has a part already
12522: $keyroot=$prefix;
12523: } elsif (defined($prefix)) {
12524: # prefix that is missing a part
12525: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12526: } else {
12527: # no prefix at all
12528: if (defined($part)) { $keyroot='_'.$part; }
12529: }
12530: return $keyroot;
12531: }
12532:
1.71 www 12533: # ---------------------------------------------------------------- Get metadata
12534:
1.599 albertel 12535: my %metaentry;
1.1070 www 12536: my %importedpartids;
1.1369 raeburn 12537: my %importedrespids;
1.71 www 12538: sub metadata {
1.1362 raeburn 12539: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12540: $uri=&declutter($uri);
1.288 albertel 12541: # if it is a non metadata possible uri return quickly
1.529 albertel 12542: if (($uri eq '') ||
12543: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12544: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12545: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12546: return undef;
12547: }
1.1261 raeburn 12548: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12549: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12550: return undef;
1.288 albertel 12551: }
1.73 www 12552: my $filename=$uri;
12553: $uri=~s/\.meta$//;
1.172 www 12554: #
12555: # Is the metadata already cached?
1.177 www 12556: # Look at timestamp of caching
1.172 www 12557: # Everything is cached by the main uri, libraries are never directly cached
12558: #
1.428 albertel 12559: if (!defined($liburi)) {
1.599 albertel 12560: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12561: if (defined($cached)) { return $result->{':'.$what}; }
12562: }
1.1362 raeburn 12563:
12564: #
12565: # If the uri is for an external tool the file from
12566: # which metadata should be retrieved depends on whether
12567: # the tool had been configured to be gradable (set in the Course
12568: # Editor or Resource Editor).
12569: #
12570: # If a valid symb has been included as the third arg in the call
12571: # to &metadata() that can be used to retrieve the value of
12572: # parameter_0_gradable set for the resource, and included in the
12573: # uploaded map containing the tool. The value is retrieved via
12574: # &EXT(), if a valid symb is available. Otherwise the value of
12575: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12576: # is retrieved via &get().
12577: #
12578: # When lonuserstate::traceroute() calls lonnet::EXT() for
12579: # hiddenresource and encrypturl (during course initialization)
12580: # the map-level parameter for resource.0.gradable included in the
12581: # uploaded map containing the tool will not yet have been stored
12582: # in the user_course_parms.db file for the user's session, so in
12583: # this case fall back to retrieving gradable status from the
12584: # exttool_$marker.db file.
1.1362 raeburn 12585: #
12586: # In order to avoid an infinite loop, &metadata() will return
12587: # before a call to &EXT(), if the uri is for an external tool
12588: # and the $what for which metadata is being requested is
12589: # parameter_0_gradable or 0_gradable.
12590: #
12591:
12592: if ($uri =~ /ext\.tool$/) {
12593: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12594: return;
12595: } else {
12596: my ($checked,$use_passback);
12597: if ($toolsymb ne '') {
12598: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12599: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12600: $checked = 1;
12601: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12602: $use_passback = 1;
12603: }
12604: }
12605: }
12606: unless ($checked) {
12607: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12608: $marker=~s/\D//g;
1.1363 raeburn 12609: if ($marker) {
1.1362 raeburn 12610: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12611: $use_passback = $toolsettings{'gradable'};
12612: }
12613: }
12614: if ($use_passback) {
12615: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12616: } else {
12617: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12618: }
12619: }
12620: }
12621:
1.428 albertel 12622: {
1.1069 www 12623: # Imported parts would go here
1.1369 raeburn 12624: my @origfiletagids=();
1.1069 www 12625: my $importedparts=0;
1.1369 raeburn 12626:
12627: # Imported responseids would go here
12628: my $importedresponses=0;
1.172 www 12629: #
12630: # Is this a recursive call for a library?
12631: #
1.599 albertel 12632: # if (! exists($metacache{$uri})) {
12633: # $metacache{$uri}={};
12634: # }
1.924 albertel 12635: my $cachetime = 60*60;
1.171 www 12636: if ($liburi) {
12637: $liburi=&declutter($liburi);
12638: $filename=$liburi;
1.401 bowersj2 12639: } else {
1.599 albertel 12640: &devalidate_cache_new('meta',$uri);
12641: undef(%metaentry);
1.401 bowersj2 12642: }
1.140 www 12643: my %metathesekeys=();
1.73 www 12644: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12645: my $metastring;
1.1140 www 12646: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12647: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12648: $metastring =
1.929 albertel 12649: &Apache::lonnet::ssi_body($which,
1.924 albertel 12650: ('grade_target' => 'meta'));
12651: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12652: } elsif (($uri !~ m -^(editupload)/-) &&
12653: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12654: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12655: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12656: $metastring=&getfile($file);
1.489 albertel 12657: }
1.208 albertel 12658: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12659: my $token;
1.140 www 12660: undef %metathesekeys;
1.71 www 12661: while ($token=$parser->get_token) {
1.339 albertel 12662: if ($token->[0] eq 'S') {
12663: if (defined($token->[2]->{'package'})) {
1.172 www 12664: #
12665: # This is a package - get package info
12666: #
1.339 albertel 12667: my $package=$token->[2]->{'package'};
12668: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12669: if (defined($token->[2]->{'id'})) {
12670: $keyroot.='_'.$token->[2]->{'id'};
12671: }
1.599 albertel 12672: if ($metaentry{':packages'}) {
12673: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12674: } else {
1.599 albertel 12675: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12676: }
1.736 albertel 12677: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12678: my $part=$keyroot;
12679: $part=~s/^\_//;
1.736 albertel 12680: if ($pack_entry=~/^\Q$package\E\&/ ||
12681: $pack_entry=~/^\Q$package\E_0\&/) {
12682: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12683: # ignore package.tab specified default values
12684: # here &package_tab_default() will fetch those
12685: if ($subp eq 'default') { next; }
1.736 albertel 12686: my $value=$packagetab{$pack_entry};
1.432 albertel 12687: my $unikey;
12688: if ($pack =~ /_0$/) {
12689: $unikey='parameter_0_'.$name;
12690: $part=0;
12691: } else {
12692: $unikey='parameter'.$keyroot.'_'.$name;
12693: }
1.339 albertel 12694: if ($subp eq 'display') {
12695: $value.=' [Part: '.$part.']';
12696: }
1.599 albertel 12697: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12698: $metathesekeys{$unikey}=1;
1.599 albertel 12699: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12700: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12701: }
1.599 albertel 12702: if (defined($metaentry{':'.$unikey.'.default'})) {
12703: $metaentry{':'.$unikey}=
12704: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12705: }
1.339 albertel 12706: }
12707: }
12708: } else {
1.172 www 12709: #
12710: # This is not a package - some other kind of start tag
1.339 albertel 12711: #
12712: my $entry=$token->[1];
1.1068 www 12713: my $unikey='';
1.175 www 12714:
1.339 albertel 12715: if ($entry eq 'import') {
1.175 www 12716: #
12717: # Importing a library here
1.339 albertel 12718: #
1.1067 www 12719: my $location=$parser->get_text('/import');
12720: my $dir=$filename;
12721: $dir=~s|[^/]*$||;
12722: $location=&filelocation($dir,$location);
1.1369 raeburn 12723:
12724: my $importid=$token->[2]->{'id'};
1.1068 www 12725: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 12726: #
12727: # Check metadata for imported file to
12728: # see if it contained response items
12729: #
1.1372 raeburn 12730: my ($origfile,@libfilekeys);
1.1370 raeburn 12731: my %currmetaentry = %metaentry;
1.1372 raeburn 12732: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12733: $depthcount+1));
12734: if (grep(/^responseorder$/,@libfilekeys)) {
12735: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12736: undef,$depthcount+1);
12737: if ($libresponseorder ne '') {
12738: if ($#origfiletagids<0) {
12739: undef(%importedrespids);
12740: undef(%importedpartids);
12741: }
1.1373 raeburn 12742: my @respids = split(/\s*,\s*/,$libresponseorder);
12743: if (@respids) {
12744: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12745: }
12746: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 12747: $importedresponses = 1;
1.1369 raeburn 12748: # We need to get the original file and the imported file to get the response order correct
12749: # Load and inspect original file
1.1372 raeburn 12750: if ($#origfiletagids<0) {
12751: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12752: $origfile=&getfile($origfilelocation);
12753: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12754: }
1.1369 raeburn 12755: }
12756: }
12757: }
1.1370 raeburn 12758: # Do not overwrite contents of %metaentry hash for resource itself with
12759: # hash populated for imported library file
12760: %metaentry = %currmetaentry;
12761: undef(%currmetaentry);
1.1374 raeburn 12762: if ($importmode eq 'part') {
1.1068 www 12763: # Import as part(s)
1.1069 www 12764: $importedparts=1;
12765: # We need to get the original file and the imported file to get the part order correct
12766: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 12767: # Load and inspect original file if we didn't do that already
12768: if ($#origfiletagids<0) {
12769: undef(%importedrespids);
12770: undef(%importedpartids);
12771: if ($origfile eq '') {
12772: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12773: $origfile=&getfile($origfilelocation);
12774: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12775: }
1.1070 www 12776: }
1.1372 raeburn 12777: my @impfilepartids;
12778: # If <partorder> tag is included in metadata for the imported file
12779: # get the parts in the imported file from that.
12780: if (grep(/^partorder$/,@libfilekeys)) {
12781: %currmetaentry = %metaentry;
12782: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12783: $depthcount+1);
12784: %metaentry = %currmetaentry;
12785: undef(%currmetaentry);
12786: if ($libpartorder ne '') {
12787: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12788: }
12789: } else {
12790: # If no <partorder> tag available, load and inspect imported file
12791: my $impfile=&getfile($location);
12792: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12793: }
1.1069 www 12794: if ($#impfilepartids>=0) {
12795: # This problem had parts
1.1070 www 12796: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12797: } else {
12798: # Importing by turning a single problem into a problem part
12799: # It gets the import-tags ID as part-ID
12800: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12801: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12802: }
1.1068 www 12803: } else {
1.1374 raeburn 12804: # Import as problem or as normal import
12805: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12806: unless ($importmode eq 'problem') {
1.1068 www 12807: # Normal import
1.1374 raeburn 12808: if (defined($token->[2]->{'id'})) {
12809: $unikey.='_'.$token->[2]->{'id'};
12810: }
12811: }
12812: # Check metadata for imported file to
12813: # see if it contained parts
12814: if (grep(/^partorder$/,@libfilekeys)) {
12815: %currmetaentry = %metaentry;
12816: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12817: $depthcount+1);
12818: %metaentry = %currmetaentry;
12819: undef(%currmetaentry);
12820: if ($libpartorder ne '') {
12821: $importedparts = 1;
12822: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12823: }
12824: }
1.1067 www 12825: }
1.339 albertel 12826: if ($depthcount<20) {
1.736 albertel 12827: my $metadata =
1.1362 raeburn 12828: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 12829: $depthcount+1);
12830: foreach my $meta (split(',',$metadata)) {
12831: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12832: $metathesekeys{$meta}=1;
1.339 albertel 12833: }
1.1068 www 12834: }
1.1067 www 12835: } else {
12836: #
12837: # Not importing, some other kind of non-package, non-library start tag
12838: #
12839: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12840: if (defined($token->[2]->{'id'})) {
12841: $unikey.='_'.$token->[2]->{'id'};
12842: }
1.339 albertel 12843: if (defined($token->[2]->{'name'})) {
12844: $unikey.='_'.$token->[2]->{'name'};
12845: }
12846: $metathesekeys{$unikey}=1;
1.736 albertel 12847: foreach my $param (@{$token->[3]}) {
12848: $metaentry{':'.$unikey.'.'.$param} =
12849: $token->[2]->{$param};
1.339 albertel 12850: }
12851: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12852: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12853: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12854: # only ws inside the tag, and not in default, so use default
12855: # as value
1.599 albertel 12856: $metaentry{':'.$unikey}=$default;
1.908 albertel 12857: } elsif ( $internaltext =~ /\S/ ) {
12858: # something interesting inside the tag
12859: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12860: } else {
1.908 albertel 12861: # no interesting values, don't set a default
1.339 albertel 12862: }
1.172 www 12863: # end of not-a-package not-a-library import
1.339 albertel 12864: }
1.172 www 12865: # end of not-a-package start tag
1.339 albertel 12866: }
1.172 www 12867: # the next is the end of "start tag"
1.339 albertel 12868: }
12869: }
1.483 albertel 12870: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12871: $extension = lc($extension);
12872: if ($extension eq 'htm') { $extension='html'; }
12873:
1.737 albertel 12874: foreach my $key (keys(%packagetab)) {
1.483 albertel 12875: #no specific packages #how's our extension
12876: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12877: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12878: \%metathesekeys);
12879: }
1.883 albertel 12880:
12881: if (!exists($metaentry{':packages'})
12882: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12883: foreach my $key (keys(%packagetab)) {
1.483 albertel 12884: #no specific packages well let's get default then
12885: if ($key!~/^default&/) { next; }
1.488 albertel 12886: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12887: \%metathesekeys);
12888: }
12889: }
1.338 www 12890: # are there custom rights to evaluate
1.599 albertel 12891: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12892:
1.338 www 12893: #
12894: # Importing a rights file here
1.339 albertel 12895: #
12896: unless ($depthcount) {
1.599 albertel 12897: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12898: my $dir=$filename;
12899: $dir=~s|[^/]*$||;
12900: $location=&filelocation($dir,$location);
1.736 albertel 12901: my $rights_metadata =
1.1362 raeburn 12902: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 12903: $depthcount+1);
12904: foreach my $rights (split(',',$rights_metadata)) {
12905: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12906: $metathesekeys{$rights}=1;
1.339 albertel 12907: }
12908: }
12909: }
1.737 albertel 12910: # uniqifiy package listing
12911: my %seen;
12912: my @uniq_packages =
12913: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12914: $metaentry{':packages'} = join(',',@uniq_packages);
12915:
1.1369 raeburn 12916: if (($importedresponses) || ($importedparts)) {
12917: if ($importedparts) {
1.1070 www 12918: # We had imported parts and need to rebuild partorder
1.1369 raeburn 12919: $metaentry{':partorder'}='';
12920: $metathesekeys{'partorder'}=1;
12921: }
12922: if ($importedresponses) {
12923: # We had imported responses and need to rebuil responseorder
12924: $metaentry{':responseorder'}='';
12925: $metathesekeys{'responseorder'}=1;
12926: }
12927: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12928: my $origid = $origfiletagids[$index+1];
12929: if ($origfiletagids[$index] eq 'part') {
12930: # Original part, part of the problem
12931: if ($importedparts) {
12932: $metaentry{':partorder'}.=','.$origid;
12933: }
12934: } elsif ($origfiletagids[$index] eq 'import') {
12935: if ($importedparts) {
12936: # We have imported parts at this position
1.1373 raeburn 12937: if ($importedpartids{$origid} ne '') {
12938: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12939: }
1.1369 raeburn 12940: }
12941: if ($importedresponses) {
12942: # We have imported responses at this position
1.1373 raeburn 12943: if ($importedrespids{$origid} ne '') {
12944: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 12945: }
12946: }
12947: } else {
12948: # Original response item, part of the problem
12949: if ($importedresponses) {
12950: $metaentry{':responseorder'}.=','.$origid;
12951: }
12952: }
12953: }
12954: if ($importedparts) {
12955: $metaentry{':partorder'}=~s/^\,//;
12956: }
12957: if ($importedresponses) {
12958: $metaentry{':responseorder'}=~s/^\,//;
12959: }
1.1070 www 12960: }
1.737 albertel 12961: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12962: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 12963: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 12964: unless ($liburi) {
12965: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12966: }
1.177 www 12967: # this is the end of "was not already recently cached
1.71 www 12968: }
1.599 albertel 12969: return $metaentry{':'.$what};
1.261 albertel 12970: }
12971:
1.488 albertel 12972: sub metadata_create_package_def {
1.483 albertel 12973: my ($uri,$key,$package,$metathesekeys)=@_;
12974: my ($pack,$name,$subp)=split(/\&/,$key);
12975: if ($subp eq 'default') { next; }
12976:
1.599 albertel 12977: if (defined($metaentry{':packages'})) {
12978: $metaentry{':packages'}.=','.$package;
1.483 albertel 12979: } else {
1.599 albertel 12980: $metaentry{':packages'}=$package;
1.483 albertel 12981: }
12982: my $value=$packagetab{$key};
12983: my $unikey;
12984: $unikey='parameter_0_'.$name;
1.599 albertel 12985: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12986: $$metathesekeys{$unikey}=1;
1.599 albertel 12987: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12988: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12989: }
1.599 albertel 12990: if (defined($metaentry{':'.$unikey.'.default'})) {
12991: $metaentry{':'.$unikey}=
12992: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12993: }
12994: }
12995:
1.261 albertel 12996: sub metadata_generate_part0 {
12997: my ($metadata,$metacache,$uri) = @_;
12998: my %allnames;
1.737 albertel 12999: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13000: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13001: my $part=$$metacache{':'.$metakey.'.part'};
13002: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13003: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13004: $allnames{$name}=$part;
13005: }
13006: }
13007: }
13008: foreach my $name (keys(%allnames)) {
13009: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13010: my $key=":parameter_0_$name";
1.261 albertel 13011: $$metacache{"$key.part"}='0';
13012: $$metacache{"$key.name"}=$name;
1.428 albertel 13013: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13014: $allnames{$name}.'_'.$name.
13015: '.type'};
1.428 albertel 13016: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13017: '.display'};
1.644 www 13018: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13019: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13020: $$metacache{"$key.display"}=$olddis;
13021: }
1.71 www 13022: }
13023:
1.764 albertel 13024: # ------------------------------------------------------ Devalidate title cache
13025:
13026: sub devalidate_title_cache {
13027: my ($url)=@_;
13028: if (!$env{'request.course.id'}) { return; }
13029: my $symb=&symbread($url);
13030: if (!$symb) { return; }
13031: my $key=$env{'request.course.id'}."\0".$symb;
13032: &devalidate_cache_new('title',$key);
13033: }
13034:
1.1014 droeschl 13035: # ------------------------------------------------- Get the title of a course
13036:
13037: sub current_course_title {
13038: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13039: }
1.301 www 13040: # ------------------------------------------------- Get the title of a resource
13041:
13042: sub gettitle {
13043: my $urlsymb=shift;
13044: my $symb=&symbread($urlsymb);
1.534 albertel 13045: if ($symb) {
1.620 albertel 13046: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13047: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13048: if (defined($cached)) {
13049: return $result;
13050: }
1.534 albertel 13051: my ($map,$resid,$url)=&decode_symb($symb);
13052: my $title='';
1.907 albertel 13053: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13054: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13055: } else {
13056: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13057: &GDBM_READER(),0640)) {
13058: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13059: $title=$bighash{'title_'.$mapid.'.'.$resid};
13060: untie(%bighash);
13061: }
1.534 albertel 13062: }
13063: $title=~s/\&colon\;/\:/gs;
13064: if ($title) {
1.1159 www 13065: # Remember both $symb and $title for dynamic metadata
13066: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13067: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13068: # Cache this title and then return it
1.599 albertel 13069: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13070: }
13071: $urlsymb=$url;
13072: }
13073: my $title=&metadata($urlsymb,'title');
13074: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13075: return $title;
1.301 www 13076: }
1.613 albertel 13077:
1.614 albertel 13078: sub get_slot {
13079: my ($which,$cnum,$cdom)=@_;
13080: if (!$cnum || !$cdom) {
1.790 albertel 13081: (undef,my $courseid)=&whichuser();
1.620 albertel 13082: $cdom=$env{'course.'.$courseid.'.domain'};
13083: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13084: }
1.703 albertel 13085: my $key=join("\0",'slots',$cdom,$cnum,$which);
13086: my %slotinfo;
13087: if (exists($remembered{$key})) {
13088: $slotinfo{$which} = $remembered{$key};
13089: } else {
13090: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13091: &Apache::lonhomework::showhash(%slotinfo);
13092: my ($tmp)=keys(%slotinfo);
13093: if ($tmp=~/^error:/) { return (); }
13094: $remembered{$key} = $slotinfo{$which};
13095: }
1.616 albertel 13096: if (ref($slotinfo{$which}) eq 'HASH') {
13097: return %{$slotinfo{$which}};
13098: }
13099: return $slotinfo{$which};
1.614 albertel 13100: }
1.1150 raeburn 13101:
13102: sub get_reservable_slots {
13103: my ($cnum,$cdom,$uname,$udom) = @_;
13104: my $now = time;
13105: my $reservable_info;
13106: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13107: if (exists($remembered{$key})) {
13108: $reservable_info = $remembered{$key};
13109: } else {
13110: my %resv;
13111: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13112: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13113: $reservable_info = \%resv;
13114: $remembered{$key} = $reservable_info;
13115: }
13116: return $reservable_info;
13117: }
13118:
13119: sub get_course_slots {
13120: my ($cnum,$cdom) = @_;
13121: my $hashid=$cnum.':'.$cdom;
13122: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13123: if (defined($cached)) {
13124: if (ref($result) eq 'HASH') {
13125: return %{$result};
13126: }
13127: } else {
13128: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13129: my ($tmp) = keys(%slots);
13130: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13131: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13132: return %slots;
13133: }
13134: }
13135: return;
13136: }
13137:
13138: sub devalidate_slots_cache {
13139: my ($cnum,$cdom)=@_;
13140: my $hashid=$cnum.':'.$cdom;
13141: &devalidate_cache_new('allslots',$hashid);
13142: }
13143:
1.1181 raeburn 13144: sub get_coursechange {
13145: my ($cdom,$cnum) = @_;
13146: if ($cdom eq '' || $cnum eq '') {
13147: return unless ($env{'request.course.id'});
13148: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13149: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13150: }
13151: my $hashid=$cdom.'_'.$cnum;
13152: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13153: if ((defined($cached)) && ($change ne '')) {
13154: return $change;
13155: } else {
13156: my %crshash;
13157: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13158: if ($crshash{'internal.contentchange'} eq '') {
13159: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13160: if ($change eq '') {
13161: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13162: $change = $crshash{'internal.created'};
13163: }
13164: } else {
13165: $change = $crshash{'internal.contentchange'};
13166: }
13167: my $cachetime = 600;
13168: &do_cache_new('crschange',$hashid,$change,$cachetime);
13169: }
13170: return $change;
13171: }
13172:
13173: sub devalidate_coursechange_cache {
13174: my ($cnum,$cdom)=@_;
13175: my $hashid=$cnum.':'.$cdom;
13176: &devalidate_cache_new('crschange',$hashid);
13177: }
13178:
1.31 www 13179: # ------------------------------------------------- Update symbolic store links
13180:
13181: sub symblist {
13182: my ($mapname,%newhash)=@_;
1.438 www 13183: $mapname=&deversion(&declutter($mapname));
1.31 www 13184: my %hash;
1.620 albertel 13185: if (($env{'request.course.fn'}) && (%newhash)) {
13186: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13187: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13188: foreach my $url (keys(%newhash)) {
1.711 albertel 13189: next if ($url eq 'last_known'
13190: && $env{'form.no_update_last_known'});
13191: $hash{declutter($url)}=&encode_symb($mapname,
13192: $newhash{$url}->[1],
13193: $newhash{$url}->[0]);
1.191 harris41 13194: }
1.31 www 13195: if (untie(%hash)) {
13196: return 'ok';
13197: }
13198: }
13199: }
13200: return 'error';
1.212 www 13201: }
13202:
13203: # --------------------------------------------------------------- Verify a symb
13204:
13205: sub symbverify {
1.1190 raeburn 13206: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13207: my $thisfn=$thisurl;
1.439 www 13208: $thisfn=&declutter($thisfn);
1.215 www 13209: # direct jump to resource in page or to a sequence - will construct own symbs
13210: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13211: # check URL part
1.409 www 13212: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13213:
1.431 www 13214: unless ($url eq $thisfn) { return 0; }
1.213 www 13215:
1.216 www 13216: $symb=&symbclean($symb);
1.510 www 13217: $thisurl=&deversion($thisurl);
1.439 www 13218: $thisfn=&deversion($thisfn);
1.213 www 13219:
13220: my %bighash;
13221: my $okay=0;
1.431 www 13222:
1.620 albertel 13223: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13224: &GDBM_READER(),0640)) {
1.1032 raeburn 13225: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13226: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13227: if ($map =~ m{^uploaded/.+\.page$}) {
13228: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13229: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13230: }
13231: }
13232: my $ids;
1.1419 raeburn 13233: if ($map =~ m{^uploaded/.+\.page$}) {
13234: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13235: } else {
13236: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13237: }
1.1102 raeburn 13238: unless ($ids) {
13239: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13240: $ids=$bighash{$idkey};
1.216 www 13241: }
13242: if ($ids) {
13243: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13244: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13245: $symb =~ s/\?.+$//;
1.1202 raeburn 13246: }
1.800 albertel 13247: foreach my $id (split(/\,/,$ids)) {
13248: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13249: if (
13250: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13251: eq $symb) {
13252: if (ref($encstate)) {
13253: $$encstate = $bighash{'encrypted_'.$id};
13254: }
1.620 albertel 13255: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13256: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13257: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13258: $okay=1;
1.1202 raeburn 13259: last;
1.582 albertel 13260: }
13261: }
1.216 www 13262: }
13263: }
1.213 www 13264: untie(%bighash);
13265: }
13266: return $okay;
1.31 www 13267: }
13268:
1.210 www 13269: # --------------------------------------------------------------- Clean-up symb
13270:
13271: sub symbclean {
13272: my $symb=shift;
1.568 albertel 13273: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13274: # remove version from map
13275: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13276:
1.210 www 13277: # remove version from URL
13278: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13279:
1.507 www 13280: # remove wrapper
13281:
1.510 www 13282: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13283: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13284: return $symb;
1.409 www 13285: }
13286:
13287: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13288:
13289: sub encode_symb {
13290: my ($map,$resid,$url)=@_;
13291: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13292: }
1.409 www 13293:
13294: sub decode_symb {
1.568 albertel 13295: my $symb=shift;
13296: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13297: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13298: return (&fixversion($map),$resid,&fixversion($url));
13299: }
13300:
13301: sub fixversion {
13302: my $fn=shift;
1.609 banghart 13303: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13304: my %bighash;
13305: my $uri=&clutter($fn);
1.620 albertel 13306: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13307: # is this cached?
1.599 albertel 13308: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13309: if (defined($cached)) { return $result; }
13310: # unfortunately not cached, or expired
1.620 albertel 13311: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13312: &GDBM_READER(),0640)) {
13313: if ($bighash{'version_'.$uri}) {
13314: my $version=$bighash{'version_'.$uri};
1.444 www 13315: unless (($version eq 'mostrecent') ||
13316: ($version==&getversion($uri))) {
1.440 www 13317: $uri=~s/\.(\w+)$/\.$version\.$1/;
13318: }
13319: }
13320: untie %bighash;
1.413 www 13321: }
1.599 albertel 13322: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13323: }
13324:
13325: sub deversion {
13326: my $url=shift;
13327: $url=~s/\.\d+\.(\w+)$/\.$1/;
13328: return $url;
1.210 www 13329: }
13330:
1.31 www 13331: # ------------------------------------------------------ Return symb list entry
13332:
13333: sub symbread {
1.1424 raeburn 13334: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13335: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13336: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13337: if (defined($env{$cache_str})) {
1.1424 raeburn 13338: unless (ref($possibles) eq 'HASH') {
13339: if ($ignorecachednull) {
13340: return $env{$cache_str} unless ($env{$cache_str} eq '');
13341: } else {
13342: return $env{$cache_str};
13343: }
1.1282 raeburn 13344: }
13345: }
1.242 www 13346: # no filename provided? try from environment
1.1265 raeburn 13347: unless ($thisfn) {
1.620 albertel 13348: if ($env{'request.symb'}) {
1.1427 raeburn 13349: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13350: }
1.620 albertel 13351: $thisfn=$env{'request.filename'};
1.44 www 13352: }
1.569 albertel 13353: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13354: # is that filename actually a symb? Verify, clean, and return
13355: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13356: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 13357: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13358: }
1.242 www 13359: }
1.44 www 13360: $thisfn=declutter($thisfn);
1.31 www 13361: my %hash;
1.37 www 13362: my %bighash;
13363: my $syval='';
1.620 albertel 13364: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13365: my $targetfn = $thisfn;
1.609 banghart 13366: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13367: $targetfn = 'adm/wrapper/'.$thisfn;
13368: }
1.687 albertel 13369: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13370: $targetfn=$1;
13371: }
1.1427 raeburn 13372: unless ($ignoresymbdb) {
1.1424 raeburn 13373: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13374: &GDBM_READER(),0640)) {
13375: $syval=$hash{$targetfn};
13376: untie(%hash);
13377: }
1.1427 raeburn 13378: if ($syval && $checkforblock) {
13379: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 13380: if (@blockers) {
13381: $syval='';
13382: }
13383: }
1.37 www 13384: }
13385: # ---------------------------------------------------------- There was an entry
13386: if ($syval) {
1.601 albertel 13387: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13388: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13389: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13390: #return $env{$cache_str}='';
1.601 albertel 13391: #}
13392: #$syval.=$1;
13393: #}
1.37 www 13394: } else {
13395: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13396: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13397: &GDBM_READER(),0640)) {
1.37 www 13398: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13399: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13400: unless ($ids) {
13401: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13402: }
13403: unless ($ids) {
13404: # alias?
13405: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13406: }
1.37 www 13407: if ($ids) {
13408: # ------------------------------------------------------------------- Has ID(s)
13409: my @possibilities=split(/\,/,$ids);
1.39 www 13410: if ($#possibilities==0) {
13411: # ----------------------------------------------- There is only one possibility
1.37 www 13412: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13413: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13414: $resid,$thisfn);
1.1282 raeburn 13415: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 13416: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13417: $possibles->{$syval} = 1;
13418: }
1.1282 raeburn 13419: }
13420: if ($checkforblock) {
1.1424 raeburn 13421: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 13422: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 13423: if (@blockers) {
13424: $syval = '';
1.1425 raeburn 13425: untie(%bighash);
13426: return $env{$cache_str}='';
1.1424 raeburn 13427: }
1.1282 raeburn 13428: }
13429: }
13430: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13431: # ------------------------------------------ There is more than one possibility
13432: my $realpossible=0;
1.800 albertel 13433: foreach my $id (@possibilities) {
13434: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13435: my $canaccess;
13436: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13437: $canaccess = 1;
13438: } else {
13439: $canaccess = &allowed('bre',$file);
13440: }
13441: if ($canaccess) {
13442: my ($mapid,$resid)=split(/\./,$id);
13443: if ($bighash{'map_type_'.$mapid} ne 'page') {
13444: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13445: $resid,$thisfn);
1.1424 raeburn 13446: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 13447: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 13448: if ($checkforblock) {
1.1426 raeburn 13449: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 13450: if (@blockers > 0) {
13451: $syval = '';
13452: } else {
1.1282 raeburn 13453: $syval = $poss_syval;
13454: $realpossible++;
13455: }
13456: } else {
13457: $syval = $poss_syval;
13458: $realpossible++;
13459: }
1.1424 raeburn 13460: if ($syval) {
13461: if (ref($possibles) eq 'HASH') {
13462: $possibles->{$syval} = 1;
13463: }
13464: }
1.1282 raeburn 13465: }
1.39 www 13466: }
1.191 harris41 13467: }
1.39 www 13468: if ($realpossible!=1) { $syval=''; }
1.249 www 13469: } else {
13470: $syval='';
1.37 www 13471: }
13472: }
1.1282 raeburn 13473: untie(%bighash);
1.481 raeburn 13474: }
1.31 www 13475: }
1.62 www 13476: if ($syval) {
1.1427 raeburn 13477: return $env{$cache_str}=$syval;
1.62 www 13478: }
1.31 www 13479: }
1.949 raeburn 13480: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13481: return $env{$cache_str}='';
1.31 www 13482: }
13483:
13484: # ---------------------------------------------------------- Return random seed
13485:
1.32 www 13486: sub numval {
13487: my $txt=shift;
13488: $txt=~tr/A-J/0-9/;
13489: $txt=~tr/a-j/0-9/;
13490: $txt=~tr/K-T/0-9/;
13491: $txt=~tr/k-t/0-9/;
13492: $txt=~tr/U-Z/0-5/;
13493: $txt=~tr/u-z/0-5/;
13494: $txt=~s/\D//g;
1.564 albertel 13495: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13496: return int($txt);
1.368 albertel 13497: }
13498:
1.484 albertel 13499: sub numval2 {
13500: my $txt=shift;
13501: $txt=~tr/A-J/0-9/;
13502: $txt=~tr/a-j/0-9/;
13503: $txt=~tr/K-T/0-9/;
13504: $txt=~tr/k-t/0-9/;
13505: $txt=~tr/U-Z/0-5/;
13506: $txt=~tr/u-z/0-5/;
13507: $txt=~s/\D//g;
13508: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13509: my $total;
13510: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13511: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13512: return int($total);
13513: }
13514:
1.575 albertel 13515: sub numval3 {
13516: use integer;
13517: my $txt=shift;
13518: $txt=~tr/A-J/0-9/;
13519: $txt=~tr/a-j/0-9/;
13520: $txt=~tr/K-T/0-9/;
13521: $txt=~tr/k-t/0-9/;
13522: $txt=~tr/U-Z/0-5/;
13523: $txt=~tr/u-z/0-5/;
13524: $txt=~s/\D//g;
13525: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13526: my $total;
13527: foreach my $val (@txts) { $total+=$val; }
13528: if ($_64bit) { $total=(($total<<32)>>32); }
13529: return $total;
13530: }
13531:
1.675 albertel 13532: sub digest {
13533: my ($data)=@_;
13534: my $digest=&Digest::MD5::md5($data);
13535: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13536: my ($e,$f);
13537: {
13538: use integer;
13539: $e=($a+$b);
13540: $f=($c+$d);
13541: if ($_64bit) {
13542: $e=(($e<<32)>>32);
13543: $f=(($f<<32)>>32);
13544: }
13545: }
13546: if (wantarray) {
13547: return ($e,$f);
13548: } else {
13549: my $g;
13550: {
13551: use integer;
13552: $g=($e+$f);
13553: if ($_64bit) {
13554: $g=(($g<<32)>>32);
13555: }
13556: }
13557: return $g;
13558: }
13559: }
13560:
1.368 albertel 13561: sub latest_rnd_algorithm_id {
1.675 albertel 13562: return '64bit5';
1.366 albertel 13563: }
1.32 www 13564:
1.503 albertel 13565: sub get_rand_alg {
13566: my ($courseid)=@_;
1.790 albertel 13567: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13568: if ($courseid) {
1.620 albertel 13569: return $env{"course.$courseid.rndseed"};
1.503 albertel 13570: }
13571: return &latest_rnd_algorithm_id();
13572: }
13573:
1.562 albertel 13574: sub validCODE {
13575: my ($CODE)=@_;
13576: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13577: return 0;
13578: }
13579:
1.491 albertel 13580: sub getCODE {
1.620 albertel 13581: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13582: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13583: defined($Apache::lonhomework::parsing_a_task) ) &&
13584: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13585: return $Apache::lonhomework::history{'resource.CODE'};
13586: }
13587: return undef;
13588: }
1.1133 foxr 13589: #
13590: # Determines the random seed for a specific context:
13591: #
13592: # parameters:
13593: # symb - in course context the symb for the seed.
13594: # course_id - The course id of the form domain_coursenum.
13595: # domain - Domain for the user.
13596: # course - Course for the user.
13597: # cenv - environment of the course.
13598: #
13599: # NOTE:
13600: # All parameters are picked out of the environment if missing
13601: # or not defined.
13602: # If a symb cannot be determined the current time is used instead.
13603: #
13604: # For a given well defined symb, courside, domain, username,
13605: # and course environment, the seed is reproducible.
13606: #
1.31 www 13607: sub rndseed {
1.1133 foxr 13608: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13609: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13610: if (!defined($symb)) {
1.366 albertel 13611: unless ($symb=$wsymb) { return time; }
13612: }
1.1146 foxr 13613: if (!defined $courseid) {
13614: $courseid=$wcourseid;
13615: }
13616: if (!defined $domain) { $domain=$wdomain; }
13617: if (!defined $username) { $username=$wusername }
1.1133 foxr 13618:
13619: my $which;
13620: if (defined($cenv->{'rndseed'})) {
13621: $which = $cenv->{'rndseed'};
13622: } else {
13623: $which =&get_rand_alg($courseid);
13624: }
1.491 albertel 13625: if (defined(&getCODE())) {
1.1133 foxr 13626:
1.675 albertel 13627: if ($which eq '64bit5') {
13628: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13629: } elsif ($which eq '64bit4') {
1.575 albertel 13630: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13631: } else {
13632: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13633: }
1.675 albertel 13634: } elsif ($which eq '64bit5') {
13635: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13636: } elsif ($which eq '64bit4') {
13637: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13638: } elsif ($which eq '64bit3') {
13639: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13640: } elsif ($which eq '64bit2') {
13641: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13642: } elsif ($which eq '64bit') {
13643: return &rndseed_64bit($symb,$courseid,$domain,$username);
13644: }
13645: return &rndseed_32bit($symb,$courseid,$domain,$username);
13646: }
13647:
13648: sub rndseed_32bit {
13649: my ($symb,$courseid,$domain,$username)=@_;
13650: {
13651: use integer;
13652: my $symbchck=unpack("%32C*",$symb) << 27;
13653: my $symbseed=numval($symb) << 22;
13654: my $namechck=unpack("%32C*",$username) << 17;
13655: my $nameseed=numval($username) << 12;
13656: my $domainseed=unpack("%32C*",$domain) << 7;
13657: my $courseseed=unpack("%32C*",$courseid);
13658: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13659: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13660: #&logthis("rndseed :$num:$symb");
1.564 albertel 13661: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13662: return $num;
13663: }
13664: }
13665:
13666: sub rndseed_64bit {
13667: my ($symb,$courseid,$domain,$username)=@_;
13668: {
13669: use integer;
13670: my $symbchck=unpack("%32S*",$symb) << 21;
13671: my $symbseed=numval($symb) << 10;
13672: my $namechck=unpack("%32S*",$username);
13673:
13674: my $nameseed=numval($username) << 21;
13675: my $domainseed=unpack("%32S*",$domain) << 10;
13676: my $courseseed=unpack("%32S*",$courseid);
13677:
13678: my $num1=$symbchck+$symbseed+$namechck;
13679: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13680: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13681: #&logthis("rndseed :$num:$symb");
1.564 albertel 13682: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13683: return "$num1,$num2";
1.155 albertel 13684: }
1.366 albertel 13685: }
13686:
1.443 albertel 13687: sub rndseed_64bit2 {
13688: my ($symb,$courseid,$domain,$username)=@_;
13689: {
13690: use integer;
13691: # strings need to be an even # of cahracters long, it it is odd the
13692: # last characters gets thrown away
13693: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13694: my $symbseed=numval($symb) << 10;
13695: my $namechck=unpack("%32S*",$username.' ');
13696:
13697: my $nameseed=numval($username) << 21;
1.501 albertel 13698: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13699: my $courseseed=unpack("%32S*",$courseid.' ');
13700:
13701: my $num1=$symbchck+$symbseed+$namechck;
13702: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13703: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13704: #&logthis("rndseed :$num:$symb");
1.803 albertel 13705: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13706: return "$num1,$num2";
13707: }
13708: }
13709:
13710: sub rndseed_64bit3 {
13711: my ($symb,$courseid,$domain,$username)=@_;
13712: {
13713: use integer;
13714: # strings need to be an even # of cahracters long, it it is odd the
13715: # last characters gets thrown away
13716: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13717: my $symbseed=numval2($symb) << 10;
13718: my $namechck=unpack("%32S*",$username.' ');
13719:
13720: my $nameseed=numval2($username) << 21;
1.443 albertel 13721: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13722: my $courseseed=unpack("%32S*",$courseid.' ');
13723:
13724: my $num1=$symbchck+$symbseed+$namechck;
13725: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13726: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13727: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13728: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13729:
1.503 albertel 13730: return "$num1:$num2";
1.443 albertel 13731: }
13732: }
13733:
1.575 albertel 13734: sub rndseed_64bit4 {
13735: my ($symb,$courseid,$domain,$username)=@_;
13736: {
13737: use integer;
13738: # strings need to be an even # of cahracters long, it it is odd the
13739: # last characters gets thrown away
13740: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13741: my $symbseed=numval3($symb) << 10;
13742: my $namechck=unpack("%32S*",$username.' ');
13743:
13744: my $nameseed=numval3($username) << 21;
13745: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13746: my $courseseed=unpack("%32S*",$courseid.' ');
13747:
13748: my $num1=$symbchck+$symbseed+$namechck;
13749: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13750: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13751: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13752: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13753:
1.575 albertel 13754: return "$num1:$num2";
13755: }
13756: }
13757:
1.675 albertel 13758: sub rndseed_64bit5 {
13759: my ($symb,$courseid,$domain,$username)=@_;
13760: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13761: return "$num1:$num2";
13762: }
13763:
1.366 albertel 13764: sub rndseed_CODE_64bit {
13765: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13766: {
1.366 albertel 13767: use integer;
1.443 albertel 13768: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13769: my $symbseed=numval2($symb);
1.491 albertel 13770: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13771: my $CODEseed=numval(&getCODE());
1.443 albertel 13772: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13773: my $num1=$symbseed+$CODEchck;
13774: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13775: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13776: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13777: if ($_64bit) { $num1=(($num1<<32)>>32); }
13778: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13779: return "$num1:$num2";
1.366 albertel 13780: }
13781: }
13782:
1.575 albertel 13783: sub rndseed_CODE_64bit4 {
13784: my ($symb,$courseid,$domain,$username)=@_;
13785: {
13786: use integer;
13787: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13788: my $symbseed=numval3($symb);
13789: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13790: my $CODEseed=numval3(&getCODE());
13791: my $courseseed=unpack("%32S*",$courseid.' ');
13792: my $num1=$symbseed+$CODEchck;
13793: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13794: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13795: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13796: if ($_64bit) { $num1=(($num1<<32)>>32); }
13797: if ($_64bit) { $num2=(($num2<<32)>>32); }
13798: return "$num1:$num2";
13799: }
13800: }
13801:
1.675 albertel 13802: sub rndseed_CODE_64bit5 {
13803: my ($symb,$courseid,$domain,$username)=@_;
13804: my $code = &getCODE();
13805: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13806: return "$num1:$num2";
13807: }
13808:
1.366 albertel 13809: sub setup_random_from_rndseed {
13810: my ($rndseed)=@_;
1.503 albertel 13811: if ($rndseed =~/([,:])/) {
1.1262 raeburn 13812: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13813: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13814: &Math::Random::random_set_seed_from_phrase($rndseed);
13815: } else {
13816: &Math::Random::random_set_seed($num1,$num2);
13817: }
1.366 albertel 13818: } else {
13819: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13820: }
1.36 albertel 13821: }
13822:
1.474 albertel 13823: sub latest_receipt_algorithm_id {
1.835 albertel 13824: return 'receipt3';
1.474 albertel 13825: }
13826:
1.480 www 13827: sub recunique {
13828: my $fucourseid=shift;
13829: my $unique;
1.835 albertel 13830: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13831: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13832: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13833: } else {
13834: $unique=$perlvar{'lonReceipt'};
13835: }
13836: return unpack("%32C*",$unique);
13837: }
13838:
13839: sub recprefix {
13840: my $fucourseid=shift;
13841: my $prefix;
1.835 albertel 13842: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13843: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13844: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13845: } else {
13846: $prefix=$perlvar{'lonHostID'};
13847: }
13848: return unpack("%32C*",$prefix);
13849: }
13850:
1.76 www 13851: sub ireceipt {
1.474 albertel 13852: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13853:
13854: my $return =&recprefix($fucourseid).'-';
13855:
13856: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13857: $env{'request.state'} eq 'construct') {
13858: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13859: return $return;
13860: }
13861:
1.76 www 13862: my $cuname=unpack("%32C*",$funame);
13863: my $cudom=unpack("%32C*",$fudom);
13864: my $cucourseid=unpack("%32C*",$fucourseid);
13865: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13866: my $cunique=&recunique($fucourseid);
1.474 albertel 13867: my $cpart=unpack("%32S*",$part);
1.835 albertel 13868: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13869:
1.790 albertel 13870: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13871:
13872: $return.= ($cunique%$cuname+
13873: $cunique%$cudom+
13874: $cusymb%$cuname+
13875: $cusymb%$cudom+
13876: $cucourseid%$cuname+
13877: $cucourseid%$cudom+
13878: $cpart%$cuname+
13879: $cpart%$cudom);
13880: } else {
13881: $return.= ($cunique%$cuname+
13882: $cunique%$cudom+
13883: $cusymb%$cuname+
13884: $cusymb%$cudom+
13885: $cucourseid%$cuname+
13886: $cucourseid%$cudom);
13887: }
13888: return $return;
1.76 www 13889: }
13890:
13891: sub receipt {
1.474 albertel 13892: my ($part)=@_;
1.790 albertel 13893: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13894: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13895: }
1.260 ng 13896:
1.790 albertel 13897: sub whichuser {
13898: my ($passedsymb)=@_;
13899: my ($symb,$courseid,$domain,$name,$publicuser);
13900: if (defined($env{'form.grade_symb'})) {
13901: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13902: my $allowed=&allowed('vgr',$tmp_courseid);
13903: if (!$allowed &&
13904: exists($env{'request.course.sec'}) &&
13905: $env{'request.course.sec'} !~ /^\s*$/) {
13906: $allowed=&allowed('vgr',$tmp_courseid.
13907: '/'.$env{'request.course.sec'});
13908: }
13909: if ($allowed) {
13910: ($symb)=&get_env_multiple('form.grade_symb');
13911: $courseid=$tmp_courseid;
13912: ($domain)=&get_env_multiple('form.grade_domain');
13913: ($name)=&get_env_multiple('form.grade_username');
13914: return ($symb,$courseid,$domain,$name,$publicuser);
13915: }
13916: }
13917: if (!$passedsymb) {
13918: $symb=&symbread();
13919: } else {
13920: $symb=$passedsymb;
13921: }
13922: $courseid=$env{'request.course.id'};
13923: $domain=$env{'user.domain'};
13924: $name=$env{'user.name'};
13925: if ($name eq 'public' && $domain eq 'public') {
13926: if (!defined($env{'form.username'})) {
13927: $env{'form.username'}.=time.rand(10000000);
13928: }
13929: $name.=$env{'form.username'};
13930: }
13931: return ($symb,$courseid,$domain,$name,$publicuser);
13932:
13933: }
13934:
1.36 albertel 13935: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13936: # returns either the contents of the file or
13937: # -1 if the file doesn't exist
1.481 raeburn 13938: #
13939: # if the target is a file that was uploaded via DOCS,
13940: # a check will be made to see if a current copy exists on the local server,
13941: # if it does this will be served, otherwise a copy will be retrieved from
13942: # the home server for the course and stored in /home/httpd/html/userfiles on
13943: # the local server.
1.472 albertel 13944:
1.36 albertel 13945: sub getfile {
1.538 albertel 13946: my ($file) = @_;
1.609 banghart 13947: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13948: &repcopy($file);
13949: return &readfile($file);
13950: }
13951:
13952: sub repcopy_userfile {
13953: my ($file)=@_;
1.1142 raeburn 13954: my $londocroot = $perlvar{'lonDocRoot'};
13955: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13956: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13957: my ($cdom,$cnum,$filename) =
1.811 albertel 13958: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13959: my $uri="/uploaded/$cdom/$cnum/$filename";
13960: if (-e "$file") {
1.828 www 13961: # we already have a local copy, check it out
1.538 albertel 13962: my @fileinfo = stat($file);
1.828 www 13963: my $rtncode;
13964: my $info;
1.538 albertel 13965: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13966: if ($lwpresp ne 'ok') {
1.828 www 13967: # there is no such file anymore, even though we had a local copy
1.482 albertel 13968: if ($rtncode eq '404') {
1.538 albertel 13969: unlink($file);
1.482 albertel 13970: }
13971: return -1;
13972: }
13973: if ($info < $fileinfo[9]) {
1.828 www 13974: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13975: return 'ok';
1.828 www 13976: } else {
13977: # the file is outdated, get rid of it
13978: unlink($file);
1.482 albertel 13979: }
1.828 www 13980: }
13981: # one way or the other, at this point, we don't have the file
13982: # construct the correct path for the file
13983: my @parts = ($cdom,$cnum);
13984: if ($filename =~ m|^(.+)/[^/]+$|) {
13985: push @parts, split(/\//,$1);
13986: }
13987: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13988: foreach my $part (@parts) {
13989: $path .= '/'.$part;
13990: if (!-e $path) {
13991: mkdir($path,0770);
1.482 albertel 13992: }
13993: }
1.828 www 13994: # now the path exists for sure
13995: # get a user agent
13996: my $transferfile=$file.'.in.transfer';
13997: # FIXME: this should flock
13998: if (-e $transferfile) { return 'ok'; }
13999: my $request;
14000: $uri=~s/^\///;
1.980 raeburn 14001: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14002: my $hostname = &hostname($homeserver);
1.980 raeburn 14003: my $protocol = $protocol{$homeserver};
14004: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14005: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14006: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14007: # did it work?
14008: if ($response->is_error()) {
14009: unlink($transferfile);
14010: &logthis("Userfile repcopy failed for $uri");
14011: return -1;
14012: }
14013: # worked, rename the transfer file
14014: rename($transferfile,$file);
1.607 raeburn 14015: return 'ok';
1.481 raeburn 14016: }
14017:
1.517 albertel 14018: sub tokenwrapper {
14019: my $uri=shift;
1.980 raeburn 14020: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14021: $uri=~s|^/||;
1.620 albertel 14022: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14023: my $token=$1;
1.552 albertel 14024: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14025: if ($udom && $uname && $file) {
14026: $file=~s|(\?\.*)*$||;
1.949 raeburn 14027: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14028: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14029: my $hostname = &hostname($homeserver);
1.980 raeburn 14030: my $protocol = $protocol{$homeserver};
14031: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14032: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14033: (($uri=~/\?/)?'&':'?').'token='.$token.
14034: '&tokenissued='.$perlvar{'lonHostID'};
14035: } else {
14036: return '/adm/notfound.html';
14037: }
14038: }
14039:
1.828 www 14040: # call with reqtype HEAD: get last modification time
14041: # call with reqtype GET: get the file contents
14042: # Do not call this with reqtype GET for large files! It loads everything into memory
14043: #
1.481 raeburn 14044: sub getuploaded {
14045: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14046: $uri=~s/^\///;
1.980 raeburn 14047: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14048: my $hostname = &hostname($homeserver);
1.980 raeburn 14049: my $protocol = $protocol{$homeserver};
14050: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14051: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14052: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14053: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14054: $$rtncode = $response->code;
1.482 albertel 14055: if (! $response->is_success()) {
14056: return 'failed';
14057: }
14058: if ($reqtype eq 'HEAD') {
1.486 www 14059: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14060: } elsif ($reqtype eq 'GET') {
14061: $$info = $response->content;
1.472 albertel 14062: }
1.482 albertel 14063: return 'ok';
1.36 albertel 14064: }
14065:
1.481 raeburn 14066: sub readfile {
14067: my $file = shift;
14068: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14069: my $fh;
1.1359 raeburn 14070: open($fh,"<",$file);
1.481 raeburn 14071: my $a='';
1.800 albertel 14072: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14073: return $a;
14074: }
14075:
1.36 albertel 14076: sub filelocation {
1.590 banghart 14077: my ($dir,$file) = @_;
14078: my $location;
14079: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14080:
14081: if ($file =~ m-^/adm/-) {
14082: $file=~s-^/adm/wrapper/-/-;
14083: $file=~s-^/adm/coursedocs/showdoc/-/-;
14084: }
1.882 albertel 14085:
1.1139 www 14086: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14087: $location = $file;
1.609 banghart 14088: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14089: my ($udom,$uname,$filename)=
1.811 albertel 14090: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14091: my $home=&homeserver($uname,$udom);
14092: my $is_me=0;
14093: my @ids=¤t_machine_ids();
14094: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14095: if ($is_me) {
1.1117 foxr 14096: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14097: } else {
14098: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14099: $udom.'/'.$uname.'/'.$filename;
14100: }
1.882 albertel 14101: } elsif ($file =~ m-^/adm/-) {
14102: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14103: } else {
14104: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14105: $file=~s:^/(res|priv)/:/:;
14106: my $space=$1;
1.590 banghart 14107: if ( !( $file =~ m:^/:) ) {
14108: $location = $dir. '/'.$file;
14109: } else {
1.1142 raeburn 14110: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14111: }
1.59 albertel 14112: }
1.590 banghart 14113: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14114: while ($location=~m{/\.\./}) {
14115: if ($location =~ m{/[^/]+/\.\./}) {
14116: $location=~ s{/[^/]+/\.\./}{/}g;
14117: } else {
14118: $location=~ s{/\.\./}{/}g;
14119: }
14120: } #remove dir/..
1.590 banghart 14121: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14122: return $location;
1.46 www 14123: }
1.36 albertel 14124:
1.46 www 14125: sub hreflocation {
14126: my ($dir,$file)=@_;
1.980 raeburn 14127: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14128: $file=filelocation($dir,$file);
1.700 albertel 14129: } elsif ($file=~m-^/adm/-) {
14130: $file=~s-^/adm/wrapper/-/-;
14131: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14132: }
14133: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14134: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14135: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14136: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14137: {/uploaded/$1/$2/}x;
1.46 www 14138: }
1.913 albertel 14139: if ($file=~ m{^/userfiles/}) {
14140: $file =~ s{^/userfiles/}{/uploaded/};
14141: }
1.462 albertel 14142: return $file;
1.465 albertel 14143: }
14144:
1.1139 www 14145:
14146:
14147:
14148:
1.465 albertel 14149: sub current_machine_domains {
1.853 albertel 14150: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14151: }
14152:
14153: sub machine_domains {
14154: my ($hostname) = @_;
1.465 albertel 14155: my @domains;
1.838 albertel 14156: my %hostname = &all_hostnames();
1.465 albertel 14157: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14158: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14159: if ($hostname eq $name) {
1.844 albertel 14160: push(@domains,&host_domain($id));
1.465 albertel 14161: }
14162: }
14163: return @domains;
14164: }
14165:
14166: sub current_machine_ids {
1.853 albertel 14167: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14168: }
14169:
14170: sub machine_ids {
14171: my ($hostname) = @_;
14172: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14173: my @ids;
1.888 albertel 14174: my %name_to_host = &all_names();
1.889 albertel 14175: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14176: return @{ $name_to_host{$hostname} };
14177: }
14178: return;
1.31 www 14179: }
14180:
1.824 raeburn 14181: sub additional_machine_domains {
14182: my @domains;
1.1359 raeburn 14183: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 14184: while( my $line = <$fh>) {
14185: $line =~ s/\s//g;
14186: push(@domains,$line);
14187: }
14188: return @domains;
14189: }
14190:
14191: sub default_login_domain {
14192: my $domain = $perlvar{'lonDefDomain'};
14193: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14194: foreach my $posdom (¤t_machine_domains(),
14195: &additional_machine_domains()) {
14196: if (lc($posdom) eq lc($testdomain)) {
14197: $domain=$posdom;
14198: last;
14199: }
14200: }
14201: return $domain;
14202: }
14203:
1.1414 raeburn 14204: sub shared_institution {
14205: my ($dom) = @_;
14206: my $same_intdom;
14207: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14208: if ($hostintdom ne '') {
14209: my %iphost = &get_iphost();
14210: my $primary_id = &domain($dom,'primary');
14211: my $primary_ip = &get_host_ip($primary_id);
14212: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14213: foreach my $id (@{$iphost{$primary_ip}}) {
14214: my $intdom = &internet_dom($id);
14215: if ($intdom eq $hostintdom) {
14216: $same_intdom = 1;
14217: last;
14218: }
14219: }
14220: }
14221: }
14222: return $same_intdom;
14223: }
14224:
1.1398 raeburn 14225: sub uses_sts {
14226: my ($ignore_cache) = @_;
14227: my $lonhost = $perlvar{'lonHostID'};
14228: my $hostname = &hostname($lonhost);
14229: my $sts_on;
14230: if ($protocol{$lonhost} eq 'https') {
14231: my $cachetime = 12*3600;
14232: if (!$ignore_cache) {
14233: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14234: if (defined($cached)) {
14235: return $sts_on;
14236: }
14237: }
14238: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14239: my $request=new HTTP::Request('HEAD',$url);
14240: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14241: if ($response->is_success) {
14242: my $has_sts = $response->header('Strict-Transport-Security');
14243: if ($has_sts eq '') {
14244: $sts_on = 0;
14245: } else {
14246: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14247: my $maxage = $1;
14248: if ($maxage) {
14249: $sts_on = 1;
14250: } else {
14251: $sts_on = 0;
14252: }
14253: } else {
14254: $sts_on = 0;
14255: }
14256: }
14257: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14258: }
14259: }
14260: return;
14261: }
14262:
1.31 www 14263: # ------------------------------------------------------------- Declutters URLs
14264:
14265: sub declutter {
14266: my $thisfn=shift;
1.569 albertel 14267: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 14268: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14269: $thisfn=~s{^/home/httpd/html}{};
14270: }
1.31 www 14271: $thisfn=~s/^\///;
1.697 albertel 14272: $thisfn=~s|^adm/wrapper/||;
14273: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14274: $thisfn=~s/^res\///;
1.1172 bisitz 14275: $thisfn=~s/^priv\///;
1.1032 raeburn 14276: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14277: $thisfn=~s/\?.+$//;
14278: }
1.268 www 14279: return $thisfn;
14280: }
14281:
14282: # ------------------------------------------------------------- Clutter up URLs
14283:
14284: sub clutter {
14285: my $thisfn='/'.&declutter(shift);
1.887 albertel 14286: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14287: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14288: $thisfn='/res'.$thisfn;
14289: }
1.1031 raeburn 14290: if ($thisfn !~m|^/adm|) {
14291: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14292: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14293: } else {
14294: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14295: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14296: if ($embstyle eq 'ssi'
14297: || ($embstyle eq 'hdn')
14298: || ($embstyle eq 'rat')
14299: || ($embstyle eq 'prv')
14300: || ($embstyle eq 'ign')) {
14301: #do nothing with these
14302: } elsif (($embstyle eq 'img')
1.695 albertel 14303: || ($embstyle eq 'emb')
14304: || ($embstyle eq 'wrp')) {
14305: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14306: } elsif ($embstyle eq 'unk'
14307: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14308: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14309: } else {
1.718 www 14310: # &logthis("Got a blank emb style");
1.695 albertel 14311: }
1.694 albertel 14312: }
1.1343 raeburn 14313: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14314: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14315: }
1.31 www 14316: return $thisfn;
1.12 www 14317: }
14318:
1.787 albertel 14319: sub clutter_with_no_wrapper {
14320: my $uri = &clutter(shift);
14321: if ($uri =~ m-^/adm/-) {
14322: $uri =~ s-^/adm/wrapper/-/-;
14323: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14324: }
14325: return $uri;
14326: }
14327:
1.557 albertel 14328: sub freeze_escape {
14329: my ($value)=@_;
14330: if (ref($value)) {
14331: $value=&nfreeze($value);
14332: return '__FROZEN__'.&escape($value);
14333: }
14334: return &escape($value);
14335: }
14336:
1.11 www 14337:
1.557 albertel 14338: sub thaw_unescape {
14339: my ($value)=@_;
14340: if ($value =~ /^__FROZEN__/) {
14341: substr($value,0,10,undef);
14342: $value=&unescape($value);
14343: return &thaw($value);
14344: }
14345: return &unescape($value);
14346: }
14347:
1.436 albertel 14348: sub correct_line_ends {
14349: my ($result)=@_;
14350: $$result =~s/\r\n/\n/mg;
14351: $$result =~s/\r/\n/mg;
1.415 albertel 14352: }
1.1 albertel 14353: # ================================================================ Main Program
14354:
1.184 www 14355: sub goodbye {
1.204 albertel 14356: &logthis("Starting Shut down");
1.443 albertel 14357: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14358: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14359: #converted
1.599 albertel 14360: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14361: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14362: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14363: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14364: #1.1 only
1.870 albertel 14365: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14366: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14367: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14368: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14369: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14370: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14371: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14372: &flushcourselogs();
14373: &logthis("Shutting down");
14374: }
14375:
1.852 albertel 14376: sub get_dns {
1.1210 raeburn 14377: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14378: if (!$ignore_cache) {
14379: my ($content,$cached)=
14380: &Apache::lonnet::is_cached_new('dns',$url);
14381: if ($cached) {
1.1210 raeburn 14382: &$func($content,$hashref);
1.869 albertel 14383: return;
14384: }
14385: }
14386:
14387: my %alldns;
1.1379 raeburn 14388: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14389: foreach my $dns (<$config>) {
14390: next if ($dns !~ /^\^(\S*)/x);
14391: my $line = $1;
14392: my ($host,$protocol) = split(/:/,$line);
14393: if ($protocol ne 'https') {
14394: $protocol = 'http';
14395: }
14396: $alldns{$host} = $protocol;
1.979 raeburn 14397: }
1.1379 raeburn 14398: close($config);
1.869 albertel 14399: }
14400: while (%alldns) {
1.1263 raeburn 14401: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 14402: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 14403: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 14404: delete($alldns{$dns});
1.852 albertel 14405: next if ($response->is_error());
1.1379 raeburn 14406: if ($url eq '/adm/dns/loncapaCRL') {
14407: return &$func($response);
14408: } else {
14409: my @content = split("\n",$response->content);
14410: unless ($nocache) {
14411: &do_cache_new('dns',$url,\@content,30*24*60*60);
14412: }
14413: &$func(\@content,$hashref);
14414: return;
14415: }
14416: }
14417: my $which = (split('/',$url,4))[3];
14418: if ($which eq 'loncapaCRL') {
14419: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14420: if (-e $diskfile) {
14421: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14422: } else {
14423: &logthis("unable to contact DNS, no on disk file $diskfile available");
14424: }
14425: } else {
14426: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14427: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14428: my @content = <$config>;
14429: close($config);
14430: &$func(\@content,$hashref);
14431: }
1.852 albertel 14432: }
1.1210 raeburn 14433: return;
14434: }
14435:
14436: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 14437: sub parse_dns_checksums_tab {
1.1210 raeburn 14438: my ($lines,$hashref) = @_;
1.1264 raeburn 14439: my $lonhost = $perlvar{'lonHostID'};
14440: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 14441: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 14442: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14443: my $webconfdir = '/etc/httpd/conf';
14444: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14445: $webconfdir = '/etc/apache2';
14446: } elsif ($distro =~ /^sles(\d+)$/) {
14447: if ($1 >= 10) {
14448: $webconfdir = '/etc/apache2';
14449: }
14450: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14451: if ($1 >= 10.0) {
14452: $webconfdir = '/etc/apache2';
14453: }
14454: }
1.1210 raeburn 14455: my ($release,$timestamp) = split(/\-/,$loncaparev);
14456: my (%chksum,%revnum);
14457: if (ref($lines) eq 'ARRAY') {
14458: chomp(@{$lines});
1.1238 raeburn 14459: my $version = shift(@{$lines});
14460: if ($version eq $release) {
1.1210 raeburn 14461: foreach my $line (@{$lines}) {
1.1238 raeburn 14462: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 14463: if ($file =~ m{^/etc/httpd/conf}) {
14464: if ($webconfdir eq '/etc/apache2') {
14465: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14466: }
14467: }
1.1238 raeburn 14468: $chksum{$file} = $shasum;
14469: $revnum{$file} = $version;
1.1210 raeburn 14470: }
14471: if (ref($hashref) eq 'HASH') {
14472: %{$hashref} = (
14473: sums => \%chksum,
14474: versions => \%revnum,
14475: );
14476: }
14477: }
14478: }
1.869 albertel 14479: return;
1.852 albertel 14480: }
1.1210 raeburn 14481:
14482: sub fetch_dns_checksums {
1.1238 raeburn 14483: my %checksums;
14484: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 14485: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 14486: my ($release,$timestamp) = split(/\-/,$loncaparev);
14487: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 14488: \%checksums);
1.1210 raeburn 14489: return \%checksums;
14490: }
14491:
1.1379 raeburn 14492: sub fetch_crl_pemfile {
14493: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14494: }
14495:
14496: sub save_crl_pem {
14497: my ($response) = @_;
1.1380 raeburn 14498: my ($msg,$hadchanges);
1.1379 raeburn 14499: if (ref($response)) {
14500: my $now = time;
14501: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14502: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14503: if (open(my $fh,'>',"$tmpcrl")) {
14504: print $fh $response->content;
14505: close($fh);
14506: if (-e $lonca) {
14507: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14508: my $check = <PIPE>;
14509: close(PIPE);
14510: chomp($check);
14511: if ($check eq 'verify OK') {
14512: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 14513: my $backup;
1.1379 raeburn 14514: if (-e $dest) {
1.1380 raeburn 14515: if (&File::Copy::move($dest,"$dest.bak")) {
14516: $backup = 'ok';
14517: }
1.1379 raeburn 14518: }
14519: if (&File::Copy::move($tmpcrl,$dest)) {
14520: $msg = 'ok';
1.1380 raeburn 14521: if ($backup) {
14522: my (%oldnums,%newnums);
14523: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14524: while (<PIPE>) {
14525: $oldnums{(split(/:/))[1]} = 1;
14526: }
14527: close(PIPE);
14528: }
14529: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14530: while(<PIPE>) {
14531: $newnums{(split(/:/))[1]} = 1;
14532: }
14533: close(PIPE);
14534: }
14535: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14536: unless (exists($oldnums{$key})) {
14537: $hadchanges = 1;
14538: last;
14539: }
14540: }
14541: unless ($hadchanges) {
14542: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14543: unless (exists($newnums{$key})) {
14544: $hadchanges = 1;
14545: last;
14546: }
14547: }
14548: }
14549: }
1.1379 raeburn 14550: }
14551: } else {
14552: unlink($tmpcrl);
14553: }
14554: } else {
14555: unlink($tmpcrl);
14556: }
14557: } else {
14558: unlink($tmpcrl);
14559: }
14560: }
14561: }
1.1380 raeburn 14562: return ($msg,$hadchanges);
1.1379 raeburn 14563: }
14564:
1.327 albertel 14565: # ------------------------------------------------------------ Read domain file
14566: {
1.852 albertel 14567: my $loaded;
1.846 albertel 14568: my %domain;
14569:
1.852 albertel 14570: sub parse_domain_tab {
14571: my ($lines) = @_;
14572: foreach my $line (@$lines) {
14573: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14574:
1.846 albertel 14575: chomp($line);
1.852 albertel 14576: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14577: my %this_domain;
14578: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14579: 'lang_def', 'city', 'longi', 'lati',
14580: 'primary') {
14581: $this_domain{$field} = shift(@elements);
14582: }
14583: $domain{$name} = \%this_domain;
1.852 albertel 14584: }
14585: }
1.864 albertel 14586:
14587: sub reset_domain_info {
14588: undef($loaded);
14589: undef(%domain);
14590: }
14591:
1.852 albertel 14592: sub load_domain_tab {
1.1293 raeburn 14593: my ($ignore_cache,$nocache) = @_;
14594: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14595: my $fh;
1.1359 raeburn 14596: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14597: my @lines = <$fh>;
14598: &parse_domain_tab(\@lines);
1.448 albertel 14599: }
1.852 albertel 14600: close($fh);
14601: $loaded = 1;
1.327 albertel 14602: }
1.846 albertel 14603:
14604: sub domain {
1.852 albertel 14605: &load_domain_tab() if (!$loaded);
14606:
1.846 albertel 14607: my ($name,$what) = @_;
14608: return if ( !exists($domain{$name}) );
14609:
14610: if (!$what) {
14611: return $domain{$name}{'description'};
14612: }
14613: return $domain{$name}{$what};
14614: }
1.974 raeburn 14615:
14616: sub domain_info {
14617: &load_domain_tab() if (!$loaded);
14618: return %domain;
14619: }
14620:
1.327 albertel 14621: }
14622:
14623:
1.1 albertel 14624: # ------------------------------------------------------------- Read hosts file
14625: {
1.838 albertel 14626: my %hostname;
1.844 albertel 14627: my %hostdom;
1.845 albertel 14628: my %libserv;
1.852 albertel 14629: my $loaded;
1.888 albertel 14630: my %name_to_host;
1.1074 raeburn 14631: my %internetdom;
1.1107 raeburn 14632: my %LC_dns_serv;
1.852 albertel 14633:
14634: sub parse_hosts_tab {
14635: my ($file) = @_;
14636: foreach my $configline (@$file) {
14637: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14638: chomp($configline);
14639: if ($configline =~ /^\^/) {
14640: if ($configline =~ /^\^([\w.\-]+)/) {
14641: $LC_dns_serv{$1} = 1;
14642: }
14643: next;
14644: }
1.1074 raeburn 14645: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14646: $name=~s/\s//g;
14647: if ($id && $domain && $role && $name) {
1.1351 raeburn 14648: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14649: my $curr = $hostname{$id};
14650: my $skip;
14651: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14652: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14653: $skip = 1;
14654: } else {
14655: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14656: }
14657: }
14658: unless ($skip) {
14659: push(@{$name_to_host{$name}},$id);
14660: }
14661: } else {
14662: push(@{$name_to_host{$name}},$id);
14663: }
1.852 albertel 14664: $hostname{$id}=$name;
14665: $hostdom{$id}=$domain;
14666: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14667: if (defined($protocol)) {
14668: if ($protocol eq 'https') {
14669: $protocol{$id} = $protocol;
14670: } else {
14671: $protocol{$id} = 'http';
14672: }
1.968 raeburn 14673: } else {
1.969 raeburn 14674: $protocol{$id} = 'http';
1.968 raeburn 14675: }
1.1074 raeburn 14676: if (defined($intdom)) {
14677: $internetdom{$id} = $intdom;
14678: }
1.852 albertel 14679: }
14680: }
14681: }
1.864 albertel 14682:
14683: sub reset_hosts_info {
1.897 albertel 14684: &purge_remembered();
1.864 albertel 14685: &reset_domain_info();
14686: &reset_hosts_ip_info();
1.1339 raeburn 14687: undef(%internetdom);
1.892 albertel 14688: undef(%name_to_host);
1.864 albertel 14689: undef(%hostname);
14690: undef(%hostdom);
14691: undef(%libserv);
14692: undef($loaded);
14693: }
1.1 albertel 14694:
1.852 albertel 14695: sub load_hosts_tab {
1.1293 raeburn 14696: my ($ignore_cache,$nocache) = @_;
14697: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 14698: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14699: my @config = <$config>;
14700: &parse_hosts_tab(\@config);
14701: close($config);
14702: $loaded=1;
1.1 albertel 14703: }
1.852 albertel 14704:
1.838 albertel 14705: sub hostname {
1.852 albertel 14706: &load_hosts_tab() if (!$loaded);
14707:
1.838 albertel 14708: my ($lonid) = @_;
14709: return $hostname{$lonid};
14710: }
1.845 albertel 14711:
1.838 albertel 14712: sub all_hostnames {
1.852 albertel 14713: &load_hosts_tab() if (!$loaded);
14714:
1.838 albertel 14715: return %hostname;
14716: }
1.845 albertel 14717:
1.888 albertel 14718: sub all_names {
1.1293 raeburn 14719: my ($ignore_cache,$nocache) = @_;
14720: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14721:
14722: return %name_to_host;
14723: }
14724:
1.974 raeburn 14725: sub all_host_domain {
14726: &load_hosts_tab() if (!$loaded);
14727: return %hostdom;
14728: }
14729:
1.1339 raeburn 14730: sub all_host_intdom {
14731: &load_hosts_tab() if (!$loaded);
14732: return %internetdom;
14733: }
14734:
1.845 albertel 14735: sub is_library {
1.852 albertel 14736: &load_hosts_tab() if (!$loaded);
14737:
1.845 albertel 14738: return exists($libserv{$_[0]});
14739: }
14740:
14741: sub all_library {
1.852 albertel 14742: &load_hosts_tab() if (!$loaded);
14743:
1.845 albertel 14744: return %libserv;
14745: }
14746:
1.1062 droeschl 14747: sub unique_library {
14748: #2x reverse removes all hostnames that appear more than once
14749: my %unique = reverse &all_library();
14750: return reverse %unique;
14751: }
14752:
1.841 albertel 14753: sub get_servers {
1.852 albertel 14754: &load_hosts_tab() if (!$loaded);
14755:
1.841 albertel 14756: my ($domain,$type) = @_;
14757: my %possible_hosts = ($type eq 'library') ? %libserv
14758: : %hostname;
14759: my %result;
1.842 albertel 14760: if (ref($domain) eq 'ARRAY') {
14761: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14762: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14763: $result{$host} = $hostname;
14764: }
14765: }
14766: } else {
14767: while ( my ($host,$hostname) = each(%possible_hosts)) {
14768: if ($hostdom{$host} eq $domain) {
14769: $result{$host} = $hostname;
14770: }
1.841 albertel 14771: }
14772: }
14773: return %result;
14774: }
1.845 albertel 14775:
1.1062 droeschl 14776: sub get_unique_servers {
14777: my %unique = reverse &get_servers(@_);
14778: return reverse %unique;
14779: }
14780:
1.844 albertel 14781: sub host_domain {
1.852 albertel 14782: &load_hosts_tab() if (!$loaded);
14783:
1.844 albertel 14784: my ($lonid) = @_;
14785: return $hostdom{$lonid};
14786: }
14787:
1.841 albertel 14788: sub all_domains {
1.852 albertel 14789: &load_hosts_tab() if (!$loaded);
14790:
1.841 albertel 14791: my %seen;
14792: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14793: return @uniq;
14794: }
1.1074 raeburn 14795:
14796: sub internet_dom {
14797: &load_hosts_tab() if (!$loaded);
14798:
14799: my ($lonid) = @_;
14800: return $internetdom{$lonid};
14801: }
1.1107 raeburn 14802:
14803: sub is_LC_dns {
14804: &load_hosts_tab() if (!$loaded);
14805:
14806: my ($hostname) = @_;
14807: return exists($LC_dns_serv{$hostname});
14808: }
14809:
1.1 albertel 14810: }
14811:
1.847 albertel 14812: {
14813: my %iphost;
1.856 albertel 14814: my %name_to_ip;
14815: my %lonid_to_ip;
1.869 albertel 14816:
1.847 albertel 14817: sub get_hosts_from_ip {
14818: my ($ip) = @_;
14819: my %iphosts = &get_iphost();
14820: if (ref($iphosts{$ip})) {
14821: return @{$iphosts{$ip}};
14822: }
14823: return;
1.839 albertel 14824: }
1.864 albertel 14825:
14826: sub reset_hosts_ip_info {
14827: undef(%iphost);
14828: undef(%name_to_ip);
14829: undef(%lonid_to_ip);
14830: }
1.856 albertel 14831:
14832: sub get_host_ip {
14833: my ($lonid) = @_;
14834: if (exists($lonid_to_ip{$lonid})) {
14835: return $lonid_to_ip{$lonid};
14836: }
14837: my $name=&hostname($lonid);
14838: my $ip = gethostbyname($name);
14839: return if (!$ip || length($ip) ne 4);
14840: $ip=inet_ntoa($ip);
14841: $name_to_ip{$name} = $ip;
14842: $lonid_to_ip{$lonid} = $ip;
14843: return $ip;
14844: }
1.847 albertel 14845:
14846: sub get_iphost {
1.1293 raeburn 14847: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14848:
1.869 albertel 14849: if (!$ignore_cache) {
14850: if (%iphost) {
14851: return %iphost;
14852: }
14853: my ($ip_info,$cached)=
14854: &Apache::lonnet::is_cached_new('iphost','iphost');
14855: if ($cached) {
14856: %iphost = %{$ip_info->[0]};
14857: %name_to_ip = %{$ip_info->[1]};
14858: %lonid_to_ip = %{$ip_info->[2]};
14859: return %iphost;
14860: }
14861: }
1.894 albertel 14862:
14863: # get yesterday's info for fallback
14864: my %old_name_to_ip;
14865: my ($ip_info,$cached)=
14866: &Apache::lonnet::is_cached_new('iphost','iphost');
14867: if ($cached) {
14868: %old_name_to_ip = %{$ip_info->[1]};
14869: }
14870:
1.1293 raeburn 14871: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14872: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14873: my $ip;
14874: if (!exists($name_to_ip{$name})) {
14875: $ip = gethostbyname($name);
14876: if (!$ip || length($ip) ne 4) {
1.894 albertel 14877: if (defined($old_name_to_ip{$name})) {
14878: $ip = $old_name_to_ip{$name};
14879: &logthis("Can't find $name defaulting to old $ip");
14880: } else {
14881: &logthis("Name $name no IP found");
14882: next;
14883: }
14884: } else {
14885: $ip=inet_ntoa($ip);
1.847 albertel 14886: }
14887: $name_to_ip{$name} = $ip;
14888: } else {
14889: $ip = $name_to_ip{$name};
1.653 albertel 14890: }
1.888 albertel 14891: foreach my $id (@{ $name_to_host{$name} }) {
14892: $lonid_to_ip{$id} = $ip;
14893: }
14894: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14895: }
1.1293 raeburn 14896: unless ($nocache) {
14897: &do_cache_new('iphost','iphost',
14898: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14899: 48*60*60);
14900: }
1.869 albertel 14901:
1.847 albertel 14902: return %iphost;
1.598 albertel 14903: }
14904:
1.992 raeburn 14905: #
14906: # Given a DNS returns the loncapa host name for that DNS
14907: #
14908: sub host_from_dns {
14909: my ($dns) = @_;
14910: my @hosts;
14911: my $ip;
14912:
1.993 raeburn 14913: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14914: $ip = $name_to_ip{$dns};
14915: }
14916: if (!$ip) {
14917: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14918: if (length($ip) == 4) {
14919: $ip = &IO::Socket::inet_ntoa($ip);
14920: }
14921: }
14922: if ($ip) {
14923: @hosts = get_hosts_from_ip($ip);
14924: return $hosts[0];
14925: }
14926: return undef;
1.986 foxr 14927: }
1.992 raeburn 14928:
1.1074 raeburn 14929: sub get_internet_names {
14930: my ($lonid) = @_;
14931: return if ($lonid eq '');
14932: my ($idnref,$cached)=
14933: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14934: if ($cached) {
14935: return $idnref;
14936: }
14937: my $ip = &get_host_ip($lonid);
14938: my @hosts = &get_hosts_from_ip($ip);
14939: my %iphost = &get_iphost();
14940: my (@idns,%seen);
14941: foreach my $id (@hosts) {
14942: my $dom = &host_domain($id);
14943: my $prim_id = &domain($dom,'primary');
14944: my $prim_ip = &get_host_ip($prim_id);
14945: next if ($seen{$prim_ip});
14946: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14947: foreach my $id (@{$iphost{$prim_ip}}) {
14948: my $intdom = &internet_dom($id);
14949: unless (grep(/^\Q$intdom\E$/,@idns)) {
14950: push(@idns,$intdom);
14951: }
14952: }
14953: }
14954: $seen{$prim_ip} = 1;
14955: }
1.1219 raeburn 14956: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14957: }
14958:
1.986 foxr 14959: }
14960:
1.1079 raeburn 14961: sub all_loncaparevs {
1.1249 raeburn 14962: 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 14963: }
14964:
1.1227 raeburn 14965: # ---------------------------------------------------------- Read loncaparev table
14966: {
14967: sub load_loncaparevs {
14968: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 14969: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 14970: while (my $configline=<$config>) {
14971: chomp($configline);
14972: my ($hostid,$loncaparev)=split(/:/,$configline);
14973: $loncaparevs{$hostid}=$loncaparev;
14974: }
14975: close($config);
14976: }
14977: }
14978: }
14979: }
14980:
14981: # ---------------------------------------------------------- Read serverhostID table
14982: {
14983: sub load_serverhomeIDs {
14984: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 14985: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 14986: while (my $configline=<$config>) {
14987: chomp($configline);
14988: my ($name,$id)=split(/:/,$configline);
14989: $serverhomeIDs{$name}=$id;
14990: }
14991: close($config);
14992: }
14993: }
14994: }
14995: }
14996:
14997:
1.862 albertel 14998: BEGIN {
14999:
15000: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15001: unless ($readit) {
15002: {
15003: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15004: %perlvar = (%perlvar,%{$configvars});
15005: }
15006:
15007:
1.1 albertel 15008: # ------------------------------------------------------ Read spare server file
15009: {
1.1359 raeburn 15010: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15011:
15012: while (my $configline=<$config>) {
15013: chomp($configline);
1.284 matthew 15014: if ($configline) {
1.784 albertel 15015: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15016: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15017: push(@{ $spareid{$type} }, $host);
1.1 albertel 15018: }
15019: }
1.448 albertel 15020: close($config);
1.1 albertel 15021: }
1.11 www 15022: # ------------------------------------------------------------ Read permissions
15023: {
1.1359 raeburn 15024: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15025:
15026: while (my $configline=<$config>) {
1.448 albertel 15027: chomp($configline);
15028: if ($configline) {
15029: my ($role,$perm)=split(/ /,$configline);
15030: if ($perm ne '') { $pr{$role}=$perm; }
15031: }
1.11 www 15032: }
1.448 albertel 15033: close($config);
1.11 www 15034: }
15035:
15036: # -------------------------------------------- Read plain texts for permissions
15037: {
1.1359 raeburn 15038: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15039:
15040: while (my $configline=<$config>) {
1.448 albertel 15041: chomp($configline);
15042: if ($configline) {
1.742 raeburn 15043: my ($short,@plain)=split(/:/,$configline);
15044: %{$prp{$short}} = ();
15045: if (@plain > 0) {
15046: $prp{$short}{'std'} = $plain[0];
15047: for (my $i=1; $i<@plain; $i++) {
15048: $prp{$short}{'alt'.$i} = $plain[$i];
15049: }
15050: }
1.448 albertel 15051: }
1.135 www 15052: }
1.448 albertel 15053: close($config);
1.135 www 15054: }
15055:
15056: # ---------------------------------------------------------- Read package table
15057: {
1.1359 raeburn 15058: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15059:
15060: while (my $configline=<$config>) {
1.483 albertel 15061: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15062: chomp($configline);
15063: my ($short,$plain)=split(/:/,$configline);
15064: my ($pack,$name)=split(/\&/,$short);
15065: if ($plain ne '') {
15066: $packagetab{$pack.'&'.$name.'&name'}=$name;
15067: $packagetab{$short}=$plain;
15068: }
1.11 www 15069: }
1.448 albertel 15070: close($config);
1.329 matthew 15071: }
15072:
1.1073 raeburn 15073: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15074:
15075: &load_loncaparevs();
1.1073 raeburn 15076:
1.1074 raeburn 15077: # ---------------------------------------------------------- Read serverhostID table
15078:
1.1227 raeburn 15079: &load_serverhomeIDs();
15080:
15081: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15082: {
15083: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15084: if (-e $file) {
15085: my $parser = HTML::LCParser->new($file);
15086: while (my $token = $parser->get_token()) {
15087: if ($token->[0] eq 'S') {
15088: my $item = $token->[1];
15089: my $name = $token->[2]{'name'};
15090: my $value = $token->[2]{'value'};
1.1285 raeburn 15091: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15092: my $namematch = $token->[2]{'namematch'};
15093: if ($item eq 'parameter') {
15094: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15095: my $release = $parser->get_text();
15096: $release =~ s/(^\s*|\s*$ )//gx;
15097: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15098: }
15099: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15100: my $release = $parser->get_text();
15101: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15102: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15103: }
15104: }
15105: }
15106: }
1.1073 raeburn 15107: }
15108:
1.1138 raeburn 15109: # ---------------------------------------------------------- Read managers table
15110: {
15111: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15112: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15113: while (my $configline=<$config>) {
15114: chomp($configline);
15115: next if ($configline =~ /^\#/);
15116: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15117: $managerstab{$configline} = 1;
15118: }
15119: }
15120: close($config);
15121: }
15122: }
15123: }
15124:
1.329 matthew 15125: # ------------- set up temporary directory
15126: {
1.1117 foxr 15127: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15128:
1.11 www 15129: }
15130:
1.1405 raeburn 15131: # ------------- set default texengine (domain default overrides this)
15132: {
15133: $deftex = LONCAPA::texengine();
15134: }
15135:
1.1416 raeburn 15136: # ------------- set default minimum length for passwords for internal auth users
15137: {
15138: $passwdmin = LONCAPA::passwd_min();
15139: }
15140:
1.794 albertel 15141: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15142: 'compress_threshold'=> 20_000,
15143: });
1.185 www 15144:
1.281 www 15145: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15146: $dumpcount=0;
1.958 www 15147: $locknum=0;
1.22 www 15148:
1.163 harris41 15149: &logtouch();
1.672 albertel 15150: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15151: $readit=1;
1.564 albertel 15152: {
15153: use integer;
15154: my $test=(2**32)+1;
1.568 albertel 15155: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15156: &logthis(" Detected 64bit platform ($_64bit)");
15157: }
1.195 www 15158: }
1.1 albertel 15159: }
1.179 www 15160:
1.1 albertel 15161: 1;
1.191 harris41 15162: __END__
15163:
1.243 albertel 15164: =pod
15165:
1.191 harris41 15166: =head1 NAME
15167:
1.243 albertel 15168: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15169:
15170: =head1 SYNOPSIS
15171:
1.243 albertel 15172: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15173:
15174: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15175:
1.243 albertel 15176: Common parameters:
15177:
15178: =over 4
15179:
15180: =item *
15181:
15182: $uname : an internal username (if $cname expecting a course Id specifically)
15183:
15184: =item *
15185:
15186: $udom : a domain (if $cdom expecting a course's domain specifically)
15187:
15188: =item *
15189:
15190: $symb : a resource instance identifier
15191:
15192: =item *
15193:
15194: $namespace : the name of a .db file that contains the data needed or
15195: being set.
15196:
15197: =back
15198:
1.394 bowersj2 15199: =head1 OVERVIEW
1.191 harris41 15200:
1.394 bowersj2 15201: lonnet provides subroutines which interact with the
15202: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15203: about classes, users, and resources.
1.243 albertel 15204:
15205: For many of these objects you can also use this to store data about
15206: them or modify them in various ways.
1.191 harris41 15207:
1.394 bowersj2 15208: =head2 Symbs
1.191 harris41 15209:
1.394 bowersj2 15210: To identify a specific instance of a resource, LON-CAPA uses symbols
15211: or "symbs"X<symb>. These identifiers are built from the URL of the
15212: map, the resource number of the resource in the map, and the URL of
15213: the resource itself. The latter is somewhat redundant, but might help
15214: if maps change.
15215:
15216: An example is
15217:
15218: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15219:
15220: The respective map entry is
15221:
15222: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15223: title="Problem 2">
15224: </resource>
15225:
15226: Symbs are used by the random number generator, as well as to store and
15227: restore data specific to a certain instance of for example a problem.
15228:
15229: =head2 Storing And Retrieving Data
15230:
15231: X<store()>X<cstore()>X<restore()>Three of the most important functions
15232: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15233: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15234: is is the non-critical message twin of cstore. These functions are for
15235: handlers to store a perl hash to a user's permanent data space in an
15236: easy manner, and to retrieve it again on another call. It is expected
15237: that a handler would use this once at the beginning to retrieve data,
15238: and then again once at the end to send only the new data back.
15239:
15240: The data is stored in the user's data directory on the user's
15241: homeserver under the ID of the course.
15242:
15243: The hash that is returned by restore will have all of the previous
15244: value for all of the elements of the hash.
15245:
15246: Example:
15247:
15248: #creating a hash
15249: my %hash;
15250: $hash{'foo'}='bar';
15251:
15252: #storing it
15253: &Apache::lonnet::cstore(\%hash);
15254:
15255: #changing a value
15256: $hash{'foo'}='notbar';
15257:
15258: #adding a new value
15259: $hash{'bar'}='foo';
15260: &Apache::lonnet::cstore(\%hash);
15261:
15262: #retrieving the hash
15263: my %history=&Apache::lonnet::restore();
15264:
15265: #print the hash
15266: foreach my $key (sort(keys(%history))) {
15267: print("\%history{$key} = $history{$key}");
15268: }
15269:
15270: Will print out:
1.191 harris41 15271:
1.394 bowersj2 15272: %history{1:foo} = bar
15273: %history{1:keys} = foo:timestamp
15274: %history{1:timestamp} = 990455579
15275: %history{2:bar} = foo
15276: %history{2:foo} = notbar
15277: %history{2:keys} = foo:bar:timestamp
15278: %history{2:timestamp} = 990455580
15279: %history{bar} = foo
15280: %history{foo} = notbar
15281: %history{timestamp} = 990455580
15282: %history{version} = 2
15283:
15284: Note that the special hash entries C<keys>, C<version> and
15285: C<timestamp> were added to the hash. C<version> will be equal to the
15286: total number of versions of the data that have been stored. The
15287: C<timestamp> attribute will be the UNIX time the hash was
15288: stored. C<keys> is available in every historical section to list which
15289: keys were added or changed at a specific historical revision of a
15290: hash.
15291:
15292: B<Warning>: do not store the hash that restore returns directly. This
15293: will cause a mess since it will restore the historical keys as if the
15294: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15295:
1.394 bowersj2 15296: Calling convention:
1.191 harris41 15297:
1.1225 raeburn 15298: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15299: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15300:
1.394 bowersj2 15301: For more detailed information, see lonnet specific documentation.
1.191 harris41 15302:
1.394 bowersj2 15303: =head1 RETURN MESSAGES
1.191 harris41 15304:
1.394 bowersj2 15305: =over 4
1.191 harris41 15306:
1.394 bowersj2 15307: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15308:
1.394 bowersj2 15309: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15310: when the connection is brought back up
1.191 harris41 15311:
1.394 bowersj2 15312: =item * B<con_failed>: unable to contact remote host and unable to save message
15313: for later delivery
1.191 harris41 15314:
1.967 bisitz 15315: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15316:
1.394 bowersj2 15317: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15318: that was requested
1.191 harris41 15319:
1.243 albertel 15320: =back
1.191 harris41 15321:
1.243 albertel 15322: =head1 PUBLIC SUBROUTINES
1.191 harris41 15323:
1.243 albertel 15324: =head2 Session Environment Functions
1.191 harris41 15325:
1.243 albertel 15326: =over 4
1.191 harris41 15327:
1.394 bowersj2 15328: =item *
15329: X<appenv()>
1.949 raeburn 15330: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15331: the user envirnoment file, and will be restored for each access this
1.620 albertel 15332: user makes during this session, also modifies the %env for the current
1.949 raeburn 15333: process. Optional rolesarrayref - if defined contains a reference to an array
15334: of roles which are exempt from the restriction on modifying user.role entries
15335: in the user's environment.db and in %env.
1.191 harris41 15336:
15337: =item *
1.394 bowersj2 15338: X<delenv()>
1.987 raeburn 15339: B<delenv($delthis,$regexp)>: removes all items from the session
15340: environment file that begin with $delthis. If the
15341: optional second arg - $regexp - is true, $delthis is treated as a
15342: regular expression, otherwise \Q$delthis\E is used.
15343: The values are also deleted from the current processes %env.
1.191 harris41 15344:
1.795 albertel 15345: =item * get_env_multiple($name)
15346:
15347: gets $name from the %env hash, it seemlessly handles the cases where multiple
15348: values may be defined and end up as an array ref.
15349:
15350: returns an array of values
15351:
1.243 albertel 15352: =back
15353:
15354: =head2 User Information
1.191 harris41 15355:
1.243 albertel 15356: =over 4
1.191 harris41 15357:
15358: =item *
1.394 bowersj2 15359: X<queryauthenticate()>
15360: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15361: authentication scheme
15362:
15363: =item *
1.394 bowersj2 15364: X<authenticate()>
1.1073 raeburn 15365: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15366: authenticate user from domain's lib servers (first use the current
15367: one). C<$upass> should be the users password.
1.1073 raeburn 15368: $checkdefauth is optional (value is 1 if a check should be made to
15369: authenticate user using default authentication method, and allow
15370: account creation if username does not have account in the domain).
15371: $clientcancheckhost is optional (value is 1 if checking whether the
15372: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15373:
15374: =item *
1.394 bowersj2 15375: X<homeserver()>
15376: B<homeserver($uname,$udom)>: find the server which has
15377: the user's directory and files (there must be only one), this caches
15378: the answer, and also caches if there is a borken connection.
1.191 harris41 15379:
15380: =item *
1.394 bowersj2 15381: X<idget()>
1.1300 raeburn 15382: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15383: a list of student/employee IDs or clicker IDs
15384: (student/employee IDs are a unique resource in a domain, there must be
15385: only 1 ID per username, and only 1 username per ID in a specific domain).
15386: clickerIDs are not necessarily unique, as students might share clickers.
15387: (returns hash: id=>name,id=>name)
1.191 harris41 15388:
15389: =item *
1.394 bowersj2 15390: X<idrget()>
15391: B<idrget($udom,@unames)>: find the IDs behind a list of
15392: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15393:
15394: =item *
1.394 bowersj2 15395: X<idput()>
1.1300 raeburn 15396: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15397: names and associated student/employee IDs or clicker IDs.
15398:
15399: =item *
15400: X<iddel()>
15401: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15402: student/employee ID or clicker ID username look-ups from domain.
15403: The homeserver ($uhome) and namespace ($namespace) are optional.
15404: If no $uhome is provided, it will be determined usig &homeserver()
15405: for each user. If no $namespace is provided, the default is ids.
15406:
15407: =item *
15408: X<updateclickers()>
15409: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15410: clicker ID-to-username look-ups in clickers.db on library server.
15411: Permitted actions are add or del (i.e., add or delete). The
15412: clickers.db contains clickerID as keys (escaped), and each corresponding
15413: value is an escaped comma-separated list of usernames (for whom the
15414: library server is the homeserver), who registered that particular ID.
15415: If $critical is true, the update will be sent via &critical, otherwise
15416: &reply() will be used.
1.191 harris41 15417:
15418: =item *
1.394 bowersj2 15419: X<rolesinit()>
1.1169 droeschl 15420: B<rolesinit($udom,$username)>: get user privileges.
15421: returns user role, first access and timer interval hashes
1.243 albertel 15422:
15423: =item *
1.1171 droeschl 15424: X<privileged()>
15425: B<privileged($username,$domain)>: returns a true if user has a
15426: privileged and active role (i.e. su or dc), false otherwise.
15427:
15428: =item *
1.551 albertel 15429: X<getsection()>
15430: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15431: course $cname, return section name/number or '' for "not in course"
15432: and '-1' for "no section"
15433:
15434: =item *
1.394 bowersj2 15435: X<userenvironment()>
15436: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15437: passed in @what from the requested user's environment, returns a hash
15438:
1.858 raeburn 15439: =item *
15440: X<userlog_query()>
1.859 albertel 15441: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15442: activity.log file. %filters defines filters applied when parsing the
15443: log file. These can be start or end timestamps, or the type of action
15444: - log to look for Login or Logout events, check for Checkin or
15445: Checkout, role for role selection. The response is in the form
15446: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15447: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15448:
1.243 albertel 15449: =back
15450:
15451: =head2 User Roles
15452:
15453: =over 4
15454:
15455: =item *
15456:
1.1284 raeburn 15457: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15458: returns codes for allowed actions.
15459:
15460: The first argument is required, all others are optional.
15461:
15462: $priv is the privilege being checked.
15463: $uri contains additional information about what is being checked for access (e.g.,
15464: URL, course ID etc.).
15465: $symb is the unique resource instance identifier in a course; if needed,
15466: but not provided, it will be retrieved via a call to &symbread().
15467: $role is the role for which a priv is being checked (only used if priv is evb).
15468: $clientip is the user's IP address (only used when checking for access to portfolio
15469: files).
15470: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15471: prevents recursive calls to &allowed.
15472:
1.243 albertel 15473: F: full access
15474: U,I,K: authentication modes (cxx only)
15475: '': forbidden
15476: 1: user needs to choose course
15477: 2: browse allowed
1.766 albertel 15478: A: passphrase authentication needed
1.1284 raeburn 15479: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 15480: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15481:
15482: =item *
15483:
1.1192 raeburn 15484: constructaccess($url,$setpriv) : check for access to construction space URL
15485:
15486: See if the owner domain and name in the URL match those in the
15487: expected environment. If so, return three element list
15488: ($ownername,$ownerdomain,$ownerhome).
15489:
15490: Otherwise return the null string.
15491:
15492: If second argument 'setpriv' is true, it assigns the privileges,
15493: and returns the same three element list, unless the owner has
15494: blocked "ad hoc" Domain Coordinator access to the Author Space,
15495: in which case the null string is returned.
15496:
15497: =item *
15498:
1.1326 raeburn 15499: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15500: define a custom role rolename set privileges in format of lonTabs/roles.tab
15501: for system, domain, and course level. $uname and $udom are optional (current
15502: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15503:
15504: =item *
15505:
1.988 raeburn 15506: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15507: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15508: $type is Course (default) or Community.
1.988 raeburn 15509: If $forcedefault evaluates to true, text returned will be default
15510: text for $type. Otherwise, if this is a course, the text returned
15511: will be a custom name for the role (if defined in the course's
15512: environment). If no custom name is defined the default is returned.
15513:
1.832 raeburn 15514: =item *
15515:
1.1219 raeburn 15516: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15517: All arguments are optional. Returns a hash of a roles, either for
15518: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15519: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15520: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15521: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15522: For each key, value is set to colon-separated start and end times for
15523: the role. If no username and domain are specified, will default to
1.934 raeburn 15524: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15525: of role statuses (active, future or previous), roles
15526: (e.g., cc,in, st etc.) and domains of the roles which can be used
15527: to restrict the list of roles reported. If no array ref is
15528: provided for types, will default to return only active roles.
1.834 albertel 15529:
1.1195 raeburn 15530: =item *
15531:
15532: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 15533: user: $uname:$udom has a role in the course: $cdom_$cnum.
15534:
15535: Additional optional arguments are: $type (if role checking is to be restricted
15536: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 15537: available roles) or future (roles available in the future), and
15538: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 15539: have active Domain Coordinator role in course's domain or in additional
15540: domains (specified in 'Domains to check for privileged users' in course
15541: environment -- set via: Course Settings -> Classlists and staff listing).
15542:
15543: =item *
15544:
15545: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15546: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15547: $possdomains and $possroles are optional array refs -- to domains to check and
15548: roles to check. If $possdomains is not specified, a dump will be done of the
15549: users' roles.db to check for a dc or su role in any domain. This can be
15550: time consuming if &privileged is called repeatedly (e.g., when displaying a
15551: classlist), so in such cases, supplying a $possdomains array is preferred, as
15552: this then allows &privileged_by_domain() to be used, which caches the identity
15553: of privileged users, eliminating the need for repeated calls to &dump().
15554:
15555: =item *
15556:
15557: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15558: where the outer hash keys are domains specified in the $possdomains array ref,
15559: next inner hash keys are privileged roles specified in the $roles array ref,
15560: and the innermost hash contains key = value pairs for username:domain = end:start
15561: for active or future "privileged" users with that role in that domain. To avoid
15562: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15563: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 15564:
1.243 albertel 15565: =back
15566:
15567: =head2 User Modification
15568:
15569: =over 4
15570:
15571: =item *
15572:
1.957 raeburn 15573: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15574: user for the level given by URL. Optional start and end dates (leave empty
15575: string or zero for "no date")
1.191 harris41 15576:
15577: =item *
15578:
1.243 albertel 15579: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15580: change a users, password, possible return values are: ok,
15581: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15582: refused
1.191 harris41 15583:
15584: =item *
15585:
1.243 albertel 15586: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15587:
15588: =item *
15589:
1.1058 raeburn 15590: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15591: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15592:
15593: will update user information (firstname,middlename,lastname,generation,
15594: permanentemail), and if forceid is true, student/employee ID also.
15595: A user's institutional affiliation(s) can also be updated.
15596: User information fields will not be overwritten with empty entries
15597: unless the field is included in the $candelete array reference.
15598: This array is included when a single user is modified via "Manage Users",
15599: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15600:
15601: =item *
15602:
1.286 matthew 15603: modifystudent
15604:
1.957 raeburn 15605: modify a student's enrollment and identification information.
1.1235 raeburn 15606: The course id is resolved based on the current user's environment.
15607: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15608: associated with a course.
15609:
1.297 matthew 15610: This call is essentially a wrapper for lonnet::modifyuser and
15611: lonnet::modify_student_enrollment
1.286 matthew 15612:
15613: Inputs:
15614:
15615: =over 4
15616:
1.957 raeburn 15617: =item B<$udom> Student's loncapa domain
1.286 matthew 15618:
1.957 raeburn 15619: =item B<$uname> Student's loncapa login name
1.286 matthew 15620:
1.964 bisitz 15621: =item B<$uid> Student/Employee ID
1.286 matthew 15622:
1.957 raeburn 15623: =item B<$umode> Student's authentication mode
1.286 matthew 15624:
1.957 raeburn 15625: =item B<$upass> Student's password
1.286 matthew 15626:
1.957 raeburn 15627: =item B<$first> Student's first name
1.286 matthew 15628:
1.957 raeburn 15629: =item B<$middle> Student's middle name
1.286 matthew 15630:
1.957 raeburn 15631: =item B<$last> Student's last name
1.286 matthew 15632:
1.957 raeburn 15633: =item B<$gene> Student's generation
1.286 matthew 15634:
1.957 raeburn 15635: =item B<$usec> Student's section in course
1.286 matthew 15636:
15637: =item B<$end> Unix time of the roles expiration
15638:
15639: =item B<$start> Unix time of the roles start date
15640:
15641: =item B<$forceid> If defined, allow $uid to be changed
15642:
15643: =item B<$desiredhome> server to use as home server for student
15644:
1.957 raeburn 15645: =item B<$email> Student's permanent e-mail address
15646:
15647: =item B<$type> Type of enrollment (auto or manual)
15648:
1.963 raeburn 15649: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15650:
15651: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15652:
1.963 raeburn 15653: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15654:
1.963 raeburn 15655: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15656:
1.1216 raeburn 15657: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15658:
15659: =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 15660:
1.286 matthew 15661: =back
1.297 matthew 15662:
15663: =item *
15664:
15665: modify_student_enrollment
15666:
1.1235 raeburn 15667: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15668: 'role.request.course' must be defined for this function to proceed.
15669:
15670: Inputs:
15671:
15672: =over 4
15673:
1.1235 raeburn 15674: =item $udom, student's domain
1.297 matthew 15675:
1.1235 raeburn 15676: =item $uname, student's name
1.297 matthew 15677:
1.1235 raeburn 15678: =item $uid, student's user id
1.297 matthew 15679:
1.1235 raeburn 15680: =item $first, student's first name
1.297 matthew 15681:
15682: =item $middle
15683:
15684: =item $last
15685:
15686: =item $gene
15687:
15688: =item $usec
15689:
15690: =item $end
15691:
15692: =item $start
15693:
1.957 raeburn 15694: =item $type
15695:
15696: =item $locktype
15697:
15698: =item $cid
15699:
15700: =item $selfenroll
15701:
15702: =item $context
15703:
1.1216 raeburn 15704: =item $credits, number of credits student will earn from this class
15705:
1.1314 raeburn 15706: =item $instsec, institutional course section code for student
15707:
1.297 matthew 15708: =back
15709:
1.191 harris41 15710:
15711: =item *
15712:
1.243 albertel 15713: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15714: custom role; give a custom role to a user for the level given by URL. Specify
15715: name and domain of role author, and role name
1.191 harris41 15716:
15717: =item *
15718:
1.243 albertel 15719: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15720:
15721: =item *
15722:
1.243 albertel 15723: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15724:
15725: =back
15726:
15727: =head2 Course Infomation
15728:
15729: =over 4
1.191 harris41 15730:
15731: =item *
15732:
1.1118 foxr 15733: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15734: specified course id, including all environment settings for the
15735: course, the description of the course will be in the hash under the
15736: key 'description'
1.191 harris41 15737:
1.1118 foxr 15738: $options is an optional parameter that if supplied is a hash reference that controls
15739: what how this function works. It has the following key/values:
15740:
15741: =over 4
15742:
15743: =item freshen_cache
15744:
15745: If defined, and the environment cache for the course is valid, it is
15746: returned in the returned hash.
15747:
15748: =item one_time
15749:
15750: If defined, the last cache time is set to _now_
15751:
15752: =item user
15753:
15754: If defined, the supplied username is used instead of the current user.
15755:
15756:
15757: =back
15758:
1.191 harris41 15759: =item *
15760:
1.624 albertel 15761: resdata($name,$domain,$type,@which) : request for current parameter
15762: setting for a specific $type, where $type is either 'course' or 'user',
15763: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 15764: answers for 10 minutes.
1.243 albertel 15765:
1.877 foxr 15766: =item *
15767:
15768: get_courseresdata($courseid, $domain) : dump the entire course resource
15769: data base, returning a hash that is keyed by the resource name and has
15770: values that are the resource value. I believe that the timestamps and
15771: versions are also returned.
15772:
1.1236 raeburn 15773: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15774: supplemental content area. This routine caches the number of files for
15775: 10 minutes.
15776:
1.243 albertel 15777: =back
15778:
15779: =head2 Course Modification
15780:
15781: =over 4
1.191 harris41 15782:
15783: =item *
15784:
1.243 albertel 15785: writecoursepref($courseid,%prefs) : write preferences (environment
15786: database) for a course
1.191 harris41 15787:
15788: =item *
15789:
1.1011 raeburn 15790: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15791:
15792: =item *
15793:
1.1038 raeburn 15794: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15795:
1.1167 droeschl 15796: =item *
15797:
15798: is_course($courseid), is_course($cdom, $cnum)
15799:
15800: Accepts either a combined $courseid (in the form of domain_courseid) or the
15801: two component version $cdom, $cnum. It checks if the specified course exists.
15802:
15803: Returns:
15804: undef if the course doesn't exist, otherwise
15805: in scalar context the combined courseid.
15806: in list context the two components of the course identifier, domain and
15807: courseid.
15808:
1.243 albertel 15809: =back
15810:
1.1401 raeburn 15811: =head2 Bubblesheet Configuration
15812:
15813: =over 4
15814:
15815: =item *
15816:
15817: get_scantron_config($which)
15818:
15819: $which - the name of the configuration to parse from the file.
15820:
15821: Parses and returns the bubblesheet configuration line selected as a
15822: hash of configuration file fields.
15823:
15824:
15825: Returns:
15826: If the named configuration is not in the file, an empty
15827: hash is returned.
15828:
15829: a hash with the fields
15830: name - internal name for the this configuration setup
15831: description - text to display to operator that describes this config
15832: CODElocation - if 0 or the string 'none'
15833: - no CODE exists for this config
15834: if -1 || the string 'letter'
15835: - a CODE exists for this config and is
15836: a string of letters
15837: Unsupported value (but planned for future support)
15838: if a positive integer
15839: - The CODE exists as the first n items from
15840: the question section of the form
15841: if the string 'number'
15842: - The CODE exists for this config and is
15843: a string of numbers
15844: CODEstart - (only matter if a CODE exists) column in the line where
15845: the CODE starts
15846: CODElength - length of the CODE
15847: IDstart - column where the student/employee ID starts
15848: IDlength - length of the student/employee ID info
15849: Qstart - column where the information from the bubbled
15850: 'questions' start
15851: Qlength - number of columns comprising a single bubble line from
15852: the sheet. (usually either 1 or 10)
15853: Qon - either a single character representing the character used
15854: to signal a bubble was chosen in the positional setup, or
15855: the string 'letter' if the letter of the chosen bubble is
15856: in the final, or 'number' if a number representing the
15857: chosen bubble is in the file (1->A 0->J)
15858: Qoff - the character used to represent that a bubble was
15859: left blank
15860: PaperID - if the scanning process generates a unique number for each
15861: sheet scanned the column that this ID number starts in
15862: PaperIDlength - number of columns that comprise the unique ID number
15863: for the sheet of paper
15864: FirstName - column that the first name starts in
15865: FirstNameLength - number of columns that the first name spans
15866: LastName - column that the last name starts in
15867: LastNameLength - number of columns that the last name spans
15868: BubblesPerRow - number of bubbles available in each row used to
15869: bubble an answer. (If not specified, 10 assumed).
15870:
15871:
15872: =item *
15873:
15874: get_scantronformat_file($cdom)
15875:
15876: $cdom - the course's domain (optional); if not supplied, uses
15877: domain for current $env{'request.course.id'}.
15878:
15879: Returns an array containing lines from the scantron format file for
15880: the domain of the course.
15881:
15882: If a url for a custom.tab file is listed in domain's configuration.db,
15883: lines are from this file.
15884:
15885: Otherwise, if a default.tab has been published in RES space by the
15886: domainconfig user, lines are from this file.
15887:
15888: Otherwise, fall back to getting lines from the legacy file on the
15889: local server: /home/httpd/lonTabs/default_scantronformat.tab
15890:
15891: =back
15892:
1.243 albertel 15893: =head2 Resource Subroutines
15894:
15895: =over 4
1.191 harris41 15896:
15897: =item *
15898:
1.243 albertel 15899: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15900:
15901: =item *
15902:
1.243 albertel 15903: repcopy($filename) : subscribes to the requested file, and attempts to
15904: replicate from the owning library server, Might return
1.607 raeburn 15905: 'unavailable', 'not_found', 'forbidden', 'ok', or
15906: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15907: resource. Expects the local filesystem pathname
15908: (/home/httpd/html/res/....)
15909:
15910: =back
15911:
15912: =head2 Resource Information
15913:
15914: =over 4
1.191 harris41 15915:
15916: =item *
15917:
1.1228 raeburn 15918: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15919: and returns the value of a variety of different possible values,
15920: $varname should be a request string, and the other parameters can be
15921: used to specify who and what one is asking about. Ordinarily, $cid
15922: does not need to be specified, as it is retrived from
15923: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15924: within lonuserstate::loadmap() when initializing a course, before
15925: $env{'request.course.id'} has been set, so it needs to be provided
15926: in that one case.
1.243 albertel 15927:
15928: Possible values for $varname are environment.lastname (or other item
15929: from the envirnment hash), user.name (or someother aspect about the
15930: user), resource.0.maxtries (or some other part and parameter of a
15931: resource)
1.204 albertel 15932:
15933: =item *
15934:
1.243 albertel 15935: directcondval($number) : get current value of a condition; reads from a state
15936: string
1.204 albertel 15937:
15938: =item *
15939:
1.243 albertel 15940: condval($condidx) : value of condition index based on state
1.204 albertel 15941:
15942: =item *
15943:
1.1362 raeburn 15944: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 15945: resource's metadata, $what should be either a specific key, or either
15946: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 15947: packages that this resource currently uses, the last 3 arguments are
15948: only used internally for recursive metadata.
15949:
15950: the toolsymb is only used where the uri is for an external tool (for which
15951: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 15952:
1.1371 raeburn 15953: this function automatically caches all requests except any made recursively
15954: to retrieve a list of metadata keys for an imported library file ($liburi is
15955: defined).
1.191 harris41 15956:
15957: =item *
15958:
1.243 albertel 15959: metadata_query($query,$custom,$customshow) : make a metadata query against the
15960: network of library servers; returns file handle of where SQL and regex results
15961: will be stored for query
1.191 harris41 15962:
15963: =item *
15964:
1.1282 raeburn 15965: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15966: return symbolic list entry (all arguments optional).
15967:
15968: Args: filename is the filename (including path) for the file for which a symb
15969: is required; donotrecurse, if true will prevent calls to allowed() being made
15970: to check access status if more than one resource was found in the bighash
15971: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15972: a randompick); ignorecachednull, if true will prevent a symb of '' being
15973: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15974: cause possible symbs to be checked to determine if they are subject to content
15975: blocking, if so they will not be included as possible symbs; possibles is a
15976: ref to a hash, which, as a side effect, will be populated with all possible
15977: symbs (content blocking not tested).
15978:
1.243 albertel 15979: returns the data handle
1.191 harris41 15980:
15981: =item *
15982:
1.1190 raeburn 15983: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15984: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15985: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 15986: on failure, user must be in a course, as it assumes the existence of
15987: the course initial hash, and uses $env('request.course.id'}. The third
15988: arg is an optional reference to a scalar. If this arg is passed in the
15989: call to symbverify, it will be set to 1 if the symb has been set to be
15990: encrypted; otherwise it will be null.
1.191 harris41 15991:
15992: =item *
15993:
1.243 albertel 15994: symbclean($symb) : removes versions numbers from a symb, returns the
15995: cleaned symb
1.191 harris41 15996:
15997: =item *
15998:
1.243 albertel 15999: is_on_map($uri) : checks if the $uri is somewhere on the current
16000: course map, user must be in a course for it to work.
1.191 harris41 16001:
16002: =item *
16003:
1.243 albertel 16004: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16005:
16006: =item *
16007:
1.243 albertel 16008: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16009: a random seed, all arguments are optional, if they aren't sent it uses the
16010: environment to derive them. Note: if symb isn't sent and it can't get one
16011: from &symbread it will use the current time as its return value
1.191 harris41 16012:
16013: =item *
16014:
1.243 albertel 16015: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16016: unfakeable, receipt
1.191 harris41 16017:
16018: =item *
16019:
1.620 albertel 16020: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16021:
16022: =item *
16023:
1.243 albertel 16024: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16025:
16026: =item *
16027:
1.243 albertel 16028: 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 16029:
16030: =item *
16031:
1.243 albertel 16032: 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 16033:
16034: =item *
16035:
1.243 albertel 16036: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16037:
16038: =item *
16039:
1.243 albertel 16040: devalidate($symb) : devalidate temporary spreadsheet calculations,
16041: forcing spreadsheet to reevaluate the resource scores next time.
16042:
1.1195 raeburn 16043: =item *
16044:
1.1196 raeburn 16045: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16046: when viewing in course context.
1.1195 raeburn 16047:
1.1196 raeburn 16048: input: six args -- filename (decluttered), course number, course domain,
16049: url, symb (if registered) and group (if this is a
16050: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16051:
1.1196 raeburn 16052: output: array of five scalars --
1.1195 raeburn 16053: $cfile -- url for file editing if editable on current server
16054: $home -- homeserver of resource (i.e., for author if published,
16055: or course if uploaded.).
16056: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16057: $forceedit -- 1 if icon/link should be to go to edit mode
16058: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16059:
16060: =item *
16061:
16062: is_course_upload($file,$cnum,$cdom)
16063:
16064: Used in course context to determine if current file was uploaded to
16065: the course (i.e., would be found in /userfiles/docs on the course's
16066: homeserver.
16067:
16068: input: 3 args -- filename (decluttered), course number and course domain.
16069: output: boolean -- 1 if file was uploaded.
16070:
1.243 albertel 16071: =back
16072:
16073: =head2 Storing/Retreiving Data
16074:
16075: =over 4
1.191 harris41 16076:
16077: =item *
16078:
1.1269 raeburn 16079: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16080: permanently for this url; hashref needs to be given and should be a \%hashname;
16081: the remaining args aren't required and if they aren't passed or are '' they will
16082: be derived from the env (with the exception of $laststore, which is an
16083: optional arg used when a user's submission is stored in grading).
16084: $laststore is $version=$timestamp, where $version is the most recent version
16085: number retrieved for the corresponding $symb in the $namespace db file, and
16086: $timestamp is the timestamp for that transaction (UNIX time).
16087: $laststore is currently only passed when cstore() is called by
16088: structuretags::finalize_storage().
1.191 harris41 16089:
16090: =item *
16091:
1.1269 raeburn 16092: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16093: but uses critical subroutine
1.191 harris41 16094:
16095: =item *
16096:
1.243 albertel 16097: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16098: all args are optional
1.191 harris41 16099:
16100: =item *
16101:
1.717 albertel 16102: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16103: dumps the complete (or key matching regexp) namespace into a hash
16104: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16105: normally &store()ed into
16106:
16107: $range should be either an integer '100' (give me the first 100
16108: matching records)
16109: or be two integers sperated by a - with no spaces
16110: '30-50' (give me the 30th through the 50th matching
16111: records)
16112:
16113:
16114: =item *
16115:
1.1269 raeburn 16116: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16117: replaces a &store() version of data with a replacement set of data
16118: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16119: reference. If $tolog is true, the transaction is logged in the courselog
16120: with an action=PUTSTORE.
1.717 albertel 16121:
16122: =item *
16123:
1.243 albertel 16124: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16125: works very similar to store/cstore, but all data is stored in a
16126: temporary location and can be reset using tmpreset, $storehash should
16127: be a hash reference, returns nothing on success
1.191 harris41 16128:
16129: =item *
16130:
1.243 albertel 16131: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16132: similar to restore, but all data is stored in a temporary location and
16133: can be reset using tmpreset. Returns a hash of values on success,
16134: error string otherwise.
1.191 harris41 16135:
16136: =item *
16137:
1.243 albertel 16138: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16139: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16140:
16141: =item *
16142:
1.243 albertel 16143: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16144: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16145:
16146: =item *
16147:
1.243 albertel 16148: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16149: namesp ($udom and $uname are optional)
1.191 harris41 16150:
16151: =item *
16152:
1.702 albertel 16153: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16154: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16155: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16156:
1.702 albertel 16157: $range should be either an integer '100' (give me the first 100
16158: matching records)
16159: or be two integers sperated by a - with no spaces
16160: '30-50' (give me the 30th through the 50th matching
16161: records)
1.449 matthew 16162: =item *
16163:
16164: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16165: $store can be a scalar, an array reference, or if the amount to be
16166: incremented is > 1, a hash reference.
16167:
16168: ($udom and $uname are optional)
1.191 harris41 16169:
16170: =item *
16171:
1.243 albertel 16172: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16173: ($udom and $uname are optional)
1.191 harris41 16174:
16175: =item *
16176:
1.243 albertel 16177: cput($namespace,$storehash,$udom,$uname) : critical put
16178: ($udom and $uname are optional)
1.191 harris41 16179:
16180: =item *
16181:
1.748 albertel 16182: newput($namespace,$storehash,$udom,$uname) :
16183:
16184: Attempts to store the items in the $storehash, but only if they don't
16185: currently exist, if this succeeds you can be certain that you have
16186: successfully created a new key value pair in the $namespace db.
16187:
16188:
16189: Args:
16190: $namespace: name of database to store values to
16191: $storehash: hashref to store to the db
16192: $udom: (optional) domain of user containing the db
16193: $uname: (optional) name of user caontaining the db
16194:
16195: Returns:
16196: 'ok' -> succeeded in storing all keys of $storehash
16197: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16198: least <key> already existed in the db (other
16199: requested keys may also already exist)
1.967 bisitz 16200: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16201: 'con_lost' -> unable to contact request server
16202: 'refused' -> action was not allowed by remote machine
16203:
16204:
16205: =item *
16206:
1.243 albertel 16207: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16208: reference filled in from namesp (encrypts the return communication)
16209: ($udom and $uname are optional)
1.191 harris41 16210:
16211: =item *
16212:
1.243 albertel 16213: log($udom,$name,$home,$message) : write to permanent log for user; use
16214: critical subroutine
16215:
1.806 raeburn 16216: =item *
16217:
1.860 raeburn 16218: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16219: array reference filled in from namespace found in domain level on either
16220: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16221:
16222: =item *
16223:
1.860 raeburn 16224: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16225: domain level either on specified domain server ($uhome) or primary domain
16226: server ($udom and $uhome are optional)
1.806 raeburn 16227:
1.943 raeburn 16228: =item *
16229:
1.1240 raeburn 16230: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16231: for: authentication, language, quotas, timezone, date locale, and portal URL in
16232: the target domain.
16233:
16234: May also include additional key => value pairs for the following groups:
16235:
16236: =over
16237:
16238: =item
16239: disk quotas (MB allocated by default to portfolios and authoring spaces).
16240:
16241: =over
16242:
16243: =item defaultquota, authorquota
16244:
16245: =back
16246:
16247: =item
16248: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16249: portfolio for users).
16250:
16251: =over
16252:
16253: =item
16254: aboutme, blog, webdav, portfolio
16255:
16256: =back
16257:
16258: =item
16259: requestcourses: ability to request courses, and how requests are processed.
16260:
16261: =over
16262:
16263: =item
1.1305 raeburn 16264: official, unofficial, community, textbook, placement
1.1240 raeburn 16265:
16266: =back
16267:
16268: =item
16269: inststatus: types of institutional affiliation, and order in which they are displayed.
16270:
16271: =over
16272:
16273: =item
1.1256 raeburn 16274: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 16275:
16276: =back
16277:
16278: =item
16279: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16280: for course's uploaded content.
16281:
16282: =over
16283:
16284: =item
1.1246 raeburn 16285: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16286: communityquota, textbookquota, placementquota
1.1240 raeburn 16287:
16288: =back
16289:
16290: =item
16291: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16292: on your servers.
16293:
16294: =over
16295:
16296: =item
16297: remotesessions, hostedsessions
16298:
16299: =back
16300:
16301: =back
16302:
16303: In cases where a domain coordinator has never used the "Set Domain Configuration"
16304: utility to create a configuration.db file on a domain's primary library server
16305: only the following domain defaults: auth_def, auth_arg_def, lang_def
16306: -- corresponding values are authentication type (internal, krb4, krb5,
16307: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16308: will be available. Values are retrieved from cache (if current), unless the
16309: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16310: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16311:
16312: Typical usage:
1.943 raeburn 16313:
1.1240 raeburn 16314: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16315:
1.243 albertel 16316: =back
16317:
16318: =head2 Network Status Functions
16319:
16320: =over 4
1.191 harris41 16321:
16322: =item *
16323:
1.1137 raeburn 16324: dirlist() : return directory list based on URI (first arg).
16325:
16326: Inputs: 1 required, 5 optional.
16327:
16328: =over
16329:
16330: =item
16331: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16332:
16333: =item
16334: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16335:
16336: =item
16337: $username - username of user/course to be listed. Extracted from $uri if absent.
16338:
16339: =item
16340: $getpropath - boolean: 1 if prepend path using &propath().
16341:
16342: =item
16343: $getuserdir - boolean: 1 if prepend path for "userfiles".
16344:
16345: =item
16346: $alternateRoot - path to prepend in place of path from $uri.
16347:
16348: =back
16349:
16350: Returns: Array of up to two items.
16351:
16352: =over
16353:
16354: a reference to an array of files/subdirectories
16355:
16356: =over
16357:
16358: Each element in the array of files/subdirectories is a & separated list of
16359: item name and the result of running stat on the item. If dirlist was requested
16360: for a file instead of a directory, the item name will be ''. For a directory
16361: listing, if the item is a metadata file, the element will end &N&M
16362: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16363: default copyright set (1).
16364:
16365: =back
16366:
16367: a scalar containing error condition (if encountered).
16368:
16369: =over
16370:
16371: =item
16372: no_host (no homeserver identified for $username:$domain).
16373:
16374: =item
16375: no_such_host (server contacted for listing not identified as valid host).
16376:
16377: =item
16378: con_lost (connection to remote server failed).
16379:
16380: =item
16381: refused (invalid $username:$domain received on lond side).
16382:
16383: =item
16384: no_such_dir (directory at specified path on lond side does not exist).
16385:
16386: =item
16387: empty (directory at specified path on lond side is empty).
16388:
16389: =over
16390:
16391: This is currently not encountered because the &ls3, &ls2,
16392: &ls (_handler) routines on the lond side do not filter out
16393: . and .. from a directory listing.
16394:
16395: =back
16396:
16397: =back
16398:
16399: =back
1.191 harris41 16400:
16401: =item *
16402:
1.243 albertel 16403: spareserver() : find server with least workload from spare.tab
16404:
1.986 foxr 16405:
16406: =item *
16407:
16408: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16409: if there is no corresponding loncapa host.
16410:
1.243 albertel 16411: =back
16412:
1.986 foxr 16413:
1.243 albertel 16414: =head2 Apache Request
16415:
16416: =over 4
1.191 harris41 16417:
16418: =item *
16419:
1.243 albertel 16420: ssi($url,%hash) : server side include, does a complete request cycle on url to
16421: localhost, posts hash
16422:
16423: =back
16424:
16425: =head2 Data to String to Data
16426:
16427: =over 4
1.191 harris41 16428:
16429: =item *
16430:
1.243 albertel 16431: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16432: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16433:
16434: =item *
16435:
1.243 albertel 16436: hashref2str($hashref) : convert a hashref into a string complete with
16437: escaping and '=' and '&' separators, supports elements that are
16438: arrayrefs and hashrefs
1.191 harris41 16439:
16440: =item *
16441:
1.243 albertel 16442: arrayref2str($arrayref) : convert an arrayref into a string complete
16443: with escaping and '&' separators, supports elements that are arrayrefs
16444: and hashrefs
1.191 harris41 16445:
16446: =item *
16447:
1.243 albertel 16448: str2hash($string) : convert string to hash using unescaping and
16449: splitting on '=' and '&', supports elements that are arrayrefs and
16450: hashrefs
1.191 harris41 16451:
16452: =item *
16453:
1.243 albertel 16454: str2array($string) : convert string to hash using unescaping and
16455: splitting on '&', supports elements that are arrayrefs and hashrefs
16456:
16457: =back
16458:
16459: =head2 Logging Routines
16460:
16461:
16462: These routines allow one to make log messages in the lonnet.log and
16463: lonnet.perm logfiles.
1.191 harris41 16464:
1.1119 foxr 16465: =over 4
16466:
1.191 harris41 16467: =item *
16468:
1.243 albertel 16469: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16470:
16471: =item *
16472:
1.243 albertel 16473: logthis() : append message to the normal lonnet.log file, it gets
16474: preiodically rolled over and deleted.
1.191 harris41 16475:
16476: =item *
16477:
1.243 albertel 16478: logperm() : append a permanent message to lonnet.perm.log, this log
16479: file never gets deleted by any automated portion of the system, only
16480: messages of critical importance should go in here.
16481:
1.1119 foxr 16482:
1.243 albertel 16483: =back
16484:
16485: =head2 General File Helper Routines
16486:
16487: =over 4
1.191 harris41 16488:
16489: =item *
16490:
1.481 raeburn 16491: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16492: (a) files in /uploaded
16493: (i) If a local copy of the file exists -
16494: compares modification date of local copy with last-modified date for
16495: definitive version stored on home server for course. If local copy is
16496: stale, requests a new version from the home server and stores it.
16497: If the original has been removed from the home server, then local copy
16498: is unlinked.
16499: (ii) If local copy does not exist -
16500: requests the file from the home server and stores it.
16501:
16502: If $caller is 'uploadrep':
16503: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16504: for request for files originally uploaded via DOCS.
16505: - returns 'ok' if fresh local copy now available, -1 otherwise.
16506:
16507: Otherwise:
16508: This indicates a call from the content generation phase of the request.
16509: - returns the entire contents of the file or -1.
16510:
16511: (b) files in /res
16512: - returns the entire contents of a file or -1;
16513: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16514:
1.712 albertel 16515:
16516: =item *
16517:
16518: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16519: reference
16520:
16521: returns either a stat() list of data about the file or an empty list
16522: if the file doesn't exist or couldn't find out about it (connection
16523: problems or user unknown)
16524:
1.191 harris41 16525: =item *
16526:
1.243 albertel 16527: filelocation($dir,$file) : returns file system location of a file
16528: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16529: directory that relative $file lookups are to looked in ($dir of /a/dir
16530: and a file of ../bob will become /a/bob)
1.191 harris41 16531:
16532: =item *
16533:
16534: hreflocation($dir,$file) : returns file system location or a URL; same as
16535: filelocation except for hrefs
16536:
16537: =item *
16538:
1.1261 raeburn 16539: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16540: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16541:
1.243 albertel 16542: =back
16543:
1.608 albertel 16544: =head2 Usererfile file routines (/uploaded*)
16545:
16546: =over 4
16547:
16548: =item *
16549:
16550: userfileupload(): main rotine for putting a file in a user or course's
16551: filespace, arguments are,
16552:
1.620 albertel 16553: formname - required - this is the name of the element in $env where the
1.608 albertel 16554: filename, and the contents of the file to create/modifed exist
1.620 albertel 16555: the filename is in $env{'form.'.$formname.'.filename'} and the
16556: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16557: context - if coursedoc, store the file in the course of the active role
16558: of the current user;
16559: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16560: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16561: subdir - required - subdirectory to put the file in under ../userfiles/
16562: if undefined, it will be placed in "unknown"
16563:
16564: (This routine calls clean_filename() to remove any dangerous
16565: characters from the filename, and then calls finuserfileupload() to
16566: complete the transaction)
16567:
16568: returns either the url of the uploaded file (/uploaded/....) if successful
16569: and /adm/notfound.html if unsuccessful
16570:
16571: =item *
16572:
16573: clean_filename(): routine for cleaing a filename up for storage in
16574: userfile space, argument is:
16575:
16576: filename - proposed filename
16577:
16578: returns: the new clean filename
16579:
16580: =item *
16581:
1.1090 raeburn 16582: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16583: userspace, probably shouldn't be called directly
16584:
16585: docuname: username or courseid of destination for the file
16586: docudom: domain of user/course of destination for the file
16587: formname: same as for userfileupload()
1.1090 raeburn 16588: fname: filename (including subdirectories) for the file
16589: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 16590: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16591: allfiles: reference to hash used to store objects found by parser
16592: codebase: reference to hash used for codebases of java objects found by parser
16593: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16594: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16595: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16596: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16597: context: if 'overwrite', will move the uploaded file from its temporary location to
16598: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16599: mimetype: reference to scalar to accommodate mime type determined
16600: from File::MMagic if $parser = parse.
1.608 albertel 16601:
16602: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16603: and /adm/notfound.html if unsuccessful (or an error message if context
16604: was 'overwrite').
16605:
1.608 albertel 16606:
16607: =item *
16608:
16609: renameuserfile(): renames an existing userfile to a new name
16610:
16611: Args:
16612: docuname: username or courseid of destination for the file
16613: docudom: domain of user/course of destination for the file
16614: old: current file name (including any subdirs under userfiles)
16615: new: desired file name (including any subdirs under userfiles)
16616:
16617: =item *
16618:
16619: mkdiruserfile(): creates a directory is a userfiles dir
16620:
16621: Args:
16622: docuname: username or courseid of destination for the file
16623: docudom: domain of user/course of destination for the file
16624: dir: dir to create (including any subdirs under userfiles)
16625:
16626: =item *
16627:
16628: removeuserfile(): removes a file that exists in userfiles
16629:
16630: Args:
16631: docuname: username or courseid of destination for the file
16632: docudom: domain of user/course of destination for the file
16633: fname: filname to delete (including any subdirs under userfiles)
16634:
16635: =item *
16636:
16637: removeuploadedurl(): convience function for removeuserfile()
16638:
16639: Args:
16640: url: a full /uploaded/... url to delete
16641:
1.747 albertel 16642: =item *
16643:
16644: get_portfile_permissions():
16645: Args:
16646: domain: domain of user or course contain the portfolio files
16647: user: name of user or num of course contain the portfolio files
16648: Returns:
16649: hashref of a dump of the proper file_permissions.db
16650:
16651:
16652: =item *
16653:
16654: get_access_controls():
16655:
16656: Args:
16657: current_permissions: the hash ref returned from get_portfile_permissions()
16658: group: (optional) the group you want the files associated with
16659: file: (optional) the file you want access info on
16660:
16661: Returns:
1.749 raeburn 16662: a hash (keys are file names) of hashes containing
16663: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16664: values are XML containing access control settings (see below)
1.747 albertel 16665:
16666: Internal notes:
16667:
1.749 raeburn 16668: access controls are stored in file_permissions.db as key=value pairs.
16669: key -> path to file/file_name\0uniqueID:scope_end_start
16670: where scope -> public,guest,course,group,domains or users.
16671: end -> UNIX time for end of access (0 -> no end date)
16672: start -> UNIX time for start of access
16673:
16674: value -> XML description of access control
16675: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16676: <start></start>
16677: <end></end>
16678:
16679: <password></password> for scope type = guest
16680:
16681: <domain></domain> for scope type = course or group
16682: <number></number>
16683: <roles id="">
16684: <role></role>
16685: <access></access>
16686: <section></section>
16687: <group></group>
16688: </roles>
16689:
16690: <dom></dom> for scope type = domains
16691:
16692: <users> for scope type = users
16693: <user>
16694: <uname></uname>
16695: <udom></udom>
16696: </user>
16697: </users>
16698: </scope>
16699:
16700: Access data is also aggregated for each file in an additional key=value pair:
16701: key -> path to file/file_name\0accesscontrol
16702: value -> reference to hash
16703: hash contains key = value pairs
16704: where key = uniqueID:scope_end_start
16705: value = UNIX time record was last updated
16706:
16707: Used to improve speed of look-ups of access controls for each file.
16708:
16709: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16710:
1.1198 raeburn 16711: =item *
16712:
1.749 raeburn 16713: modify_access_controls():
16714:
16715: Modifies access controls for a portfolio file
16716: Args
16717: 1. file name
16718: 2. reference to hash of required changes,
16719: 3. domain
16720: 4. username
16721: where domain,username are the domain of the portfolio owner
16722: (either a user or a course)
16723:
16724: Returns:
16725: 1. result of additions or updates ('ok' or 'error', with error message).
16726: 2. result of deletions ('ok' or 'error', with error message).
16727: 3. reference to hash of any new or updated access controls.
16728: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16729: key = integer (inbound ID)
1.1198 raeburn 16730: value = uniqueID
16731:
16732: =item *
16733:
16734: get_timebased_id():
16735:
16736: Attempts to get a unique timestamp-based suffix for use with items added to a
16737: course via the Course Editor (e.g., folders, composite pages,
16738: group bulletin boards).
16739:
16740: Args: (first three required; six others optional)
16741:
16742: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16743: docssequence, or name of group
16744:
16745: 2. keyid (alphanumeric): name of temporary locking key in hash,
16746: e.g., num, boardids
16747:
16748: 3. namespace: name of gdbm file used to store suffixes already assigned;
16749: file will be named nohist_namespace.db
16750:
16751: 4. cdom: domain of course; default is current course domain from %env
16752:
16753: 5. cnum: course number; default is current course number from %env
16754:
16755: 6. idtype: set to concat if an additional digit is to be appended to the
16756: unix timestamp to form the suffix, if the plain timestamp is already
16757: in use. Default is to not do this, but simply increment the unix
16758: timestamp by 1 until a unique key is obtained.
16759:
16760: 7. who: holder of locking key; defaults to user:domain for user.
16761:
16762: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16763: retrying); default is 3.
16764:
16765: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16766:
16767: Returns:
16768:
16769: 1. suffix obtained (numeric)
16770:
16771: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16772:
16773: 3. error: contains (localized) error message if an error occurred.
16774:
1.747 albertel 16775:
1.608 albertel 16776: =back
16777:
1.243 albertel 16778: =head2 HTTP Helper Routines
16779:
16780: =over 4
16781:
1.191 harris41 16782: =item *
16783:
16784: escape() : unpack non-word characters into CGI-compatible hex codes
16785:
16786: =item *
16787:
16788: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16789:
1.243 albertel 16790: =back
16791:
16792: =head1 PRIVATE SUBROUTINES
16793:
16794: =head2 Underlying communication routines (Shouldn't call)
16795:
16796: =over 4
16797:
16798: =item *
16799:
16800: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16801:
16802: =item *
16803:
16804: reply() : uses subreply to send a message to remote machine, logs all failures
16805:
16806: =item *
16807:
16808: critical() : passes a critical message to another server; if cannot
16809: get through then place message in connection buffer directory and
16810: returns con_delayed, if incapable of saving message, returns
16811: con_failed
16812:
16813: =item *
16814:
16815: reconlonc() : tries to reconnect lonc client processes.
16816:
16817: =back
16818:
16819: =head2 Resource Access Logging
16820:
16821: =over 4
16822:
16823: =item *
16824:
16825: flushcourselogs() : flush (save) buffer logs and access logs
16826:
16827: =item *
16828:
16829: courselog($what) : save message for course in hash
16830:
16831: =item *
16832:
16833: courseacclog($what) : save message for course using &courselog(). Perform
16834: special processing for specific resource types (problems, exams, quizzes, etc).
16835:
1.191 harris41 16836: =item *
16837:
16838: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16839: as a PerlChildExitHandler
1.243 albertel 16840:
16841: =back
16842:
16843: =head2 Other
16844:
16845: =over 4
16846:
16847: =item *
16848:
16849: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16850:
16851: =back
16852:
16853: =cut
1.877 foxr 16854:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>