Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1420
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1420 ! raeburn 4: # $Id: lonnet.pm,v 1.1419 2020/03/03 01:16:39 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:
1153: sub delbalcookie {
1154: my ($cookie,$balancer) =@_;
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("delbalcookie:$cookie",$balancer);
1163: }
1164: }
1165: }
1166:
1.914 albertel 1167: # -------------------------------- ask if server already has a session for user
1168: sub has_user_session {
1169: my ($lonid,$udom,$uname) = @_;
1170: my $result = &reply(join(':','userhassession',
1171: map {&escape($_)} ($udom,$uname)),$lonid);
1172: return 1 if ($result eq 'ok');
1173:
1174: return 0;
1175: }
1176:
1.1076 raeburn 1177: # --------- determine least loaded server in a user's domain which allows login
1178:
1179: sub choose_server {
1.1259 raeburn 1180: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1181: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1182: my %servers = &get_servers($udom);
1.1076 raeburn 1183: my $lowest_load = 30000;
1.1259 raeburn 1184: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1185: if ($skiploadbal) {
1186: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1187: unless (defined($cached)) {
1188: my $cachetime = 60*60*24;
1189: my %domconfig =
1190: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1191: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1192: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1193: $cachetime);
1194: }
1195: }
1196: }
1.1076 raeburn 1197: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1198: if ($skiploadbal) {
1199: if (ref($balancers) eq 'HASH') {
1200: next if (exists($balancers->{$lonhost}));
1201: }
1.1389 raeburn 1202: }
1.1115 raeburn 1203: my $loginvia;
1204: if ($checkloginvia) {
1205: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1206: if ($loginvia) {
1207: my ($server,$path) = split(/:/,$loginvia);
1208: ($login_host, $lowest_load) =
1.1253 raeburn 1209: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1210: if ($login_host eq $server) {
1211: $portal_path = $path;
1.1151 raeburn 1212: $isredirect = 1;
1.1116 raeburn 1213: }
1214: } else {
1215: ($login_host, $lowest_load) =
1.1253 raeburn 1216: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1217: if ($login_host eq $lonhost) {
1218: $portal_path = '';
1.1151 raeburn 1219: $isredirect = '';
1.1116 raeburn 1220: }
1221: }
1222: } else {
1.1076 raeburn 1223: ($login_host, $lowest_load) =
1.1253 raeburn 1224: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1225: }
1226: }
1227: if ($login_host ne '') {
1.1116 raeburn 1228: $hostname = &hostname($login_host);
1.1076 raeburn 1229: }
1.1331 raeburn 1230: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1231: }
1232:
1.1420 ! raeburn 1233: sub get_course_sessions {
! 1234: my ($cnum,$cdom,$lastactivity) = @_;
! 1235: my %servers = &internet_dom_servers($cdom);
! 1236: my %returnhash;
! 1237: foreach my $server (sort(keys(%servers))) {
! 1238: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
! 1239: my @pairs=split(/\&/,$rep);
! 1240: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
! 1241: foreach my $item (@pairs) {
! 1242: my ($key,$value)=split(/=/,$item,2);
! 1243: $key = &unescape($key);
! 1244: next if ($key =~ /^error: 2 /);
! 1245: if (exists($returnhash{$key})) {
! 1246: next if ($value < $returnhash{$key});
! 1247: }
! 1248: $returnhash{$key}=$value;
! 1249: }
! 1250: }
! 1251: }
! 1252: return %returnhash;
! 1253: }
! 1254:
1.202 matthew 1255: # --------------------------------------------- Try to change a user's password
1256:
1257: sub changepass {
1.799 raeburn 1258: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1259: $currentpass = &escape($currentpass);
1260: $newpass = &escape($newpass);
1.1030 raeburn 1261: my $lonhost = $perlvar{'lonHostID'};
1262: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1263: $server);
1264: if (! $answer) {
1265: &logthis("No reply on password change request to $server ".
1266: "by $uname in domain $udom.");
1267: } elsif ($answer =~ "^ok") {
1268: &logthis("$uname in $udom successfully changed their password ".
1269: "on $server.");
1270: } elsif ($answer =~ "^pwchange_failure") {
1271: &logthis("$uname in $udom was unable to change their password ".
1272: "on $server. The action was blocked by either lcpasswd ".
1273: "or pwchange");
1274: } elsif ($answer =~ "^non_authorized") {
1275: &logthis("$uname in $udom did not get their password correct when ".
1276: "attempting to change it on $server.");
1277: } elsif ($answer =~ "^auth_mode_error") {
1278: &logthis("$uname in $udom attempted to change their password despite ".
1279: "not being locally or internally authenticated on $server.");
1280: } elsif ($answer =~ "^unknown_user") {
1281: &logthis("$uname in $udom attempted to change their password ".
1282: "on $server but were unable to because $server is not ".
1283: "their home server.");
1284: } elsif ($answer =~ "^refused") {
1285: &logthis("$server refused to change $uname in $udom password because ".
1286: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1287: } elsif ($answer =~ "invalid_client") {
1288: &logthis("$server refused to change $uname in $udom password because ".
1289: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1290: } elsif ($answer =~ "^prioruse") {
1291: &logthis("$server refused to change $uname in $udom password because ".
1292: "the password had been used before");
1.202 matthew 1293: }
1294: return $answer;
1.1 albertel 1295: }
1296:
1.169 harris41 1297: # ----------------------- Try to determine user's current authentication scheme
1298:
1299: sub queryauthenticate {
1300: my ($uname,$udom)=@_;
1.456 albertel 1301: my $uhome=&homeserver($uname,$udom);
1302: if (!$uhome) {
1303: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1304: return 'no_host';
1305: }
1306: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1307: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1308: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1309: }
1.456 albertel 1310: return $answer;
1.169 harris41 1311: }
1312:
1.1 albertel 1313: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1314:
1.1 albertel 1315: sub authenticate {
1.1073 raeburn 1316: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1317: $upass=&escape($upass);
1318: $uname= &LONCAPA::clean_username($uname);
1.836 www 1319: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1320: my $newhome;
1.836 www 1321: if ((!$uhome) || ($uhome eq 'no_host')) {
1322: # Maybe the machine was offline and only re-appeared again recently?
1323: &reconlonc();
1324: # One more
1.952 raeburn 1325: $uhome=&homeserver($uname,$udom,1);
1326: if (($uhome eq 'no_host') && $checkdefauth) {
1327: if (defined(&domain($udom,'primary'))) {
1328: $newhome=&domain($udom,'primary');
1329: }
1330: if ($newhome ne '') {
1331: $uhome = $newhome;
1332: }
1333: }
1.836 www 1334: if ((!$uhome) || ($uhome eq 'no_host')) {
1335: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1336: return 'no_host';
1337: }
1.1 albertel 1338: }
1.1073 raeburn 1339: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1340: if ($answer eq 'authorized') {
1.952 raeburn 1341: if ($newhome) {
1342: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1343: return 'no_account_on_host';
1344: } else {
1345: &logthis("User $uname at $udom authorized by $uhome");
1346: return $uhome;
1347: }
1.471 albertel 1348: }
1349: if ($answer eq 'non_authorized') {
1350: &logthis("User $uname at $udom rejected by $uhome");
1351: return 'no_host';
1.9 www 1352: }
1.471 albertel 1353: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1354: return 'no_host';
1355: }
1356:
1.1073 raeburn 1357: sub can_host_session {
1.1074 raeburn 1358: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1359: my $canhost = 1;
1.1074 raeburn 1360: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1361: if (ref($remotesessions) eq 'HASH') {
1362: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1363: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1364: $canhost = 0;
1365: } else {
1366: $canhost = 1;
1367: }
1368: }
1369: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1370: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1371: $canhost = 1;
1372: } else {
1373: $canhost = 0;
1374: }
1375: }
1376: if ($canhost) {
1377: if ($remotesessions->{'version'} ne '') {
1378: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1379: if ($reqmajor ne '' && $reqminor ne '') {
1380: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1381: my $major = $1;
1382: my $minor = $2;
1383: if (($major < $reqmajor ) ||
1384: (($major == $reqmajor) && ($minor < $reqminor))) {
1385: $canhost = 0;
1386: }
1387: } else {
1388: $canhost = 0;
1389: }
1390: }
1391: }
1392: }
1393: }
1394: if ($canhost) {
1395: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1396: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1397: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1398: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1399: if (($uint_dom ne '') &&
1400: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1401: $canhost = 0;
1402: } else {
1403: $canhost = 1;
1404: }
1405: }
1406: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1407: if (($uint_dom ne '') &&
1408: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1409: $canhost = 1;
1410: } else {
1411: $canhost = 0;
1412: }
1413: }
1414: }
1415: }
1416: return $canhost;
1417: }
1418:
1.1083 raeburn 1419: sub spare_can_host {
1420: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1421: my $canhost=1;
1.1279 raeburn 1422: my $try_server_hostname = &hostname($try_server);
1423: my $serverhomeID = &get_server_homeID($try_server_hostname);
1424: my $serverhomedom = &host_domain($serverhomeID);
1425: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1426: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1427: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1428: $canhost = 0;
1429: }
1430: }
1431: if (($canhost) && ($uint_dom)) {
1432: my @intdoms;
1433: my $internet_names = &get_internet_names($try_server);
1434: if (ref($internet_names) eq 'ARRAY') {
1435: @intdoms = @{$internet_names};
1436: }
1437: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1438: my $remoterev = &get_server_loncaparev(undef,$try_server);
1439: $canhost = &can_host_session($udom,$try_server,$remoterev,
1440: $remotesessions,
1441: $defdomdefaults{'hostedsessions'});
1442: }
1.1083 raeburn 1443: }
1444: return $canhost;
1445: }
1446:
1.1123 raeburn 1447: sub this_host_spares {
1448: my ($dom) = @_;
1.1126 raeburn 1449: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1450: my @hosts = ¤t_machine_ids();
1451: foreach my $lonhost (@hosts) {
1452: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1453: $dom_in_use = $dom;
1454: $lonhost_in_use = $lonhost;
1.1123 raeburn 1455: last;
1456: }
1457: }
1.1126 raeburn 1458: if ($dom_in_use ne '') {
1459: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1460: }
1461: if (ref($result) ne 'HASH') {
1462: $lonhost_in_use = $perlvar{'lonHostID'};
1463: $dom_in_use = &host_domain($lonhost_in_use);
1464: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1465: if (ref($result) ne 'HASH') {
1466: $result = \%spareid;
1467: }
1468: }
1469: return $result;
1470: }
1471:
1472: sub spares_for_offload {
1473: my ($dom_in_use,$lonhost_in_use) = @_;
1474: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1475: if (defined($cached)) {
1476: return $result;
1477: } else {
1.1126 raeburn 1478: my $cachetime = 60*60*24;
1479: my %domconfig =
1480: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1481: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1482: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1483: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1484: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1485: }
1486: }
1487: }
1488: }
1.1126 raeburn 1489: return;
1.1123 raeburn 1490: }
1491:
1.1129 raeburn 1492: sub get_lonbalancer_config {
1493: my ($servers) = @_;
1494: my ($currbalancer,$currtargets);
1495: if (ref($servers) eq 'HASH') {
1496: foreach my $server (keys(%{$servers})) {
1497: my %what = (
1498: spareid => 1,
1499: perlvar => 1,
1500: );
1501: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1502: if ($result eq 'ok') {
1503: if (ref($returnhash) eq 'HASH') {
1504: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1505: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1506: $currbalancer = $server;
1507: $currtargets = {};
1508: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1509: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1510: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1511: }
1512: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1513: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1514: }
1515: }
1516: last;
1517: }
1518: }
1519: }
1520: }
1521: }
1522: }
1523: return ($currbalancer,$currtargets);
1524: }
1525:
1526: sub check_loadbalancing {
1.1331 raeburn 1527: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1528: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1529: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1530: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1531: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1532: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1533: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1534: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1535: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1536: my $domneedscache;
1.1129 raeburn 1537: my $cachetime = 60*60*24;
1538:
1539: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1540: $dom_in_use = $udom;
1541: $homeintdom = 1;
1542: } else {
1543: $dom_in_use = $serverhomedom;
1544: }
1545: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1546: unless (defined($cached)) {
1547: my %domconfig =
1548: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1549: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1550: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1551: } else {
1552: $domneedscache = $dom_in_use;
1.1129 raeburn 1553: }
1554: }
1555: if (ref($result) eq 'HASH') {
1.1391 raeburn 1556: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1557: &check_balancer_result($result,@hosts);
1.1129 raeburn 1558: if ($is_balancer) {
1559: if (ref($currrules) eq 'HASH') {
1560: if ($homeintdom) {
1561: if ($uname ne '') {
1562: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1563: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1564: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1565: $rule_in_effect = $currrules->{'_LC_author'};
1566: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1567: $rule_in_effect = $currrules->{'_LC_adv'}
1568: }
1569: }
1570: if ($rule_in_effect eq '') {
1571: my %userenv = &userenvironment($udom,$uname,'inststatus');
1572: if ($userenv{'inststatus'} ne '') {
1573: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1574: my ($othertitle,$usertypes,$types) =
1575: &Apache::loncommon::sorted_inst_types($udom);
1576: if (ref($types) eq 'ARRAY') {
1577: foreach my $type (@{$types}) {
1578: if (grep(/^\Q$type\E$/,@statuses)) {
1579: if (exists($currrules->{$type})) {
1580: $rule_in_effect = $currrules->{$type};
1581: }
1582: }
1583: }
1584: }
1585: } else {
1586: if (exists($currrules->{'default'})) {
1587: $rule_in_effect = $currrules->{'default'};
1588: }
1589: }
1590: }
1591: } else {
1592: if (exists($currrules->{'default'})) {
1593: $rule_in_effect = $currrules->{'default'};
1594: }
1595: }
1596: } else {
1597: if ($currrules->{'_LC_external'} ne '') {
1598: $rule_in_effect = $currrules->{'_LC_external'};
1599: }
1600: }
1601: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1602: $uname,$udom);
1603: }
1604: }
1605: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1606: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1607: unless (defined($cached)) {
1608: my %domconfig =
1609: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1610: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1611: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1612: } else {
1613: $domneedscache = $serverhomedom;
1.1129 raeburn 1614: }
1615: }
1616: if (ref($result) eq 'HASH') {
1.1391 raeburn 1617: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1618: &check_balancer_result($result,@hosts);
1619: if ($is_balancer) {
1.1129 raeburn 1620: if (ref($currrules) eq 'HASH') {
1621: if ($currrules->{'_LC_internetdom'} ne '') {
1622: $rule_in_effect = $currrules->{'_LC_internetdom'};
1623: }
1624: }
1625: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1626: $uname,$udom);
1627: }
1628: } else {
1629: if ($perlvar{'lonBalancer'} eq 'yes') {
1630: $is_balancer = 1;
1631: $offloadto = &this_host_spares($dom_in_use);
1632: }
1.1307 raeburn 1633: unless (defined($cached)) {
1634: $domneedscache = $serverhomedom;
1635: }
1.1129 raeburn 1636: }
1637: } else {
1638: if ($perlvar{'lonBalancer'} eq 'yes') {
1639: $is_balancer = 1;
1640: $offloadto = &this_host_spares($dom_in_use);
1641: }
1.1307 raeburn 1642: unless (defined($cached)) {
1643: $domneedscache = $serverhomedom;
1644: }
1645: }
1646: if ($domneedscache) {
1647: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1648: }
1.1176 raeburn 1649: if ($is_balancer) {
1650: my $lowest_load = 30000;
1651: if (ref($offloadto) eq 'HASH') {
1652: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1653: foreach my $try_server (@{$offloadto->{'primary'}}) {
1654: ($otherserver,$lowest_load) =
1655: &compare_server_load($try_server,$otherserver,$lowest_load);
1656: }
1.1129 raeburn 1657: }
1.1176 raeburn 1658: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1659:
1.1176 raeburn 1660: if (!$found_server) {
1661: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1662: foreach my $try_server (@{$offloadto->{'default'}}) {
1663: ($otherserver,$lowest_load) =
1664: &compare_server_load($try_server,$otherserver,$lowest_load);
1665: }
1666: }
1667: }
1668: } elsif (ref($offloadto) eq 'ARRAY') {
1669: if (@{$offloadto} == 1) {
1670: $otherserver = $offloadto->[0];
1671: } elsif (@{$offloadto} > 1) {
1672: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1673: ($otherserver,$lowest_load) =
1674: &compare_server_load($try_server,$otherserver,$lowest_load);
1675: }
1676: }
1677: }
1.1331 raeburn 1678: unless ($caller eq 'login') {
1679: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1680: $is_balancer = 0;
1681: if ($uname ne '' && $udom ne '') {
1682: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1683: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1684: 'user.loadbalcheck.time' => time});
1685: }
1.1176 raeburn 1686: }
1.1129 raeburn 1687: }
1688: }
1.1389 raeburn 1689: unless ($homeintdom) {
1690: undef($setcookie);
1691: }
1.1129 raeburn 1692: }
1.1391 raeburn 1693: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1694: }
1695:
1.1191 raeburn 1696: sub check_balancer_result {
1697: my ($result,@hosts) = @_;
1.1391 raeburn 1698: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1699: if (ref($result) eq 'HASH') {
1700: if ($result->{'lonhost'} ne '') {
1701: my $currbalancer = $result->{'lonhost'};
1702: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1703: $is_balancer = 1;
1704: $currtargets = $result->{'targets'};
1705: $currrules = $result->{'rules'};
1706: }
1.1391 raeburn 1707: $dom_balancers = $currbalancer;
1.1191 raeburn 1708: } else {
1.1391 raeburn 1709: if (keys(%{$result})) {
1710: foreach my $key (keys(%{$result})) {
1711: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1712: (ref($result->{$key}) eq 'HASH')) {
1713: $is_balancer = 1;
1714: $currrules = $result->{$key}{'rules'};
1715: $currtargets = $result->{$key}{'targets'};
1716: $setcookie = $result->{$key}{'cookie'};
1717: last;
1718: }
1.1191 raeburn 1719: }
1.1391 raeburn 1720: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1721: }
1722: }
1723: }
1.1391 raeburn 1724: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1725: }
1726:
1.1129 raeburn 1727: sub get_loadbalancer_targets {
1728: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1729: my $offloadto;
1.1175 raeburn 1730: if ($rule_in_effect eq 'none') {
1731: return [$perlvar{'lonHostID'}];
1732: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1733: $offloadto = $currtargets;
1734: } else {
1735: if ($rule_in_effect eq 'homeserver') {
1736: my $homeserver = &homeserver($uname,$udom);
1737: if ($homeserver ne 'no_host') {
1738: $offloadto = [$homeserver];
1739: }
1740: } elsif ($rule_in_effect eq 'externalbalancer') {
1741: my %domconfig =
1742: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1743: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1744: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1745: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1746: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1747: }
1748: }
1749: } else {
1.1178 raeburn 1750: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1751: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1752: if (&hostname($remotebalancer) ne '') {
1753: $offloadto = [$remotebalancer];
1754: }
1755: }
1756: } elsif (&hostname($rule_in_effect) ne '') {
1757: $offloadto = [$rule_in_effect];
1758: }
1759: }
1760: return $offloadto;
1761: }
1762:
1.1127 raeburn 1763: sub internet_dom_servers {
1764: my ($dom) = @_;
1765: my (%uniqservers,%servers);
1766: my $primaryserver = &hostname(&domain($dom,'primary'));
1767: my @machinedoms = &machine_domains($primaryserver);
1768: foreach my $mdom (@machinedoms) {
1769: my %currservers = %servers;
1770: my %server = &get_servers($mdom);
1771: %servers = (%currservers,%server);
1772: }
1773: my %by_hostname;
1774: foreach my $id (keys(%servers)) {
1775: push(@{$by_hostname{$servers{$id}}},$id);
1776: }
1777: foreach my $hostname (sort(keys(%by_hostname))) {
1778: if (@{$by_hostname{$hostname}} > 1) {
1779: my $match = 0;
1780: foreach my $id (@{$by_hostname{$hostname}}) {
1781: if (&host_domain($id) eq $dom) {
1782: $uniqservers{$id} = $hostname;
1783: $match = 1;
1784: }
1785: }
1786: unless ($match) {
1787: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1788: }
1789: } else {
1790: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1791: }
1792: }
1793: return %uniqservers;
1794: }
1795:
1.1347 raeburn 1796: sub trusted_domains {
1797: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1798: my ($trusted,$untrusted);
1.1347 raeburn 1799: if (&domain($calldom) eq '') {
1.1349 raeburn 1800: return ($trusted,$untrusted);
1.1347 raeburn 1801: }
1.1395 raeburn 1802: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1803: return ($trusted,$untrusted);
1.1347 raeburn 1804: }
1805: my $callprimary = &domain($calldom,'primary');
1806: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1807: if ($intcalldom eq '') {
1.1349 raeburn 1808: return ($trusted,$untrusted);
1.1347 raeburn 1809: }
1810:
1811: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1812: unless (defined($cached)) {
1813: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1814: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1815: $trustconfig = $domconfig{'trust'};
1816: }
1817: if (ref($trustconfig)) {
1818: my (%possexc,%possinc,@allexc,@allinc);
1819: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1820: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1821: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1822: }
1823: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1824: $possinc{$intcalldom} = 1;
1.1347 raeburn 1825: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1826: }
1827: }
1828: if (keys(%possexc)) {
1829: if (keys(%possinc)) {
1830: foreach my $key (sort(keys(%possexc))) {
1831: next if ($key eq $intcalldom);
1832: unless ($possinc{$key}) {
1833: push(@allexc,$key);
1834: }
1835: }
1836: } else {
1837: @allexc = sort(keys(%possexc));
1838: }
1839: }
1840: if (keys(%possinc)) {
1841: $possinc{$intcalldom} = 1;
1842: @allinc = sort(keys(%possinc));
1843: }
1844: if ((@allexc > 0) || (@allinc > 0)) {
1845: my %doms_by_intdom;
1846: my %allintdoms = &all_host_intdom();
1847: my %alldoms = &all_host_domain();
1848: foreach my $key (%allintdoms) {
1849: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1850: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1851: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1852: }
1853: } else {
1854: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1855: }
1856: }
1857: foreach my $exc (@allexc) {
1858: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1859: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1860: }
1861: }
1862: foreach my $inc (@allinc) {
1863: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1864: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1865: }
1866: }
1867: }
1868: }
1.1349 raeburn 1869: return ($trusted,$untrusted);
1.1347 raeburn 1870: }
1871:
1872: sub will_trust {
1873: my ($cmdtype,$domain,$possdom) = @_;
1874: return 1 if ($domain eq $possdom);
1875: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1876: my $willtrust;
1877: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1878: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1879: $willtrust = 1;
1880: }
1881: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1882: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1883: $willtrust = 1;
1884: }
1885: } else {
1886: $willtrust = 1;
1887: }
1888: return $willtrust;
1889: }
1890:
1.1 albertel 1891: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1892:
1.599 albertel 1893: my %homecache;
1.1 albertel 1894: sub homeserver {
1.230 stredwic 1895: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1896: my $index="$uname:$udom";
1.426 albertel 1897:
1.599 albertel 1898: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1899:
1900: my %servers = &get_servers($udom,'library');
1901: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1902: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1903: exists($badServerCache{$tryserver}));
1.841 albertel 1904:
1905: my $answer=reply("home:$udom:$uname",$tryserver);
1906: if ($answer eq 'found') {
1907: delete($badServerCache{$tryserver});
1908: return $homecache{$index}=$tryserver;
1909: } elsif ($answer eq 'no_host') {
1910: $badServerCache{$tryserver}=1;
1911: }
1.1 albertel 1912: }
1913: return 'no_host';
1.70 www 1914: }
1915:
1.1300 raeburn 1916: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1917:
1918: sub idget {
1.1300 raeburn 1919: my ($udom,$idsref,$namespace)=@_;
1.70 www 1920: my %returnhash=();
1.1300 raeburn 1921: my @ids=();
1922: if (ref($idsref) eq 'ARRAY') {
1923: @ids = @{$idsref};
1924: } else {
1925: return %returnhash;
1926: }
1927: if ($namespace eq '') {
1928: $namespace = 'ids';
1929: }
1.70 www 1930:
1.841 albertel 1931: my %servers = &get_servers($udom,'library');
1932: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1933: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1934: if ($namespace eq 'ids') {
1935: $idlist=~tr/A-Z/a-z/;
1936: }
1937: my $reply;
1938: if ($namespace eq 'ids') {
1939: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1940: } else {
1941: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1942: }
1.841 albertel 1943: my @answer=();
1944: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1945: @answer=split(/\&/,$reply);
1946: } ;
1947: my $i;
1948: for ($i=0;$i<=$#ids;$i++) {
1949: if ($answer[$i]) {
1.1299 raeburn 1950: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1951: }
1.841 albertel 1952: }
1.1300 raeburn 1953: }
1.70 www 1954: return %returnhash;
1955: }
1956:
1957: # ------------------------------------- Find the IDs behind a list of usernames
1958:
1959: sub idrget {
1960: my ($udom,@unames)=@_;
1961: my %returnhash=();
1.800 albertel 1962: foreach my $uname (@unames) {
1963: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1964: }
1.70 www 1965: return %returnhash;
1966: }
1967:
1.1300 raeburn 1968: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1969:
1970: sub idput {
1.1300 raeburn 1971: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1972: my %servers=();
1.1300 raeburn 1973: my %ids=();
1974: my %byid = ();
1975: if (ref($idsref) eq 'HASH') {
1976: %ids=%{$idsref};
1977: }
1978: if ($namespace eq '') {
1979: $namespace = 'ids';
1980: }
1.800 albertel 1981: foreach my $uname (keys(%ids)) {
1982: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1983: if ($uhom eq '') {
1984: $uhom=&homeserver($uname,$udom);
1985: }
1.70 www 1986: if ($uhom ne 'no_host') {
1.800 albertel 1987: my $esc_unam=&escape($uname);
1.1300 raeburn 1988: if ($namespace eq 'ids') {
1989: my $id=&escape($ids{$uname});
1990: $id=~tr/A-Z/a-z/;
1991: my $esc_unam=&escape($uname);
1992: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1993: } else {
1.1300 raeburn 1994: my @currids = split(/,/,$ids{$uname});
1995: foreach my $id (@currids) {
1996: $byid{$uhom}{$id} .= $uname.',';
1997: }
1998: }
1999: }
2000: }
2001: if ($namespace eq 'clickers') {
2002: foreach my $server (keys(%byid)) {
2003: if (ref($byid{$server}) eq 'HASH') {
2004: foreach my $id (keys(%{$byid{$server}})) {
2005: $byid{$server} =~ s/,$//;
2006: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2007: }
1.70 www 2008: }
2009: }
1.191 harris41 2010: }
1.800 albertel 2011: foreach my $server (keys(%servers)) {
1.1300 raeburn 2012: $servers{$server} =~ s/\&$//;
2013: if ($namespace eq 'ids') {
2014: &critical('idput:'.$udom.':'.$servers{$server},$server);
2015: } else {
2016: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2017: }
1.191 harris41 2018: }
1.344 www 2019: }
2020:
1.1300 raeburn 2021: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2022:
2023: sub iddel {
1.1300 raeburn 2024: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2025: my %result=();
1.1300 raeburn 2026: my %ids=();
2027: my %byid = ();
2028: if (ref($idshashref) eq 'HASH') {
2029: %ids=%{$idshashref};
2030: } else {
1.1231 raeburn 2031: return %result;
2032: }
1.1300 raeburn 2033: if ($namespace eq '') {
2034: $namespace = 'ids';
2035: }
1.1231 raeburn 2036: my %servers=();
1.1300 raeburn 2037: while (my ($id,$unamestr) = each(%ids)) {
2038: if ($namespace eq 'ids') {
2039: my $uhom = $uhome;
2040: if ($uhom eq '') {
2041: $uhom=&homeserver($unamestr,$udom);
2042: }
2043: if ($uhom ne 'no_host') {
2044: $servers{$uhom}.='&'.&escape($id);
2045: }
2046: } else {
2047: my @curritems = split(/,/,$ids{$id});
2048: foreach my $uname (@curritems) {
2049: my $uhom = $uhome;
2050: if ($uhom eq '') {
2051: $uhom=&homeserver($uname,$udom);
2052: }
2053: if ($uhom ne 'no_host') {
2054: $byid{$uhom}{$id} .= $uname.',';
2055: }
2056: }
1.1231 raeburn 2057: }
1.1300 raeburn 2058: }
2059: if ($namespace eq 'clickers') {
2060: foreach my $server (keys(%byid)) {
2061: if (ref($byid{$server}) eq 'HASH') {
2062: foreach my $id (keys(%{$byid{$server}})) {
2063: $byid{$server}{$id} =~ s/,$//;
2064: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2065: }
1.1231 raeburn 2066: }
2067: }
2068: }
2069: foreach my $server (keys(%servers)) {
1.1300 raeburn 2070: $servers{$server} =~ s/\&$//;
2071: if ($namespace eq 'ids') {
2072: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2073: } elsif ($namespace eq 'clickers') {
2074: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2075: }
1.1231 raeburn 2076: }
2077: return %result;
2078: }
2079:
1.1300 raeburn 2080: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2081:
2082: sub updateclickers {
2083: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2084: my %clickers;
2085: if (ref($idshashref) eq 'HASH') {
2086: %clickers=%{$idshashref};
2087: } else {
2088: return;
2089: }
2090: my $items='';
2091: foreach my $item (keys(%clickers)) {
2092: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2093: }
2094: $items=~s/\&$//;
2095: my $request = "updateclickers:$udom:$action:$items";
2096: if ($critical) {
2097: return &critical($request,$uhome);
2098: } else {
2099: return &reply($request,$uhome);
2100: }
2101: }
2102:
1.1023 raeburn 2103: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2104: sub dump_dom {
1.1165 droeschl 2105: my ($namespace, $udom, $regexp) = @_;
2106:
2107: $udom ||= $env{'user.domain'};
2108:
2109: return () unless $udom;
2110:
2111: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2112: }
2113:
1.1023 raeburn 2114: # ------------------------------------------ get items from domain db files
1.806 raeburn 2115:
2116: sub get_dom {
1.860 raeburn 2117: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 2118: return if ($udom eq 'public');
1.806 raeburn 2119: my $items='';
2120: foreach my $item (@$storearr) {
2121: $items.=&escape($item).'&';
2122: }
2123: $items=~s/\&$//;
1.860 raeburn 2124: if (!$udom) {
2125: $udom=$env{'user.domain'};
1.1267 raeburn 2126: return if ($udom eq 'public');
1.860 raeburn 2127: if (defined(&domain($udom,'primary'))) {
2128: $uhome=&domain($udom,'primary');
2129: } else {
1.874 albertel 2130: undef($uhome);
1.860 raeburn 2131: }
2132: } else {
2133: if (!$uhome) {
2134: if (defined(&domain($udom,'primary'))) {
2135: $uhome=&domain($udom,'primary');
2136: }
2137: }
2138: }
2139: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2140: my $rep;
2141: if ($namespace =~ /^enc/) {
2142: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2143: } else {
2144: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2145: }
1.866 raeburn 2146: my %returnhash;
1.875 albertel 2147: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2148: return %returnhash;
2149: }
1.806 raeburn 2150: my @pairs=split(/\&/,$rep);
2151: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2152: return @pairs;
2153: }
2154: my $i=0;
2155: foreach my $item (@$storearr) {
2156: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2157: $i++;
2158: }
2159: return %returnhash;
2160: } else {
1.880 banghart 2161: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2162: }
2163: }
2164:
2165: # -------------------------------------------- put items in domain db files
2166:
2167: sub put_dom {
1.860 raeburn 2168: my ($namespace,$storehash,$udom,$uhome)=@_;
2169: if (!$udom) {
2170: $udom=$env{'user.domain'};
2171: if (defined(&domain($udom,'primary'))) {
2172: $uhome=&domain($udom,'primary');
2173: } else {
1.874 albertel 2174: undef($uhome);
1.860 raeburn 2175: }
2176: } else {
2177: if (!$uhome) {
2178: if (defined(&domain($udom,'primary'))) {
2179: $uhome=&domain($udom,'primary');
2180: }
2181: }
2182: }
2183: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2184: my $items='';
2185: foreach my $item (keys(%$storehash)) {
2186: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2187: }
2188: $items=~s/\&$//;
1.1344 raeburn 2189: if ($namespace =~ /^enc/) {
2190: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2191: } else {
2192: return &reply("putdom:$udom:$namespace:$items",$uhome);
2193: }
1.806 raeburn 2194: } else {
1.860 raeburn 2195: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2196: }
2197: }
2198:
1.1023 raeburn 2199: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2200: sub newput_dom {
1.1023 raeburn 2201: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2202: my $result;
2203: if (!$udom) {
2204: $udom=$env{'user.domain'};
2205: }
1.1023 raeburn 2206: if ($udom) {
2207: my $uname = &get_domainconfiguser($udom);
2208: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2209: }
2210: return $result;
2211: }
2212:
1.1023 raeburn 2213: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2214: sub del_dom {
1.1023 raeburn 2215: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2216: if (ref($storearr) eq 'ARRAY') {
2217: if (!$udom) {
2218: $udom=$env{'user.domain'};
2219: }
1.1023 raeburn 2220: if ($udom) {
2221: my $uname = &get_domainconfiguser($udom);
2222: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2223: }
2224: }
2225: }
2226:
1.1023 raeburn 2227: # ----------------------------------construct domainconfig user for a domain
2228: sub get_domainconfiguser {
2229: my ($udom) = @_;
2230: return $udom.'-domainconfig';
2231: }
2232:
1.837 raeburn 2233: sub retrieve_inst_usertypes {
2234: my ($udom) = @_;
2235: my (%returnhash,@order);
1.989 raeburn 2236: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2237: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2238: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2239: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2240: } else {
2241: if (defined(&domain($udom,'primary'))) {
2242: my $uhome=&domain($udom,'primary');
2243: my $rep=&reply("inst_usertypes:$udom",$uhome);
2244: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2245: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2246: return (\%returnhash,\@order);
2247: }
2248: my ($hashitems,$orderitems) = split(/:/,$rep);
2249: my @pairs=split(/\&/,$hashitems);
2250: foreach my $item (@pairs) {
2251: my ($key,$value)=split(/=/,$item,2);
2252: $key = &unescape($key);
2253: next if ($key =~ /^error: 2 /);
2254: $returnhash{$key}=&thaw_unescape($value);
2255: }
2256: my @esc_order = split(/\&/,$orderitems);
2257: foreach my $item (@esc_order) {
2258: push(@order,&unescape($item));
2259: }
2260: } else {
1.1256 raeburn 2261: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2262: }
1.1256 raeburn 2263: return (\%returnhash,\@order);
1.837 raeburn 2264: }
2265: }
2266:
1.868 raeburn 2267: sub is_domainimage {
2268: my ($url) = @_;
1.1306 raeburn 2269: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2270: if (&domain($1) ne '') {
2271: return '1';
2272: }
2273: }
2274: return;
2275: }
2276:
1.899 raeburn 2277: sub inst_directory_query {
2278: my ($srch) = @_;
2279: my $udom = $srch->{'srchdomain'};
2280: my %results;
2281: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2282: my $outcome;
1.899 raeburn 2283: if ($homeserver ne '') {
1.1357 raeburn 2284: unless ($homeserver eq $perlvar{'lonHostID'}) {
2285: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2286: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2287: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2288: if (($major eq '' && $minor eq '') || ($major < 2) ||
2289: (($major == 2) && ($minor < 12))) {
2290: return;
2291: }
2292: }
2293: }
1.904 albertel 2294: my $queryid=&reply("querysend:instdirsearch:".
2295: &escape($srch->{'srchby'}).':'.
2296: &escape($srch->{'srchterm'}).':'.
2297: &escape($srch->{'srchtype'}),$homeserver);
2298: my $host=&hostname($homeserver);
2299: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2300: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2301: return;
2302: }
2303: my $response = &get_query_reply($queryid);
2304: my $maxtries = 5;
2305: my $tries = 1;
2306: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2307: $response = &get_query_reply($queryid);
2308: $tries ++;
2309: }
2310:
2311: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2312: if ($response eq 'unavailable') {
2313: $outcome = $response;
2314: } else {
2315: $outcome = 'ok';
2316: my @matches = split(/\n/,$response);
2317: foreach my $match (@matches) {
2318: my ($key,$value) = split(/=/,$match);
2319: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2320: }
1.899 raeburn 2321: }
2322: }
2323: }
1.909 raeburn 2324: return ($outcome,%results);
1.899 raeburn 2325: }
2326:
2327: sub usersearch {
2328: my ($srch) = @_;
2329: my $dom = $srch->{'srchdomain'};
2330: my %results;
2331: my %libserv = &all_library();
2332: my $query = 'usersearch';
2333: foreach my $tryserver (keys(%libserv)) {
2334: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2335: unless ($tryserver eq $perlvar{'lonHostID'}) {
2336: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2337: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2338: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2339: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2340: (($major == 2) && ($minor < 12)));
2341: }
2342: }
1.899 raeburn 2343: my $host=&hostname($tryserver);
2344: my $queryid=
1.911 raeburn 2345: &reply("querysend:".&escape($query).':'.
2346: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2347: &escape($srch->{'srchtype'}).':'.
2348: &escape($srch->{'srchterm'}),$tryserver);
2349: if ($queryid !~/^\Q$host\E\_/) {
2350: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2351: next;
1.899 raeburn 2352: }
2353: my $reply = &get_query_reply($queryid);
2354: my $maxtries = 1;
2355: my $tries = 1;
2356: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2357: $reply = &get_query_reply($queryid);
2358: $tries ++;
2359: }
2360: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2361: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2362: } else {
1.911 raeburn 2363: my @matches;
2364: if ($reply =~ /\n/) {
2365: @matches = split(/\n/,$reply);
2366: } else {
2367: @matches = split(/\&/,$reply);
2368: }
1.899 raeburn 2369: foreach my $match (@matches) {
2370: my ($uname,$udom,%userhash);
1.911 raeburn 2371: foreach my $entry (split(/:/,$match)) {
2372: my ($key,$value) =
2373: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2374: $userhash{$key} = $value;
2375: if ($key eq 'username') {
2376: $uname = $value;
2377: } elsif ($key eq 'domain') {
2378: $udom = $value;
1.911 raeburn 2379: }
1.899 raeburn 2380: }
2381: $results{$uname.':'.$udom} = \%userhash;
2382: }
2383: }
2384: }
2385: }
2386: return %results;
2387: }
2388:
1.912 raeburn 2389: sub get_instuser {
2390: my ($udom,$uname,$id) = @_;
2391: my $homeserver = &domain($udom,'primary');
2392: my ($outcome,%results);
2393: if ($homeserver ne '') {
2394: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2395: &escape($id).':'.&escape($udom),$homeserver);
2396: my $host=&hostname($homeserver);
2397: if ($queryid !~/^\Q$host\E\_/) {
2398: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2399: return;
2400: }
2401: my $response = &get_query_reply($queryid);
2402: my $maxtries = 5;
2403: my $tries = 1;
2404: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2405: $response = &get_query_reply($queryid);
2406: $tries ++;
2407: }
2408: if (!&error($response) && $response ne 'refused') {
2409: if ($response eq 'unavailable') {
2410: $outcome = $response;
2411: } else {
2412: $outcome = 'ok';
2413: my @matches = split(/\n/,$response);
2414: foreach my $match (@matches) {
2415: my ($key,$value) = split(/=/,$match);
2416: $results{&unescape($key)} = &thaw_unescape($value);
2417: }
2418: }
2419: }
2420: }
2421: my %userinfo;
2422: if (ref($results{$uname}) eq 'HASH') {
2423: %userinfo = %{$results{$uname}};
2424: }
2425: return ($outcome,%userinfo);
2426: }
2427:
1.1290 raeburn 2428: sub get_multiple_instusers {
2429: my ($udom,$users,$caller) = @_;
2430: my ($outcome,$results);
2431: if (ref($users) eq 'HASH') {
2432: my $count = keys(%{$users});
2433: my $requested = &freeze_escape($users);
2434: my $homeserver = &domain($udom,'primary');
2435: if ($homeserver ne '') {
2436: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2437: my $host=&hostname($homeserver);
2438: if ($queryid !~/^\Q$host\E\_/) {
2439: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2440: ' for host: '.$homeserver.'in domain '.$udom);
2441: return ($outcome,$results);
2442: }
2443: my $response = &get_query_reply($queryid);
2444: my $maxtries = 5;
2445: if ($count > 100) {
2446: $maxtries = 1+int($count/20);
2447: }
2448: my $tries = 1;
2449: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2450: $response = &get_query_reply($queryid);
2451: $tries ++;
2452: }
2453: if ($response eq '') {
2454: $results = {};
2455: foreach my $key (keys(%{$users})) {
2456: my ($uname,$id);
2457: if ($caller eq 'id') {
2458: $id = $key;
2459: } else {
2460: $uname = $key;
2461: }
2462: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2463: $outcome = $resp;
1.1290 raeburn 2464: if ($resp eq 'ok') {
2465: %{$results} = (%{$results}, %info);
2466: } else {
2467: last;
2468: }
2469: }
2470: } elsif(!&error($response) && ($response ne 'refused')) {
2471: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2472: $outcome = $response;
2473: } else {
1.1291 raeburn 2474: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2475: if ($outcome eq 'ok') {
2476: $results = &thaw_unescape($userdata);
2477: }
2478: }
2479: }
2480: }
2481: }
2482: return ($outcome,$results);
2483: }
2484:
1.912 raeburn 2485: sub inst_rulecheck {
1.923 raeburn 2486: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2487: my %returnhash;
2488: if ($udom ne '') {
2489: if (ref($rules) eq 'ARRAY') {
2490: @{$rules} = map {&escape($_);} (@{$rules});
2491: my $rulestr = join(':',@{$rules});
2492: my $homeserver=&domain($udom,'primary');
2493: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2494: my $response;
2495: if ($item eq 'username') {
2496: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2497: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2498: $homeserver));
1.923 raeburn 2499: } elsif ($item eq 'id') {
2500: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2501: ':'.&escape($id).':'.$rulestr,
2502: $homeserver));
1.945 raeburn 2503: } elsif ($item eq 'selfcreate') {
2504: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2505: &escape($udom).':'.&escape($uname).
2506: ':'.$rulestr,$homeserver));
1.923 raeburn 2507: }
1.912 raeburn 2508: if ($response ne 'refused') {
2509: my @pairs=split(/\&/,$response);
2510: foreach my $item (@pairs) {
2511: my ($key,$value)=split(/=/,$item,2);
2512: $key = &unescape($key);
2513: next if ($key =~ /^error: 2 /);
2514: $returnhash{$key}=&thaw_unescape($value);
2515: }
2516: }
2517: }
2518: }
2519: }
2520: return %returnhash;
2521: }
2522:
2523: sub inst_userrules {
1.923 raeburn 2524: my ($udom,$check) = @_;
1.912 raeburn 2525: my (%ruleshash,@ruleorder);
2526: if ($udom ne '') {
2527: my $homeserver=&domain($udom,'primary');
2528: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2529: my $response;
2530: if ($check eq 'id') {
2531: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2532: $homeserver);
1.943 raeburn 2533: } elsif ($check eq 'email') {
2534: $response=&reply('instemailrules:'.&escape($udom),
2535: $homeserver);
1.923 raeburn 2536: } else {
2537: $response=&reply('instuserrules:'.&escape($udom),
2538: $homeserver);
2539: }
1.912 raeburn 2540: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2541: ($response ne 'unknown_cmd') &&
1.912 raeburn 2542: ($response ne 'no_such_host')) {
2543: my ($hashitems,$orderitems) = split(/:/,$response);
2544: my @pairs=split(/\&/,$hashitems);
2545: foreach my $item (@pairs) {
2546: my ($key,$value)=split(/=/,$item,2);
2547: $key = &unescape($key);
2548: next if ($key =~ /^error: 2 /);
2549: $ruleshash{$key}=&thaw_unescape($value);
2550: }
2551: my @esc_order = split(/\&/,$orderitems);
2552: foreach my $item (@esc_order) {
2553: push(@ruleorder,&unescape($item));
2554: }
2555: }
2556: }
2557: }
2558: return (\%ruleshash,\@ruleorder);
2559: }
2560:
1.976 raeburn 2561: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2562:
2563: sub get_domain_defaults {
1.1240 raeburn 2564: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2565: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2566: my $cachetime = 60*60*24;
1.1240 raeburn 2567: unless ($ignore_cache) {
2568: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2569: if (defined($cached)) {
2570: if (ref($result) eq 'HASH') {
2571: return %{$result};
2572: }
1.943 raeburn 2573: }
2574: }
2575: my %domdefaults;
2576: my %domconfig =
1.989 raeburn 2577: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2578: 'requestcourses','inststatus',
1.1183 raeburn 2579: 'coursedefaults','usersessions',
1.1258 raeburn 2580: 'requestauthor','selfenrollment',
1.1320 raeburn 2581: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2582: 'trust','helpsettings'],$domain);
1.1305 raeburn 2583: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2584: if (ref($domconfig{'defaults'}) eq 'HASH') {
2585: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2586: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2587: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2588: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2589: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2590: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2591: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2592: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2593: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2594: } else {
2595: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2596: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2597: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2598: }
1.976 raeburn 2599: if (ref($domconfig{'quotas'}) eq 'HASH') {
2600: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2601: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2602: } else {
2603: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2604: }
1.1177 raeburn 2605: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2606: foreach my $item (@usertools) {
2607: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2608: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2609: }
2610: }
1.1229 raeburn 2611: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2612: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2613: }
1.976 raeburn 2614: }
1.985 raeburn 2615: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2616: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2617: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2618: }
2619: }
1.1183 raeburn 2620: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2621: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2622: }
1.989 raeburn 2623: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2624: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2625: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2626: }
2627: }
1.1047 raeburn 2628: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2629: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2630: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2631: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2632: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2633: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2634: }
1.1254 raeburn 2635: foreach my $type (@coursetypes) {
2636: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2637: unless ($type eq 'community') {
2638: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2639: }
2640: }
2641: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2642: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2643: }
1.1277 raeburn 2644: if ($domdefaults{'postsubmit'} eq 'on') {
2645: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2646: $domdefaults{$type.'postsubtimeout'} =
2647: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2648: }
2649: }
1.1230 raeburn 2650: }
1.1286 raeburn 2651: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2652: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2653: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2654: if (@clonecodes) {
2655: $domdefaults{'canclone'} = join('+',@clonecodes);
2656: }
2657: }
2658: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2659: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2660: }
1.1356 raeburn 2661: if ($domconfig{'coursedefaults'}{'texengine'}) {
2662: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2663: }
1.1047 raeburn 2664: }
1.1073 raeburn 2665: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2666: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2667: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2668: }
2669: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2670: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2671: }
1.1279 raeburn 2672: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2673: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2674: }
1.1073 raeburn 2675: }
1.1254 raeburn 2676: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2677: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2678: my @settings = ('types','registered','enroll_dates','access_dates','section',
2679: 'approval','limit');
2680: foreach my $type (@coursetypes) {
2681: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2682: my @mgrdc = ();
2683: foreach my $item (@settings) {
2684: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2685: push(@mgrdc,$item);
2686: }
2687: }
2688: if (@mgrdc) {
2689: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2690: }
2691: }
2692: }
2693: }
2694: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2695: foreach my $type (@coursetypes) {
2696: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2697: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2698: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2699: }
2700: }
2701: }
2702: }
2703: }
1.1258 raeburn 2704: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2705: $domdefaults{'catauth'} = 'std';
2706: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2707: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2708: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2709: }
2710: if ($domconfig{'coursecategories'}{'unauth'}) {
2711: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2712: }
2713: }
1.1315 raeburn 2714: if (ref($domconfig{'ssl'}) eq 'HASH') {
2715: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2716: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2717: }
1.1338 raeburn 2718: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2719: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2720: }
2721: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2722: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2723: }
2724: }
1.1320 raeburn 2725: if (ref($domconfig{'trust'}) eq 'HASH') {
2726: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2727: foreach my $prefix (@prefixes) {
2728: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2729: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2730: }
2731: }
2732: }
1.1314 raeburn 2733: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2734: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2735: }
1.1332 raeburn 2736: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2737: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2738: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2739: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2740: }
2741: }
1.1219 raeburn 2742: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2743: return %domdefaults;
2744: }
2745:
1.1412 raeburn 2746: sub get_dom_cats {
2747: my ($dom) = @_;
2748: return unless (&domain($dom));
2749: my ($cats,$cached)=&is_cached_new('cats',$dom);
2750: unless (defined($cached)) {
2751: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2752: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2753: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2754: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2755: } else {
2756: $cats = {};
2757: }
2758: } else {
2759: $cats = {};
2760: }
2761: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2762: }
1.1413 raeburn 2763: return $cats;
2764: }
2765:
2766: sub get_dom_instcats {
2767: my ($dom) = @_;
2768: return unless (&domain($dom));
2769: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2770: unless (defined($cached)) {
2771: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2772: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2773: if ($totcodes > 0) {
2774: my $caller = 'global';
2775: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2776: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2777: $instcats = {
2778: codes => \%codes,
2779: codetitles => \@codetitles,
2780: cat_titles => \%cat_titles,
2781: cat_order => \%cat_order,
2782: };
2783: &do_cache_new('instcats',$dom,$instcats,3600);
2784: }
2785: }
2786: }
2787: return $instcats;
2788: }
2789:
2790: sub retrieve_instcodes {
2791: my ($coursecodes,$dom) = @_;
2792: my $totcodes;
2793: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2794: foreach my $course (keys(%courses)) {
2795: if (ref($courses{$course}) eq 'HASH') {
2796: if ($courses{$course}{'inst_code'} ne '') {
2797: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2798: $totcodes ++;
2799: }
2800: }
2801: }
2802: return $totcodes;
1.1412 raeburn 2803: }
2804:
1.1311 raeburn 2805: sub course_portal_url {
2806: my ($cnum,$cdom) = @_;
2807: my $chome = &homeserver($cnum,$cdom);
2808: my $hostname = &hostname($chome);
2809: my $protocol = $protocol{$chome};
2810: $protocol = 'http' if ($protocol ne 'https');
2811: my %domdefaults = &get_domain_defaults($cdom);
2812: my $firsturl;
2813: if ($domdefaults{'portal_def'}) {
2814: $firsturl = $domdefaults{'portal_def'};
2815: } else {
2816: $firsturl = $protocol.'://'.$hostname;
2817: }
2818: return $firsturl;
2819: }
2820:
1.1407 raeburn 2821: # --------------------------------------------- Get domain config for passwords
2822:
2823: sub get_passwdconf {
2824: my ($dom) = @_;
2825: my (%passwdconf,$gotconf,$lookup);
2826: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2827: if (defined($cached)) {
2828: if (ref($result) eq 'HASH') {
2829: %passwdconf = %{$result};
2830: $gotconf = 1;
2831: }
2832: }
2833: unless ($gotconf) {
2834: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2835: if (ref($domconfig{'passwords'}) eq 'HASH') {
2836: %passwdconf = %{$domconfig{'passwords'}};
2837: }
2838: my $cachetime = 24*60*60;
2839: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2840: }
2841: return %passwdconf;
2842: }
2843:
1.344 www 2844: # --------------------------------------------------- Assign a key to a student
2845:
2846: sub assign_access_key {
1.364 www 2847: #
2848: # a valid key looks like uname:udom#comments
2849: # comments are being appended
2850: #
1.498 www 2851: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2852: $kdom=
1.620 albertel 2853: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2854: $knum=
1.620 albertel 2855: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2856: $cdom=
1.620 albertel 2857: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2858: $cnum=
1.620 albertel 2859: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2860: $udom=$env{'user.name'} unless (defined($udom));
2861: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2862: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2863: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2864: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2865: # assigned to this person
2866: # - this should not happen,
1.345 www 2867: # unless something went wrong
2868: # the first time around
2869: # ready to assign
1.364 www 2870: $logentry=$1.'; '.$logentry;
1.496 www 2871: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2872: $kdom,$knum) eq 'ok') {
1.345 www 2873: # key now belongs to user
1.346 www 2874: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2875: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2876: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2877: return 'ok';
2878: } else {
2879: return
2880: 'error: Count not permanently assign key, will need to be re-entered later.';
2881: }
2882: } else {
2883: return 'error: Could not assign key, try again later.';
2884: }
1.364 www 2885: } elsif (!$existing{$ckey}) {
1.345 www 2886: # the key does not exist
2887: return 'error: The key does not exist';
2888: } else {
2889: # the key is somebody else's
2890: return 'error: The key is already in use';
2891: }
1.344 www 2892: }
2893:
1.364 www 2894: # ------------------------------------------ put an additional comment on a key
2895:
2896: sub comment_access_key {
2897: #
2898: # a valid key looks like uname:udom#comments
2899: # comments are being appended
2900: #
2901: my ($ckey,$cdom,$cnum,$logentry)=@_;
2902: $cdom=
1.620 albertel 2903: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2904: $cnum=
1.620 albertel 2905: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2906: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2907: if ($existing{$ckey}) {
2908: $existing{$ckey}.='; '.$logentry;
2909: # ready to assign
1.367 www 2910: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2911: $cdom,$cnum) eq 'ok') {
2912: return 'ok';
2913: } else {
2914: return 'error: Count not store comment.';
2915: }
2916: } else {
2917: # the key does not exist
2918: return 'error: The key does not exist';
2919: }
2920: }
2921:
1.344 www 2922: # ------------------------------------------------------ Generate a set of keys
2923:
2924: sub generate_access_keys {
1.364 www 2925: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2926: $cdom=
1.620 albertel 2927: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2928: $cnum=
1.620 albertel 2929: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2930: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2931: unless (($cdom) && ($cnum)) { return 0; }
2932: if ($number>10000) { return 0; }
2933: sleep(2); # make sure don't get same seed twice
2934: srand(time()^($$+($$<<15))); # from "Programming Perl"
2935: my $total=0;
2936: for (my $i=1;$i<=$number;$i++) {
2937: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2938: sprintf("%lx",int(100000*rand)).'-'.
2939: sprintf("%lx",int(100000*rand));
2940: $newkey=~s/1/g/g; # folks mix up 1 and l
2941: $newkey=~s/0/h/g; # and also 0 and O
2942: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2943: if ($existing{$newkey}) {
2944: $i--;
2945: } else {
1.364 www 2946: if (&put('accesskeys',
2947: { $newkey => '# generated '.localtime().
1.620 albertel 2948: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2949: '; '.$logentry },
2950: $cdom,$cnum) eq 'ok') {
1.344 www 2951: $total++;
2952: }
2953: }
2954: }
1.620 albertel 2955: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2956: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2957: return $total;
2958: }
2959:
2960: # ------------------------------------------------------- Validate an accesskey
2961:
2962: sub validate_access_key {
2963: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2964: $cdom=
1.620 albertel 2965: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2966: $cnum=
1.620 albertel 2967: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2968: $udom=$env{'user.domain'} unless (defined($udom));
2969: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2970: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2971: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2972: }
2973:
2974: # ------------------------------------- Find the section of student in a course
1.652 albertel 2975: sub devalidate_getsection_cache {
2976: my ($udom,$unam,$courseid)=@_;
2977: my $hashid="$udom:$unam:$courseid";
2978: &devalidate_cache_new('getsection',$hashid);
2979: }
1.298 matthew 2980:
1.815 albertel 2981: sub courseid_to_courseurl {
2982: my ($courseid) = @_;
2983: #already url style courseid
2984: return $courseid if ($courseid =~ m{^/});
2985:
2986: if (exists($env{'course.'.$courseid.'.num'})) {
2987: my $cnum = $env{'course.'.$courseid.'.num'};
2988: my $cdom = $env{'course.'.$courseid.'.domain'};
2989: return "/$cdom/$cnum";
2990: }
2991:
2992: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2993: if (exists($courseinfo{'num'})) {
2994: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2995: }
2996:
2997: return undef;
2998: }
2999:
1.298 matthew 3000: sub getsection {
3001: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3002: my $cachetime=1800;
1.551 albertel 3003:
3004: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3005: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3006: if (defined($cached)) { return $result; }
3007:
1.298 matthew 3008: my %Pending;
3009: my %Expired;
3010: #
3011: # Each role can either have not started yet (pending), be active,
3012: # or have expired.
3013: #
3014: # If there is an active role, we are done.
3015: #
3016: # If there is more than one role which has not started yet,
3017: # choose the one which will start sooner
3018: # If there is one role which has not started yet, return it.
3019: #
3020: # If there is more than one expired role, choose the one which ended last.
3021: # If there is a role which has expired, return it.
3022: #
1.815 albertel 3023: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3024: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3025: foreach my $key (keys(%roleshash)) {
1.479 albertel 3026: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3027: my $section=$1;
3028: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3029: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3030: my $now=time;
1.548 albertel 3031: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3032: $Expired{$end}=$section;
3033: next;
3034: }
1.548 albertel 3035: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3036: $Pending{$start}=$section;
3037: next;
3038: }
1.599 albertel 3039: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3040: }
3041: #
3042: # Presumedly there will be few matching roles from the above
3043: # loop and the sorting time will be negligible.
3044: if (scalar(keys(%Pending))) {
3045: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3046: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3047: }
3048: if (scalar(keys(%Expired))) {
3049: my @sorted = sort {$a <=> $b} keys(%Expired);
3050: my $time = pop(@sorted);
1.599 albertel 3051: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3052: }
1.599 albertel 3053: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3054: }
1.70 www 3055:
1.599 albertel 3056: sub save_cache {
3057: &purge_remembered();
1.722 albertel 3058: #&Apache::loncommon::validate_page();
1.620 albertel 3059: undef(%env);
1.780 albertel 3060: undef($env_loaded);
1.599 albertel 3061: }
1.452 albertel 3062:
1.599 albertel 3063: my $to_remember=-1;
3064: my %remembered;
3065: my %accessed;
3066: my $kicks=0;
3067: my $hits=0;
1.849 albertel 3068: sub make_key {
3069: my ($name,$id) = @_;
1.872 albertel 3070: if (length($id) > 65
3071: && length(&escape($id)) > 200) {
3072: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3073: }
1.849 albertel 3074: return &escape($name.':'.$id);
3075: }
3076:
1.599 albertel 3077: sub devalidate_cache_new {
3078: my ($name,$id,$debug) = @_;
3079: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3080: my $remembered_id=$name.':'.$id;
1.849 albertel 3081: $id=&make_key($name,$id);
1.599 albertel 3082: $memcache->delete($id);
1.1319 damieng 3083: delete($remembered{$remembered_id});
3084: delete($accessed{$remembered_id});
1.599 albertel 3085: }
3086:
3087: sub is_cached_new {
3088: my ($name,$id,$debug) = @_;
1.1319 damieng 3089: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3090: if (exists($remembered{$remembered_id})) {
3091: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3092: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3093: $hits++;
1.1319 damieng 3094: return ($remembered{$remembered_id},1);
1.599 albertel 3095: }
1.1319 damieng 3096: $id=&make_key($name,$id);
1.599 albertel 3097: my $value = $memcache->get($id);
3098: if (!(defined($value))) {
3099: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3100: return (undef,undef);
1.416 albertel 3101: }
1.599 albertel 3102: if ($value eq '__undef__') {
3103: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3104: $value=undef;
3105: }
1.1319 damieng 3106: &make_room($remembered_id,$value,$debug);
1.599 albertel 3107: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3108: return ($value,1);
3109: }
3110:
3111: sub do_cache_new {
3112: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3113: my $remembered_id=$name.':'.$id;
1.849 albertel 3114: $id=&make_key($name,$id);
1.599 albertel 3115: my $setvalue=$value;
3116: if (!defined($setvalue)) {
3117: $setvalue='__undef__';
3118: }
1.623 albertel 3119: if (!defined($time) ) {
3120: $time=600;
3121: }
1.599 albertel 3122: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3123: my $result = $memcache->set($id,$setvalue,$time);
3124: if (! $result) {
1.872 albertel 3125: &logthis("caching of id -> $id failed");
1.910 albertel 3126: $memcache->disconnect_all();
1.872 albertel 3127: }
1.600 albertel 3128: # need to make a copy of $value
1.1319 damieng 3129: &make_room($remembered_id,$value,$debug);
1.599 albertel 3130: return $value;
3131: }
3132:
3133: sub make_room {
1.1319 damieng 3134: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3135:
1.1319 damieng 3136: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3137: : $value;
1.599 albertel 3138: if ($to_remember<0) { return; }
1.1319 damieng 3139: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3140: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3141: my $to_kick;
3142: my $max_time=0;
3143: foreach my $other (keys(%accessed)) {
3144: if (&tv_interval($accessed{$other}) > $max_time) {
3145: $to_kick=$other;
3146: $max_time=&tv_interval($accessed{$other});
3147: }
3148: }
3149: delete($remembered{$to_kick});
3150: delete($accessed{$to_kick});
3151: $kicks++;
3152: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3153: return;
3154: }
3155:
1.599 albertel 3156: sub purge_remembered {
1.604 albertel 3157: #&logthis("Tossing ".scalar(keys(%remembered)));
3158: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3159: undef(%remembered);
3160: undef(%accessed);
1.428 albertel 3161: }
1.70 www 3162: # ------------------------------------- Read an entry from a user's environment
3163:
3164: sub userenvironment {
3165: my ($udom,$unam,@what)=@_;
1.976 raeburn 3166: my $items;
3167: foreach my $item (@what) {
3168: $items.=&escape($item).'&';
3169: }
3170: $items=~s/\&$//;
1.70 www 3171: my %returnhash=();
1.1009 raeburn 3172: my $uhome = &homeserver($unam,$udom);
3173: unless ($uhome eq 'no_host') {
3174: my @answer=split(/\&/,
3175: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3176: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3177: return %returnhash;
3178: }
1.1009 raeburn 3179: my $i;
3180: for ($i=0;$i<=$#what;$i++) {
3181: $returnhash{$what[$i]}=&unescape($answer[$i]);
3182: }
1.70 www 3183: }
3184: return %returnhash;
1.1 albertel 3185: }
3186:
1.617 albertel 3187: # ---------------------------------------------------------- Get a studentphoto
3188: sub studentphoto {
3189: my ($udom,$unam,$ext) = @_;
3190: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3191: if (defined($env{'request.course.id'})) {
1.708 raeburn 3192: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3193: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3194: return(&retrievestudentphoto($udom,$unam,$ext));
3195: } else {
3196: my ($result,$perm_reqd)=
1.707 albertel 3197: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3198: if ($result eq 'ok') {
3199: if (!($perm_reqd eq 'yes')) {
3200: return(&retrievestudentphoto($udom,$unam,$ext));
3201: }
3202: }
3203: }
3204: }
3205: } else {
3206: my ($result,$perm_reqd) =
1.707 albertel 3207: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3208: if ($result eq 'ok') {
3209: if (!($perm_reqd eq 'yes')) {
3210: return(&retrievestudentphoto($udom,$unam,$ext));
3211: }
3212: }
3213: }
3214: return '/adm/lonKaputt/lonlogo_broken.gif';
3215: }
3216:
3217: sub retrievestudentphoto {
3218: my ($udom,$unam,$ext,$type) = @_;
3219: my $home=&Apache::lonnet::homeserver($unam,$udom);
3220: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3221: if ($ret eq 'ok') {
3222: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3223: if ($type eq 'thumbnail') {
3224: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3225: }
3226: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3227: return $tokenurl;
3228: } else {
3229: if ($type eq 'thumbnail') {
3230: return '/adm/lonKaputt/genericstudent_tn.gif';
3231: } else {
3232: return '/adm/lonKaputt/lonlogo_broken.gif';
3233: }
1.617 albertel 3234: }
3235: }
3236:
1.263 www 3237: # -------------------------------------------------------------------- New chat
3238:
3239: sub chatsend {
1.724 raeburn 3240: my ($newentry,$anon,$group)=@_;
1.620 albertel 3241: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3242: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3243: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3244: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3245: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3246: &escape($newentry)).':'.$group,$chome);
1.292 www 3247: }
3248:
3249: # ------------------------------------------ Find current version of a resource
3250:
3251: sub getversion {
3252: my $fname=&clutter(shift);
1.1189 raeburn 3253: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3254: return ¤tversion(&filelocation('',$fname));
3255: }
3256:
3257: sub currentversion {
3258: my $fname=shift;
3259: my $author=$fname;
3260: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3261: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3262: my $home=&homeserver($uname,$udom);
1.292 www 3263: if ($home eq 'no_host') {
3264: return -1;
3265: }
1.1112 www 3266: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3267: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3268: return -1;
3269: }
1.1112 www 3270: return $answer;
1.263 www 3271: }
3272:
1.1111 www 3273: #
3274: # Return special version number of resource if set by override, empty otherwise
3275: #
3276: sub usedversion {
3277: my $fname=shift;
3278: unless ($fname) { $fname=$env{'request.uri'}; }
3279: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3280: if ($urlversion) { return $urlversion; }
3281: return '';
3282: }
3283:
1.1 albertel 3284: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3285:
1.1 albertel 3286: sub subscribe {
3287: my $fname=shift;
1.761 raeburn 3288: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3289: $fname=~s/[\n\r]//g;
1.1 albertel 3290: my $author=$fname;
3291: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3292: my ($udom,$uname)=split(/\//,$author);
3293: my $home=homeserver($uname,$udom);
1.335 albertel 3294: if ($home eq 'no_host') {
3295: return 'not_found';
1.1 albertel 3296: }
3297: my $answer=reply("sub:$fname",$home);
1.64 www 3298: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3299: $answer.=' by '.$home;
3300: }
1.1 albertel 3301: return $answer;
3302: }
3303:
1.8 www 3304: # -------------------------------------------------------------- Replicate file
3305:
3306: sub repcopy {
3307: my $filename=shift;
1.23 www 3308: $filename=~s/\/+/\//g;
1.1142 raeburn 3309: my $londocroot = $perlvar{'lonDocRoot'};
3310: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3311: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3312: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3313: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3314: return &repcopy_userfile($filename);
3315: }
1.532 albertel 3316: $filename=~s/[\n\r]//g;
1.8 www 3317: my $transname="$filename.in.transfer";
1.828 www 3318: # FIXME: this should flock
1.607 raeburn 3319: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3320: my $remoteurl=subscribe($filename);
1.64 www 3321: if ($remoteurl =~ /^con_lost by/) {
3322: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3323: return 'unavailable';
1.8 www 3324: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3325: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3326: return 'not_found';
1.64 www 3327: } elsif ($remoteurl =~ /^rejected by/) {
3328: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3329: return 'forbidden';
1.20 www 3330: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3331: return 'ok';
1.8 www 3332: } else {
1.290 www 3333: my $author=$filename;
3334: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3335: my ($udom,$uname)=split(/\//,$author);
3336: my $home=homeserver($uname,$udom);
3337: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3338: my @parts=split(/\//,$filename);
3339: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3340: if ($path ne "$londocroot/res") {
1.8 www 3341: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3342: return 'bad_request';
1.8 www 3343: }
3344: my $count;
3345: for ($count=5;$count<$#parts;$count++) {
3346: $path.="/$parts[$count]";
3347: if ((-e $path)!=1) {
3348: mkdir($path,0777);
3349: }
3350: }
3351: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3352: my $response;
3353: if ($remoteurl =~ m{/raw/}) {
3354: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3355: } else {
3356: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3357: }
1.8 www 3358: if ($response->is_error()) {
3359: unlink($transname);
3360: my $message=$response->status_line;
1.672 albertel 3361: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3362: ." LWP get: $message: $filename</font>");
1.607 raeburn 3363: return 'unavailable';
1.8 www 3364: } else {
1.16 www 3365: if ($remoteurl!~/\.meta$/) {
3366: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3367: my $mresponse;
3368: if ($remoteurl =~ m{/raw/}) {
3369: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3370: } else {
3371: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3372: }
1.16 www 3373: if ($mresponse->is_error()) {
3374: unlink($filename.'.meta');
3375: &logthis(
1.672 albertel 3376: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3377: }
3378: }
1.8 www 3379: rename($transname,$filename);
1.607 raeburn 3380: return 'ok';
1.8 www 3381: }
1.290 www 3382: }
1.8 www 3383: }
1.330 www 3384: }
3385:
3386: # ------------------------------------------------ Get server side include body
3387: sub ssi_body {
1.381 albertel 3388: my ($filelink,%form)=@_;
1.606 matthew 3389: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3390: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3391: }
1.953 www 3392: my $output='';
3393: my $response;
1.980 raeburn 3394: if ($filelink=~/^https?\:/) {
1.954 raeburn 3395: ($output,$response)=&externalssi($filelink);
1.953 www 3396: } else {
1.1004 droeschl 3397: $filelink .= $filelink=~/\?/ ? '&' : '?';
3398: $filelink .= 'inhibitmenu=yes';
1.953 www 3399: ($output,$response)=&ssi($filelink,%form);
3400: }
1.778 albertel 3401: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3402: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3403: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3404: if (wantarray) {
3405: return ($output, $response);
3406: } else {
3407: return $output;
3408: }
1.8 www 3409: }
3410:
1.15 www 3411: # --------------------------------------------------------- Server Side Include
3412:
1.782 albertel 3413: sub absolute_url {
3414: my ($host_name) = @_;
3415: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3416: if ($host_name eq '') {
3417: $host_name = $ENV{'SERVER_NAME'};
3418: }
3419: return $protocol.$host_name;
3420: }
3421:
1.942 foxr 3422: #
3423: # Server side include.
3424: # Parameters:
3425: # fn Possibly encrypted resource name/id.
3426: # form Hash that describes how the rendering should be done
3427: # and other things.
1.944 foxr 3428: # Returns:
1.950 raeburn 3429: # Scalar context: The content of the response.
3430: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3431: #
1.15 www 3432: sub ssi {
3433:
1.944 foxr 3434: my ($fn,%form)=@_;
1.23 www 3435: my $request;
1.711 albertel 3436:
3437: $form{'no_update_last_known'}=1;
1.895 albertel 3438: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3439: if (%form) {
1.782 albertel 3440: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3441: $request->content(join('&',map {
3442: my $name = escape($_);
3443: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3444: ? join("&$name=", map {escape($_) } @{$form{$_}})
3445: : &escape($form{$_}) );
3446: } keys(%form)));
1.23 www 3447: } else {
1.782 albertel 3448: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3449: }
3450:
1.15 www 3451: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3452: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3453: my $islocal;
3454: if (($env{'request.course.id'}) &&
3455: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3456: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3457: ($form{'grade_symb'} ne '') &&
3458: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3459: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3460: $islocal = 1;
3461: }
1.1384 raeburn 3462: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385 raeburn 3463: '','','',$islocal);
1.1182 foxr 3464:
1.944 foxr 3465: if (wantarray) {
1.1345 raeburn 3466: return ($response->content, $response);
1.944 foxr 3467: } else {
1.1345 raeburn 3468: return $response->content;
1.942 foxr 3469: }
1.324 www 3470: }
3471:
3472: sub externalssi {
3473: my ($url)=@_;
3474: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3475: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3476: if (wantarray) {
3477: return ($response->content, $response);
3478: } else {
3479: return $response->content;
3480: }
1.15 www 3481: }
1.254 www 3482:
1.1354 raeburn 3483:
3484: # If the local copy of a replicated resource is outdated, trigger a
3485: # connection from the homeserver to flush the delayed queue. If no update
3486: # happens, remove local copies of outdated resource (and corresponding
3487: # metadata file).
3488:
1.1352 raeburn 3489: sub remove_stale_resfile {
3490: my ($url) = @_;
1.1354 raeburn 3491: my $removed;
1.1352 raeburn 3492: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3493: my $audom = $1;
3494: my $auname = $2;
1.1353 raeburn 3495: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3496: my $homeserver = &homeserver($auname,$audom);
3497: unless (($homeserver eq 'no_host') ||
3498: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3499: my $fname = &filelocation('',$url);
3500: if (-e $fname) {
3501: my $hostname = &hostname($homeserver);
3502: if ($hostname) {
1.1397 raeburn 3503: my $protocol = $protocol{$homeserver};
3504: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3505: my $uri = &declutter($url);
3506: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3507: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3508: if ($response->is_success()) {
3509: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3510: my $locmodtime = (stat($fname))[9];
3511: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3512: my $stale;
3513: my $answer = &reply('pong',$homeserver);
3514: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3515: sleep(0.2);
3516: $locmodtime = (stat($fname))[9];
3517: if ($locmodtime < $remmodtime) {
3518: my $posstransfer = $fname.'.in.transfer';
3519: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3520: $removed = 1;
3521: } else {
3522: $stale = 1;
3523: }
3524: } else {
3525: $removed = 1;
3526: }
3527: } else {
3528: $stale = 1;
3529: }
3530: if ($stale) {
3531: unlink($fname);
3532: if ($uri!~/\.meta$/) {
3533: unlink($fname.'.meta');
3534: }
3535: &reply("unsub:$fname",$homeserver);
3536: $removed = 1;
1.1352 raeburn 3537: }
3538: }
3539: }
3540: }
3541: }
3542: }
3543: }
3544: }
1.1354 raeburn 3545: return $removed;
1.1352 raeburn 3546: }
3547:
1.492 albertel 3548: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3549:
3550: sub allowuploaded {
3551: my ($srcurl,$url)=@_;
3552: $url=&clutter(&declutter($url));
3553: my $dir=$url;
3554: $dir=~s/\/[^\/]+$//;
3555: my %httpref=();
3556: my $httpurl=&hreflocation('',$url);
3557: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3558: &Apache::lonnet::appenv(\%httpref);
1.254 www 3559: }
1.477 raeburn 3560:
1.1193 raeburn 3561: #
3562: # Determine if the current user should be able to edit a particular resource,
3563: # when viewing in course context.
3564: # (a) When viewing resource used to determine if "Edit" item is included in
3565: # Functions.
3566: # (b) When displaying folder contents in course editor, used to determine if
3567: # "Edit" link will be displayed alongside resource.
3568: #
1.1196 raeburn 3569: # input: six args -- filename (decluttered), course number, course domain,
3570: # url, symb (if registered) and group (if this is a group
3571: # item -- e.g., bulletin board, group page etc.).
3572: # output: array of five scalars --
1.1193 raeburn 3573: # $cfile -- url for file editing if editable on current server
3574: # $home -- homeserver of resource (i.e., for author if published,
3575: # or course if uploaded.).
3576: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3577: # $forceedit -- 1 if icon/link should be to go to edit mode
3578: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3579: #
3580:
3581: sub can_edit_resource {
1.1194 raeburn 3582: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3583: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3584: #
3585: # For aboutme pages user can only edit his/her own.
3586: #
1.1199 raeburn 3587: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3588: my ($sdom,$sname) = ($1,$2);
3589: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3590: $home = $env{'user.home'};
3591: $cfile = $resurl;
3592: if ($env{'form.forceedit'}) {
3593: $forceview = 1;
3594: } else {
3595: $forceedit = 1;
3596: }
3597: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3598: } else {
3599: return;
3600: }
3601: }
3602:
3603: if ($env{'request.course.id'}) {
3604: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3605: if ($group ne '') {
3606: # if this is a group homepage or group bulletin board, check group privs
3607: my $allowed = 0;
1.1197 raeburn 3608: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3609: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3610: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3611: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3612: $allowed = 1;
3613: }
1.1197 raeburn 3614: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3615: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3616: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3617: $allowed = 1;
3618: }
3619: }
3620: if ($allowed) {
3621: $home=&homeserver($cnum,$cdom);
3622: if ($env{'form.forceedit'}) {
3623: $forceview = 1;
3624: } else {
3625: $forceedit = 1;
3626: }
3627: $cfile = $resurl;
3628: } else {
3629: return;
3630: }
3631: } else {
1.1208 raeburn 3632: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3633: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3634: return;
3635: }
3636: } elsif (!$crsedit) {
1.1194 raeburn 3637: #
3638: # No edit allowed where CC has switched to student role.
3639: #
3640: return;
3641: }
3642: }
3643: }
3644:
1.1193 raeburn 3645: if ($file ne '') {
3646: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3647: if (&is_course_upload($file,$cnum,$cdom)) {
3648: $uploaded = 1;
3649: $incourse = 1;
1.1193 raeburn 3650: if ($file =~/\.(htm|html|css|js|txt)$/) {
3651: $cfile = &hreflocation('',$file);
1.1201 raeburn 3652: if ($env{'form.forceedit'}) {
3653: $forceview = 1;
3654: } else {
3655: $forceedit = 1;
3656: }
1.1194 raeburn 3657: }
3658: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3659: $incourse = 1;
3660: if ($env{'form.forceedit'}) {
3661: $forceview = 1;
3662: } else {
3663: $forceedit = 1;
3664: }
3665: $cfile = $resurl;
3666: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3667: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3668: $incourse = 1;
3669: if ($env{'form.forceedit'}) {
3670: $forceview = 1;
3671: } else {
3672: $forceedit = 1;
3673: }
3674: $cfile = $resurl;
1.1199 raeburn 3675: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3676: $incourse = 1;
3677: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3678: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3679: $incourse = 1;
1.1199 raeburn 3680: if ($env{'form.forceedit'}) {
3681: $forceview = 1;
3682: } else {
3683: $forceedit = 1;
3684: }
3685: $cfile = $resurl;
1.1419 raeburn 3686: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3687: my ($map,$id,$res) = &decode_symb($symb);
3688: if ($map =~ /\.page$/) {
3689: $incourse = 1;
3690: if ($env{'form.forceedit'}) {
3691: $forceview = 1;
3692: $cfile = $map;
3693: } else {
3694: $forceedit = 1;
3695: $cfile = '/adm/wrapper'.$resurl;
3696: }
3697: }
1.1343 raeburn 3698: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3699: $incourse = 1;
3700: if ($env{'form.forceedit'}) {
3701: $forceview = 1;
3702: } else {
3703: $forceedit = 1;
3704: }
3705: $cfile = $resurl;
1.1208 raeburn 3706: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3707: $incourse = 1;
3708: if ($env{'form.forceedit'}) {
3709: $forceview = 1;
3710: } else {
3711: $forceedit = 1;
3712: }
3713: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3714: }
3715: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3716: my $template = '/res/lib/templates/simpleproblem.problem';
3717: if (&is_on_map($template)) {
3718: $incourse = 1;
3719: $forceview = 1;
3720: $cfile = $template;
1.1193 raeburn 3721: }
1.1199 raeburn 3722: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3723: $incourse = 1;
3724: if ($env{'form.forceedit'}) {
3725: $forceview = 1;
3726: } else {
3727: $forceedit = 1;
3728: }
3729: $cfile = $resurl;
1.1343 raeburn 3730: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3731: $incourse = 1;
3732: if ($env{'form.forceedit'}) {
3733: $forceview = 1;
3734: } else {
3735: $forceedit = 1;
3736: }
3737: $cfile = $resurl;
1.1199 raeburn 3738: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3739: $incourse = 1;
3740: $forceview = 1;
3741: if ($symb) {
3742: my ($map,$id,$res)=&decode_symb($symb);
3743: $env{'request.symb'} = $symb;
3744: $cfile = &clutter($res);
3745: } else {
3746: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3747: my $escfile = &unescape($cfile);
1.1343 raeburn 3748: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3749: $cfile = '/adm/wrapper'.$escfile;
3750: } else {
3751: $escfile =~ s{^http://}{};
3752: $cfile = &escape("/adm/wrapper/ext/$escfile");
3753: }
1.1199 raeburn 3754: }
1.1234 raeburn 3755: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3756: if ($env{'form.forceedit'}) {
3757: $forceview = 1;
3758: } else {
3759: $forceedit = 1;
3760: }
3761: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3762: }
3763: }
1.1194 raeburn 3764: if ($uploaded || $incourse) {
3765: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3766: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3767: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3768: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3769: # Check that the user has permission to edit this resource
3770: my $setpriv = 1;
3771: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3772: if (defined($cfudom)) {
3773: $home=&homeserver($cfuname,$cfudom);
3774: $cfile=$file;
3775: }
3776: }
1.1194 raeburn 3777: if (($cfile ne '') && (!$incourse || $uploaded) &&
3778: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3779: my @ids=¤t_machine_ids();
3780: unless (grep(/^\Q$home\E$/,@ids)) {
3781: $switchserver=1;
3782: }
3783: }
3784: }
1.1194 raeburn 3785: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3786: }
3787:
3788: sub is_course_upload {
3789: my ($file,$cnum,$cdom) = @_;
3790: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3791: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3792: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3793: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3794: return 1;
3795: }
3796: return;
3797: }
3798:
1.1194 raeburn 3799: sub in_course {
1.1195 raeburn 3800: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3801: if ($hideprivileged) {
3802: my $skipuser;
1.1219 raeburn 3803: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3804: my @possdoms = ($cdom);
3805: if ($coursehash{'checkforpriv'}) {
3806: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3807: }
3808: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3809: $skipuser = 1;
3810: if ($coursehash{'nothideprivileged'}) {
3811: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3812: my $user;
3813: if ($item =~ /:/) {
3814: $user = $item;
3815: } else {
3816: $user = join(':',split(/[\@]/,$item));
3817: }
3818: if ($user eq $uname.':'.$udom) {
3819: undef($skipuser);
3820: last;
3821: }
3822: }
3823: }
3824: if ($skipuser) {
3825: return 0;
3826: }
3827: }
3828: }
1.1194 raeburn 3829: $type ||= 'any';
3830: if (!defined($cdom) || !defined($cnum)) {
3831: my $cid = $env{'request.course.id'};
3832: $cdom = $env{'course.'.$cid.'.domain'};
3833: $cnum = $env{'course.'.$cid.'.num'};
3834: }
3835: my $typesref;
1.1195 raeburn 3836: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3837: $typesref = ['active','previous','future'];
3838: } elsif ($type eq 'previous' || $type eq 'future') {
3839: $typesref = [$type];
3840: }
3841: my %roles = &get_my_roles($uname,$udom,'userroles',
3842: $typesref,undef,[$cdom]);
3843: my ($tmp) = keys(%roles);
3844: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3845: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3846: if (@course_roles > 0) {
3847: return 1;
3848: }
3849: return 0;
3850: }
3851:
1.478 albertel 3852: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3853: # input: action, courseID, current domain, intended
1.637 raeburn 3854: # path to file, source of file, instruction to parse file for objects,
3855: # ref to hash for embedded objects,
3856: # ref to hash for codebase of java objects.
1.1095 raeburn 3857: # reference to scalar to accommodate mime type determined
3858: # from File::MMagic if $parser = parse.
1.637 raeburn 3859: #
1.485 raeburn 3860: # output: url to file (if action was uploaddoc),
3861: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3862: #
1.478 albertel 3863: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3864: # course.
1.477 raeburn 3865: #
1.478 albertel 3866: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3867: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3868: # course's home server.
1.477 raeburn 3869: #
1.478 albertel 3870: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3871: # be copied from $source (current location) to
3872: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3873: # and will then be copied to
3874: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3875: # course's home server.
1.485 raeburn 3876: #
1.481 raeburn 3877: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3878: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3879: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3880: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3881: # in course's home server.
1.637 raeburn 3882: #
1.477 raeburn 3883:
3884: sub process_coursefile {
1.1095 raeburn 3885: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3886: $mimetype)=@_;
1.477 raeburn 3887: my $fetchresult;
1.638 albertel 3888: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3889: if ($action eq 'propagate') {
1.638 albertel 3890: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3891: $home);
1.481 raeburn 3892: } else {
1.477 raeburn 3893: my $fpath = '';
3894: my $fname = $file;
1.478 albertel 3895: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3896: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3897: my $filepath = &build_filepath($fpath);
1.481 raeburn 3898: if ($action eq 'copy') {
3899: if ($source eq '') {
3900: $fetchresult = 'no source file';
3901: return $fetchresult;
3902: } else {
3903: my $destination = $filepath.'/'.$fname;
3904: rename($source,$destination);
3905: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3906: $home);
1.481 raeburn 3907: }
3908: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 3909: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3910: print $fh $env{'form.'.$source};
1.481 raeburn 3911: close($fh);
1.637 raeburn 3912: if ($parser eq 'parse') {
1.1024 raeburn 3913: my $mm = new File::MMagic;
1.1095 raeburn 3914: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3915: if ($type eq 'text/html') {
1.1024 raeburn 3916: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3917: unless ($parse_result eq 'ok') {
3918: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3919: }
1.637 raeburn 3920: }
1.1095 raeburn 3921: if (ref($mimetype)) {
3922: $$mimetype = $type;
3923: }
1.637 raeburn 3924: }
1.477 raeburn 3925: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3926: $home);
1.481 raeburn 3927: if ($fetchresult eq 'ok') {
3928: return '/uploaded/'.$fpath.'/'.$fname;
3929: } else {
3930: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3931: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3932: return '/adm/notfound.html';
3933: }
1.477 raeburn 3934: }
3935: }
1.485 raeburn 3936: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3937: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3938: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3939: }
3940: return $fetchresult;
3941: }
3942:
1.637 raeburn 3943: sub build_filepath {
3944: my ($fpath) = @_;
3945: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3946: unless ($fpath eq '') {
3947: my @parts=split('/',$fpath);
3948: foreach my $part (@parts) {
3949: $filepath.= '/'.$part;
3950: if ((-e $filepath)!=1) {
3951: mkdir($filepath,0777);
3952: }
3953: }
3954: }
3955: return $filepath;
3956: }
3957:
3958: sub store_edited_file {
1.638 albertel 3959: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3960: my $file = $primary_url;
3961: $file =~ s#^/uploaded/$docudom/$docuname/##;
3962: my $fpath = '';
3963: my $fname = $file;
3964: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3965: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3966: my $filepath = &build_filepath($fpath);
1.1359 raeburn 3967: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3968: print $fh $content;
3969: close($fh);
1.638 albertel 3970: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3971: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3972: $home);
1.637 raeburn 3973: if ($$fetchresult eq 'ok') {
3974: return '/uploaded/'.$fpath.'/'.$fname;
3975: } else {
1.638 albertel 3976: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3977: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3978: return '/adm/notfound.html';
3979: }
3980: }
3981:
1.531 albertel 3982: sub clean_filename {
1.831 albertel 3983: my ($fname,$args)=@_;
1.315 www 3984: # Replace Windows backslashes by forward slashes
1.257 www 3985: $fname=~s/\\/\//g;
1.831 albertel 3986: if (!$args->{'keep_path'}) {
3987: # Get rid of everything but the actual filename
3988: $fname=~s/^.*\/([^\/]+)$/$1/;
3989: }
1.315 www 3990: # Replace spaces by underscores
3991: $fname=~s/\s+/\_/g;
1.1406 raeburn 3992: # Transliterate non-ascii text to ascii
3993: my $lang = &Apache::lonlocal::current_language();
3994: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3995: # Replace all other weird characters by nothing
1.831 albertel 3996: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3997: # Replace all .\d. sequences with _\d. so they no longer look like version
3998: # numbers
3999: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 4000: return $fname;
4001: }
1.1406 raeburn 4002:
1.1051 raeburn 4003: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4004: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4005: # image with the same aspect ratio as the original, but with dimensions which do
4006: # not exceed $resizewidth and $resizeheight.
4007:
1.984 neumanie 4008: sub resizeImage {
1.1051 raeburn 4009: my ($img_path,$resizewidth,$resizeheight) = @_;
4010: my $ima = Image::Magick->new;
4011: my $resized;
4012: if (-e $img_path) {
4013: $ima->Read($img_path);
4014: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4015: my $width = $ima->Get('width');
4016: my $height = $ima->Get('height');
4017: if ($width > $resizewidth) {
4018: my $factor = $width/$resizewidth;
4019: my $newheight = $height/$factor;
4020: $ima->Scale(width=>$resizewidth,height=>$newheight);
4021: $resized = 1;
4022: }
4023: }
4024: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4025: my $width = $ima->Get('width');
4026: my $height = $ima->Get('height');
4027: if ($height > $resizeheight) {
4028: my $factor = $height/$resizeheight;
4029: my $newwidth = $width/$factor;
4030: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4031: $resized = 1;
4032: }
4033: }
4034: if ($resized) {
4035: $ima->Write($img_path);
4036: }
4037: }
4038: return;
1.977 amueller 4039: }
4040:
1.608 albertel 4041: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4042: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4043: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4044: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4045: # canceloverwrite, scantron or ''.
1.1090 raeburn 4046: # if 'coursedoc': upload to the current course
4047: # if 'existingfile': write file to tmp/overwrites directory
4048: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4049: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4050: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4051: # $parser - instruction to parse file for objects ($parser = parse) or
4052: # if context is 'scantron', $parser is hashref of csv column mapping
4053: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4054: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4055: # $allfiles - reference to hash for embedded objects
4056: # $codebase - reference to hash for codebase of java objects
4057: # $desuname - username for permanent storage of uploaded file
4058: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4059: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4060: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4061: # $resizewidth - width (pixels) to which to resize uploaded image
4062: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4063: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4064: # from File::MMagic.
1.858 raeburn 4065: #
1.686 albertel 4066: # output: url of file in userspace, or error: <message>
4067: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4068:
1.531 albertel 4069: sub userfileupload {
1.1090 raeburn 4070: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4071: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4072: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4073: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4074: $fname=&clean_filename($fname);
1.1090 raeburn 4075: # See if there is anything left
1.257 www 4076: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4077: # If filename now begins with a . prepend unix timestamp _ milliseconds
4078: if ($fname =~ /^\./) {
4079: my ($s,$usec) = &gettimeofday();
4080: while (length($usec) < 6) {
4081: $usec = '0'.$usec;
4082: }
4083: $fname = $s.'_'.substr($usec,0,3).$fname;
4084: }
1.1090 raeburn 4085: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4086: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4087: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4088: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4089: my $now = time;
1.1090 raeburn 4090: my $filepath;
1.1095 raeburn 4091: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4092: $filepath = 'tmp/helprequests/'.$now;
4093: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4094: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4095: '_'.$env{'user.domain'}.'/pending';
4096: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4097: my ($docuname,$docudom);
1.1350 raeburn 4098: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4099: $docudom = $destudom;
4100: } else {
4101: $docudom = $env{'user.domain'};
4102: }
1.1350 raeburn 4103: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4104: $docuname = $destuname;
4105: } else {
4106: $docuname = $env{'user.name'};
4107: }
4108: if (exists($env{'form.group'})) {
4109: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4110: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4111: }
4112: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4113: if ($context eq 'canceloverwrite') {
4114: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4115: if (-e $tempfile) {
4116: my @info = stat($tempfile);
4117: if ($info[9] eq $env{'form.timestamp'}) {
4118: unlink($tempfile);
4119: }
4120: }
4121: return;
1.523 raeburn 4122: }
4123: }
1.1090 raeburn 4124: # Create the directory if not present
1.741 raeburn 4125: my @parts=split(/\//,$filepath);
4126: my $fullpath = $perlvar{'lonDaemons'};
4127: for (my $i=0;$i<@parts;$i++) {
4128: $fullpath .= '/'.$parts[$i];
4129: if ((-e $fullpath)!=1) {
4130: mkdir($fullpath,0777);
4131: }
4132: }
1.1359 raeburn 4133: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4134: print $fh $env{'form.'.$formname};
4135: close($fh);
1.1090 raeburn 4136: if ($context eq 'existingfile') {
4137: my @info = stat($fullpath.'/'.$fname);
4138: return ($fullpath.'/'.$fname,$info[9]);
4139: } else {
4140: return $fullpath.'/'.$fname;
4141: }
1.523 raeburn 4142: }
1.995 raeburn 4143: if ($subdir eq 'scantron') {
4144: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4145: } else {
1.995 raeburn 4146: $fname="$subdir/$fname";
4147: }
1.1090 raeburn 4148: if ($context eq 'coursedoc') {
1.638 albertel 4149: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4150: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4151: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4152: return &finishuserfileupload($docuname,$docudom,
4153: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4154: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4155: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4156: } else {
1.1218 raeburn 4157: if ($env{'form.folder'}) {
4158: $fname=$env{'form.folder'}.'/'.$fname;
4159: }
1.638 albertel 4160: return &process_coursefile('uploaddoc',$docuname,$docudom,
4161: $fname,$formname,$parser,
1.1095 raeburn 4162: $allfiles,$codebase,$mimetype);
1.481 raeburn 4163: }
1.719 banghart 4164: } elsif (defined($destuname)) {
4165: my $docuname=$destuname;
4166: my $docudom=$destudom;
1.860 raeburn 4167: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4168: $parser,$allfiles,$codebase,
1.1051 raeburn 4169: $thumbwidth,$thumbheight,
1.1095 raeburn 4170: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4171: } else {
1.638 albertel 4172: my $docuname=$env{'user.name'};
4173: my $docudom=$env{'user.domain'};
1.1220 raeburn 4174: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4175: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4176: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4177: }
1.860 raeburn 4178: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4179: $parser,$allfiles,$codebase,
1.1051 raeburn 4180: $thumbwidth,$thumbheight,
1.1095 raeburn 4181: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4182: }
1.271 www 4183: }
4184:
4185: sub finishuserfileupload {
1.860 raeburn 4186: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4187: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4188: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4189: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4190:
1.860 raeburn 4191: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4192: $file=$fname;
4193: if ($fname=~m|/|) {
4194: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4195: $path.=$fnamepath.'/';
4196: }
1.259 www 4197: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4198: my $count;
4199: for ($count=4;$count<=$#parts;$count++) {
4200: $filepath.="/$parts[$count]";
4201: if ((-e $filepath)!=1) {
4202: mkdir($filepath,0777);
4203: }
4204: }
1.984 neumanie 4205:
1.258 www 4206: # Save the file
4207: {
1.1359 raeburn 4208: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4209: &logthis('Failed to create '.$filepath.'/'.$file);
4210: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4211: return '/adm/notfound.html';
4212: }
1.1090 raeburn 4213: if ($context eq 'overwrite') {
1.1117 foxr 4214: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4215: my $target = $filepath.'/'.$file;
4216: if (-e $source) {
4217: my @info = stat($source);
4218: if ($info[9] eq $env{'form.timestamp'}) {
4219: unless (&File::Copy::move($source,$target)) {
4220: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4221: return "Moving from $source failed";
4222: }
4223: } else {
4224: return "Temporary file: $source had unexpected date/time for last modification";
4225: }
4226: } else {
4227: return "Temporary file: $source missing";
4228: }
4229: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4230: &logthis('Failed to write to '.$filepath.'/'.$file);
4231: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4232: return '/adm/notfound.html';
4233: }
1.570 albertel 4234: close(FH);
1.1051 raeburn 4235: if ($resizewidth && $resizeheight) {
4236: my $mm = new File::MMagic;
4237: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4238: if ($mime_type =~ m{^image/}) {
4239: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4240: }
1.977 amueller 4241: }
1.258 www 4242: }
1.1152 raeburn 4243: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4244: if (ref($mimetype)) {
4245: if ($$mimetype eq '') {
4246: my $mm = new File::MMagic;
4247: my $type = $mm->checktype_filename($filepath.'/'.$file);
4248: $$mimetype = $type;
4249: }
4250: }
4251: }
1.1401 raeburn 4252: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4253: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4254: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4255: $allfiles,$codebase);
4256: unless ($parse_result eq 'ok') {
4257: &logthis('Failed to parse '.$filepath.$file.
4258: ' for embedded media: '.$parse_result);
4259: }
1.637 raeburn 4260: }
1.1401 raeburn 4261: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4262: my $format = $env{'form.scantron_format'};
4263: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4264: }
1.860 raeburn 4265: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4266: my $input = $filepath.'/'.$file;
4267: my $output = $filepath.'/'.'tn-'.$file;
4268: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4269: my @args = ('convert','-sample',$thumbsize,$input,$output);
4270: system({$args[0]} @args);
1.860 raeburn 4271: if (-e $filepath.'/'.'tn-'.$file) {
4272: $fetchthumb = 1;
4273: }
4274: }
1.858 raeburn 4275:
1.259 www 4276: # Notify homeserver to grep it
4277: #
1.984 neumanie 4278: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4279: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4280: if ($fetchresult eq 'ok') {
1.860 raeburn 4281: if ($fetchthumb) {
4282: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4283: if ($thumbresult ne 'ok') {
4284: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4285: $docuhome.': '.$thumbresult);
4286: }
4287: }
1.259 www 4288: #
1.258 www 4289: # Return the URL to it
1.494 albertel 4290: return '/uploaded/'.$path.$file;
1.263 www 4291: } else {
1.494 albertel 4292: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4293: ': '.$fetchresult);
1.263 www 4294: return '/adm/notfound.html';
1.858 raeburn 4295: }
1.493 albertel 4296: }
4297:
1.637 raeburn 4298: sub extract_embedded_items {
1.961 raeburn 4299: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4300: my @state = ();
1.1164 raeburn 4301: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4302: my %javafiles = (
4303: codebase => '',
4304: code => '',
4305: archive => ''
4306: );
4307: my %mediafiles = (
4308: src => '',
4309: movie => '',
4310: );
1.648 raeburn 4311: my $p;
4312: if ($content) {
4313: $p = HTML::LCParser->new($content);
4314: } else {
1.961 raeburn 4315: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4316: }
1.641 albertel 4317: while (my $t=$p->get_token()) {
1.640 albertel 4318: if ($t->[0] eq 'S') {
4319: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4320: push(@state, $tagname);
1.648 raeburn 4321: if (lc($tagname) eq 'allow') {
4322: &add_filetype($allfiles,$attr->{'src'},'src');
4323: }
1.640 albertel 4324: if (lc($tagname) eq 'img') {
4325: &add_filetype($allfiles,$attr->{'src'},'src');
4326: }
1.886 albertel 4327: if (lc($tagname) eq 'a') {
1.1222 raeburn 4328: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4329: &add_filetype($allfiles,$attr->{'href'},'href');
4330: }
1.886 albertel 4331: }
1.645 raeburn 4332: if (lc($tagname) eq 'script') {
1.1164 raeburn 4333: my $src;
1.645 raeburn 4334: if ($attr->{'archive'} =~ /\.jar$/i) {
4335: &add_filetype($allfiles,$attr->{'archive'},'archive');
4336: } else {
1.1164 raeburn 4337: if ($attr->{'src'} ne '') {
4338: $src = $attr->{'src'};
4339: &add_filetype($allfiles,$src,'src');
4340: }
4341: }
4342: my $text = $p->get_trimmed_text();
4343: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4344: my @swfargs = split(/,/,$1);
4345: foreach my $item (@swfargs) {
4346: $item =~ s/["']//g;
4347: $item =~ s/^\s+//;
4348: $item =~ s/\s+$//;
4349: }
4350: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4351: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4352: push(@{$related{$swfargs[0]}},$swfargs[2]);
4353: } else {
4354: $related{$swfargs[0]} = [$swfargs[2]];
4355: }
4356: }
1.645 raeburn 4357: }
4358: }
4359: if (lc($tagname) eq 'link') {
4360: if (lc($attr->{'rel'}) eq 'stylesheet') {
4361: &add_filetype($allfiles,$attr->{'href'},'href');
4362: }
4363: }
1.640 albertel 4364: if (lc($tagname) eq 'object' ||
4365: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4366: foreach my $item (keys(%javafiles)) {
4367: $javafiles{$item} = '';
4368: }
1.1164 raeburn 4369: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4370: $lastids{lc($tagname)} = $attr->{'id'};
4371: }
1.640 albertel 4372: }
4373: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4374: my $name = lc($attr->{'name'});
4375: foreach my $item (keys(%javafiles)) {
4376: if ($name eq $item) {
4377: $javafiles{$item} = $attr->{'value'};
4378: last;
4379: }
4380: }
1.1164 raeburn 4381: my $pathfrom;
1.640 albertel 4382: foreach my $item (keys(%mediafiles)) {
4383: if ($name eq $item) {
1.1164 raeburn 4384: $pathfrom = $attr->{'value'};
4385: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4386: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4387: last;
4388: }
4389: }
1.1164 raeburn 4390: if ($name eq 'flashvars') {
4391: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4392: }
4393: if ($pathfrom ne '') {
4394: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4395: $pathfrom);
4396: }
1.640 albertel 4397: }
4398: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4399: foreach my $item (keys(%javafiles)) {
4400: if ($attr->{$item}) {
4401: $javafiles{$item} = $attr->{$item};
4402: last;
4403: }
4404: }
4405: foreach my $item (keys(%mediafiles)) {
4406: if ($attr->{$item}) {
4407: &add_filetype($allfiles,$attr->{$item},$item);
4408: last;
4409: }
4410: }
1.1164 raeburn 4411: if (lc($tagname) eq 'embed') {
4412: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4413: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4414: $attr->{'src'});
4415: }
4416: }
1.640 albertel 4417: }
1.1243 raeburn 4418: if (lc($tagname) eq 'iframe') {
4419: my $src = $attr->{'src'} ;
4420: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4421: &add_filetype($allfiles,$src,'src');
4422: } elsif ($src =~ m{^/}) {
4423: if ($env{'request.course.id'}) {
4424: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4425: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4426: my $url = &hreflocation('',$fullpath);
4427: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4428: my $relpath = $1;
4429: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4430: &add_filetype($allfiles,$1,'src');
4431: }
4432: }
4433: }
4434: }
4435: }
1.1164 raeburn 4436: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4437: pop(@state);
1.1164 raeburn 4438: }
1.640 albertel 4439: } elsif ($t->[0] eq 'E') {
4440: my ($tagname) = ($t->[1]);
4441: if ($javafiles{'codebase'} ne '') {
4442: $javafiles{'codebase'} .= '/';
4443: }
4444: if (lc($tagname) eq 'applet' ||
4445: lc($tagname) eq 'object' ||
4446: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4447: ) {
4448: foreach my $item (keys(%javafiles)) {
4449: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4450: my $file=$javafiles{'codebase'}.$javafiles{$item};
4451: &add_filetype($allfiles,$file,$item);
4452: }
4453: }
4454: }
4455: pop @state;
4456: }
4457: }
1.1164 raeburn 4458: foreach my $id (sort(keys(%flashvars))) {
4459: if ($shockwave{$id} ne '') {
4460: my @pairs = split(/\&/,$flashvars{$id});
4461: foreach my $pair (@pairs) {
4462: my ($key,$value) = split(/\=/,$pair);
4463: if ($key eq 'thumb') {
4464: &add_filetype($allfiles,$value,$key);
4465: } elsif ($key eq 'content') {
4466: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4467: my ($ext) = ($value =~ /\.([^.]+)$/);
4468: if ($ext ne '') {
4469: &add_filetype($allfiles,$path.$value,$ext);
4470: }
4471: }
4472: }
4473: }
4474: }
1.637 raeburn 4475: return 'ok';
4476: }
4477:
1.639 albertel 4478: sub add_filetype {
4479: my ($allfiles,$file,$type)=@_;
4480: if (exists($allfiles->{$file})) {
4481: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4482: push(@{$allfiles->{$file}}, &escape($type));
4483: }
4484: } else {
4485: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4486: }
4487: }
4488:
1.1164 raeburn 4489: sub embedded_dependency {
4490: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4491: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4492: if (($identifier ne '') &&
4493: (ref($related->{$identifier}) eq 'ARRAY') &&
4494: ($pathfrom ne '')) {
4495: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4496: foreach my $dep (@{$related->{$identifier}}) {
4497: &add_filetype($allfiles,$path.$dep,'object');
4498: }
4499: }
4500: }
4501: return;
4502: }
4503:
1.1401 raeburn 4504: sub bubblesheet_converter {
4505: my ($cdom,$fullpath,$config,$format) = @_;
4506: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4507: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4508: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4509: my (%csvcols,%csvoptions);
4510: if (ref($config->{'fields'}) eq 'HASH') {
4511: %csvcols = %{$config->{'fields'}};
4512: }
4513: if (ref($config->{'options'}) eq 'HASH') {
4514: %csvoptions = %{$config->{'options'}};
4515: }
1.1401 raeburn 4516: my %csvbynum = reverse(%csvcols);
4517: my %scantronconf = &get_scantron_config($format,$cdom);
4518: if (keys(%scantronconf)) {
4519: my %bynum = (
4520: $scantronconf{CODEstart} => 'CODEstart',
4521: $scantronconf{IDstart} => 'IDstart',
4522: $scantronconf{PaperID} => 'PaperID',
4523: $scantronconf{FirstName} => 'FirstName',
4524: $scantronconf{LastName} => 'LastName',
4525: $scantronconf{Qstart} => 'Qstart',
4526: );
4527: my @ordered;
4528: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4529: push(@ordered,$bynum{$item});
1.1401 raeburn 4530: }
4531: my %mapstart = (
4532: CODEstart => 'CODE',
4533: IDstart => 'ID',
4534: PaperID => 'PaperID',
4535: FirstName => 'FirstName',
4536: LastName => 'LastName',
4537: Qstart => 'FirstQuestion',
4538: );
4539: my %maplength = (
4540: CODEstart => 'CODElength',
4541: IDstart => 'IDlength',
4542: PaperID => 'PaperIDlength',
4543: FirstName => 'FirstNamelength',
4544: LastName => 'LastNamelength',
4545: );
4546: if (open(my $fh,'<',$fullpath)) {
4547: my $output;
1.1403 raeburn 4548: my %lettdig = &letter_to_digits();
4549: my %diglett = reverse(%lettdig);
4550: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4551: my $num = 0;
1.1401 raeburn 4552: while (my $line=<$fh>) {
1.1404 raeburn 4553: $num ++;
4554: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4555: $line =~ s{[\r\n]+$}{};
4556: my %found;
4557: my @values = split(/,/,$line);
4558: my ($qstart,$record);
4559: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4560: if ((($qstart ne '') && ($i > $qstart)) ||
4561: ($csvbynum{$i} eq 'FirstQuestion')) {
4562: if ($values[$i] eq '') {
4563: $values[$i] = $scantronconf{'Qoff'};
4564: } elsif ($scantronconf{'Qon'} eq 'number') {
4565: if ($values[$i] =~ /^[A-Ja-j]$/) {
4566: $values[$i] = $lettdig{uc($values[$i])};
4567: }
4568: } elsif ($scantronconf{'Qon'} eq 'letter') {
4569: if ($values[$i] =~ /^[0-9]$/) {
4570: $values[$i] = $diglett{$values[$i]};
4571: }
4572: } else {
4573: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4574: my $digit;
4575: if ($values[$i] =~ /^[A-Ja-j]$/) {
4576: $digit = $lettdig{uc($values[$i])}-1;
4577: if ($values[$i] eq 'J') {
4578: $digit += $numletts;
4579: }
4580: } elsif ($values[$i] =~ /^[0-9]$/) {
4581: $digit = $values[$i]-1;
4582: if ($values[$i] eq '0') {
4583: $digit += $numletts;
4584: }
4585: }
4586: my $qval='';
4587: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4588: if ($j == $digit) {
4589: $qval .= $scantronconf{'Qon'};
4590: } else {
4591: $qval .= $scantronconf{'Qoff'};
4592: }
4593: }
4594: $values[$i] = $qval;
4595: }
4596: }
4597: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4598: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4599: }
4600: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4601: if ($numblank > 0) {
4602: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4603: }
1.1401 raeburn 4604: if ($csvbynum{$i} eq 'FirstQuestion') {
4605: $qstart = $i;
1.1403 raeburn 4606: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4607: } else {
1.1403 raeburn 4608: $found{'FirstQuestion'} .= $values[$i];
4609: }
4610: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4611: if ($csvoptions{'rem'}) {
4612: $values[$i] =~ s/^\s+//;
4613: }
4614: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4615: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4616: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4617: }
4618: }
4619: $found{$csvbynum{$i}} = $values[$i];
4620: }
4621: }
4622: foreach my $item (@ordered) {
4623: my $currlength = 1+length($record);
4624: my $numspaces = $scantronconf{$item} - $currlength;
4625: if ($numspaces > 0) {
4626: $record .= (' ' x $numspaces);
4627: }
4628: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4629: unless ($item eq 'Qstart') {
4630: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4631: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4632: }
4633: }
4634: $record .= $found{$mapstart{$item}};
4635: }
4636: }
4637: $output .= "$record\n";
4638: }
4639: close($fh);
4640: if ($output) {
4641: if (open(my $fh,'>',$fullpath)) {
4642: print $fh $output;
4643: close($fh);
4644: }
4645: }
4646: }
4647: }
4648: return;
4649: }
4650: }
4651:
1.1403 raeburn 4652: sub letter_to_digits {
4653: my %lettdig = (
4654: A => 1,
4655: B => 2,
4656: C => 3,
4657: D => 4,
4658: E => 5,
4659: F => 6,
4660: G => 7,
4661: H => 8,
4662: I => 9,
4663: J => 0,
4664: );
4665: return %lettdig;
4666: }
4667:
1.1401 raeburn 4668: sub get_scantron_config {
4669: my ($which,$cdom) = @_;
4670: my @lines = &get_scantronformat_file($cdom);
4671: my %config;
4672: #FIXME probably should move to XML it has already gotten a bit much now
4673: foreach my $line (@lines) {
4674: my ($name,$descrip)=split(/:/,$line);
4675: if ($name ne $which ) { next; }
4676: chomp($line);
4677: my @config=split(/:/,$line);
4678: $config{'name'}=$config[0];
4679: $config{'description'}=$config[1];
4680: $config{'CODElocation'}=$config[2];
4681: $config{'CODEstart'}=$config[3];
4682: $config{'CODElength'}=$config[4];
4683: $config{'IDstart'}=$config[5];
4684: $config{'IDlength'}=$config[6];
4685: $config{'Qstart'}=$config[7];
4686: $config{'Qlength'}=$config[8];
4687: $config{'Qoff'}=$config[9];
4688: $config{'Qon'}=$config[10];
4689: $config{'PaperID'}=$config[11];
4690: $config{'PaperIDlength'}=$config[12];
4691: $config{'FirstName'}=$config[13];
4692: $config{'FirstNamelength'}=$config[14];
4693: $config{'LastName'}=$config[15];
4694: $config{'LastNamelength'}=$config[16];
4695: $config{'BubblesPerRow'}=$config[17];
4696: last;
4697: }
4698: return %config;
4699: }
4700:
4701: sub get_scantronformat_file {
4702: my ($cdom) = @_;
4703: if ($cdom eq '') {
4704: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4705: }
4706: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4707: my $gottab = 0;
4708: my @lines;
4709: if (ref($domconfig{'scantron'}) eq 'HASH') {
4710: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4711: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4712: if ($formatfile ne '-1') {
4713: @lines = split("\n",$formatfile,-1);
4714: $gottab = 1;
4715: }
4716: }
4717: }
4718: if (!$gottab) {
4719: my $confname = $cdom.'-domainconfig';
4720: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4721: my $formatfile = &getfile($default);
4722: if ($formatfile ne '-1') {
4723: @lines = split("\n",$formatfile,-1);
4724: $gottab = 1;
4725: }
4726: }
4727: if (!$gottab) {
4728: my @domains = ¤t_machine_domains();
4729: if (grep(/^\Q$cdom\E$/,@domains)) {
4730: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4731: @lines = <$fh>;
4732: close($fh);
1.1403 raeburn 4733: }
1.1401 raeburn 4734: } else {
4735: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4736: @lines = <$fh>;
4737: close($fh);
4738: }
4739: }
4740: }
4741: return @lines;
4742: }
4743:
1.493 albertel 4744: sub removeuploadedurl {
1.984 neumanie 4745: my ($url)=@_;
4746: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4747: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4748: }
4749:
4750: sub removeuserfile {
4751: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4752: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4753: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4754: if ($result eq 'ok') {
1.798 raeburn 4755: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4756: my $metafile = $fname.'.meta';
4757: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4758: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4759: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4760: my $sqlresult =
1.823 albertel 4761: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4762: 'portfolio_metadata',$group,
4763: 'delete');
1.798 raeburn 4764: }
4765: }
4766: return $result;
1.257 www 4767: }
1.15 www 4768:
1.530 albertel 4769: sub mkdiruserfile {
4770: my ($docuname,$docudom,$dir)=@_;
4771: my $home=&homeserver($docuname,$docudom);
4772: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4773: }
4774:
1.531 albertel 4775: sub renameuserfile {
4776: my ($docuname,$docudom,$old,$new)=@_;
4777: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4778: my $result = &reply("renameuserfile:$docudom:$docuname:".
4779: &escape("$old").':'.&escape("$new"),$home);
4780: if ($result eq 'ok') {
4781: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4782: my $oldmeta = $old.'.meta';
4783: my $newmeta = $new.'.meta';
4784: my $metaresult =
4785: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4786: my $url = "/uploaded/$docudom/$docuname/$old";
4787: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4788: my $sqlresult =
1.823 albertel 4789: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4790: 'portfolio_metadata',$group,
4791: 'delete');
1.798 raeburn 4792: }
4793: }
4794: return $result;
1.531 albertel 4795: }
4796:
1.14 www 4797: # ------------------------------------------------------------------------- Log
4798:
4799: sub log {
4800: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4801: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4802: }
4803:
4804: # ------------------------------------------------------------------ Course Log
1.352 www 4805: #
4806: # This routine flushes several buffers of non-mission-critical nature
4807: #
1.157 www 4808:
4809: sub flushcourselogs {
1.352 www 4810: &logthis('Flushing log buffers');
4811: #
4812: # course logs
4813: # This is a log of all transactions in a course, which can be used
4814: # for data mining purposes
4815: #
4816: # It also collects the courseid database, which lists last transaction
4817: # times and course titles for all courseids
4818: #
4819: my %courseidbuffer=();
1.921 raeburn 4820: foreach my $crsid (keys(%courselogs)) {
1.352 www 4821: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4822: &escape($courselogs{$crsid}),
4823: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4824: delete $courselogs{$crsid};
4825: } else {
4826: &logthis('Failed to flush log buffer for '.$crsid);
4827: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4828: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4829: " exceeded maximum size, deleting.</font>");
4830: delete $courselogs{$crsid};
4831: }
1.352 www 4832: }
1.920 raeburn 4833: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4834: 'description' => $coursedescrbuf{$crsid},
4835: 'inst_code' => $courseinstcodebuf{$crsid},
4836: 'type' => $coursetypebuf{$crsid},
4837: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4838: };
1.191 harris41 4839: }
1.352 www 4840: #
4841: # Write course id database (reverse lookup) to homeserver of courses
4842: # Is used in pickcourse
4843: #
1.840 albertel 4844: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4845: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4846: $courseidbuffer{$crs_home},
4847: $crs_home,'timeonly');
1.352 www 4848: }
4849: #
4850: # File accesses
4851: # Writes to the dynamic metadata of resources to get hit counts, etc.
4852: #
1.449 matthew 4853: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4854: if ($entry =~ /___count$/) {
4855: my ($dom,$name);
1.807 albertel 4856: ($dom,$name,undef)=
1.811 albertel 4857: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4858: if (! defined($dom) || $dom eq '' ||
4859: ! defined($name) || $name eq '') {
1.620 albertel 4860: my $cid = $env{'request.course.id'};
4861: $dom = $env{'request.'.$cid.'.domain'};
4862: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4863: }
1.450 matthew 4864: my $value = $accesshash{$entry};
4865: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4866: my %temphash=($url => $value);
1.449 matthew 4867: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4868: if ($result eq 'ok') {
4869: delete $accesshash{$entry};
4870: }
4871: } else {
1.811 albertel 4872: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4873: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4874: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4875: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4876: delete $accesshash{$entry};
4877: }
1.185 www 4878: }
1.191 harris41 4879: }
1.352 www 4880: #
4881: # Roles
4882: # Reverse lookup of user roles for course faculty/staff and co-authorship
4883: #
1.800 albertel 4884: foreach my $entry (keys(%userrolehash)) {
1.351 www 4885: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4886: split(/\:/,$entry);
4887: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4888: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4889: $rudom,$runame) eq 'ok') {
4890: delete $userrolehash{$entry};
4891: }
4892: }
1.662 raeburn 4893: #
1.1334 raeburn 4894: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4895: #
4896: my %domrolebuffer = ();
1.1000 raeburn 4897: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4898: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4899: if ($domrolebuffer{$rudom}) {
4900: $domrolebuffer{$rudom}.='&'.&escape($entry).
4901: '='.&escape($domainrolehash{$entry});
4902: } else {
4903: $domrolebuffer{$rudom}.=&escape($entry).
4904: '='.&escape($domainrolehash{$entry});
4905: }
4906: delete $domainrolehash{$entry};
4907: }
4908: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4909: my %servers;
4910: if (defined(&domain($dom,'primary'))) {
4911: my $primary=&domain($dom,'primary');
4912: my $hostname=&hostname($primary);
4913: $servers{$primary} = $hostname;
4914: } else {
4915: %servers = &get_servers($dom,'library');
4916: }
1.841 albertel 4917: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4918: if (&reply('domroleput:'.$dom.':'.
4919: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4920: last;
4921: } else {
1.841 albertel 4922: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4923: }
1.662 raeburn 4924: }
4925: }
1.186 www 4926: $dumpcount++;
1.157 www 4927: }
4928:
4929: sub courselog {
4930: my $what=shift;
1.158 www 4931: $what=time.':'.$what;
1.620 albertel 4932: unless ($env{'request.course.id'}) { return ''; }
4933: $coursedombuf{$env{'request.course.id'}}=
4934: $env{'course.'.$env{'request.course.id'}.'.domain'};
4935: $coursenumbuf{$env{'request.course.id'}}=
4936: $env{'course.'.$env{'request.course.id'}.'.num'};
4937: $coursehombuf{$env{'request.course.id'}}=
4938: $env{'course.'.$env{'request.course.id'}.'.home'};
4939: $coursedescrbuf{$env{'request.course.id'}}=
4940: $env{'course.'.$env{'request.course.id'}.'.description'};
4941: $courseinstcodebuf{$env{'request.course.id'}}=
4942: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4943: $courseownerbuf{$env{'request.course.id'}}=
4944: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4945: $coursetypebuf{$env{'request.course.id'}}=
4946: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4947: if (defined $courselogs{$env{'request.course.id'}}) {
4948: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4949: } else {
1.620 albertel 4950: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4951: }
1.620 albertel 4952: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4953: &flushcourselogs();
4954: }
1.158 www 4955: }
4956:
4957: sub courseacclog {
4958: my $fnsymb=shift;
1.620 albertel 4959: unless ($env{'request.course.id'}) { return ''; }
4960: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4961: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4962: $what.=':POST';
1.583 matthew 4963: # FIXME: Probably ought to escape things....
1.800 albertel 4964: foreach my $key (keys(%env)) {
4965: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4966: my $formitem = $1;
4967: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4968: $what.=':'.$formitem.'='.$env{$key};
4969: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4970: $what.=':'.$formitem.'='.$env{$key};
4971: }
1.158 www 4972: }
1.191 harris41 4973: }
1.583 matthew 4974: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4975: # FIXME: We should not be depending on a form parameter that someone
4976: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4977: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4978: $what.= ':POST';
4979: # FIXME: Probably ought to escape things....
4980: foreach my $element ('courseexp','crsfulltext','crsrelated',
4981: 'crsdiscuss') {
1.620 albertel 4982: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4983: }
4984: }
1.158 www 4985: }
4986: &courselog($what);
1.149 www 4987: }
4988:
1.185 www 4989: sub countacc {
4990: my $url=&declutter(shift);
1.458 matthew 4991: return if (! defined($url) || $url eq '');
1.620 albertel 4992: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4993: #
4994: # Mark that this url was used in this course
4995: #
1.620 albertel 4996: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4997: #
4998: # Increase the access count for this resource in this child process
4999: #
1.281 www 5000: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5001: $accesshash{$key}++;
1.185 www 5002: }
1.349 www 5003:
1.361 www 5004: sub linklog {
5005: my ($from,$to)=@_;
5006: $from=&declutter($from);
5007: $to=&declutter($to);
5008: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5009: $accesshash{$to.'___'.$from.'___goto'}=1;
5010: }
1.1160 www 5011:
5012: sub statslog {
5013: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5014: if ($users<2) { return; }
5015: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5016: 'course' => $env{'request.course.id'},
5017: 'sections' => '"all"',
5018: 'num_students' => $users,
5019: 'part' => $part,
5020: 'symb' => $symb,
5021: 'mean_tries' => $av_attempts,
5022: 'deg_of_diff' => $degdiff});
5023: foreach my $key (keys(%dynstore)) {
5024: $accesshash{$key}=$dynstore{$key};
5025: }
5026: }
1.361 www 5027:
1.349 www 5028: sub userrolelog {
5029: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5030: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5031: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5032: $userrolehash
5033: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5034: =$tend.':'.$tstart;
1.662 raeburn 5035: }
1.1169 droeschl 5036: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5037: $userrolehash
5038: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5039: =$tend.':'.$tstart;
5040: }
1.1334 raeburn 5041: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5042: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5043: $domainrolehash
5044: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5045: = $tend.':'.$tstart;
5046: }
1.351 www 5047: }
5048:
1.957 raeburn 5049: sub courserolelog {
5050: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5051: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5052: my $cdom = $1;
5053: my $cnum = $2;
5054: my $sec = $3;
5055: my $namespace = 'rolelog';
5056: my %storehash = (
5057: role => $trole,
5058: start => $tstart,
5059: end => $tend,
5060: selfenroll => $selfenroll,
5061: context => $context,
5062: );
5063: if ($trole eq 'gr') {
5064: $namespace = 'groupslog';
5065: $storehash{'group'} = $sec;
5066: } else {
5067: $storehash{'section'} = $sec;
5068: }
1.1188 raeburn 5069: &write_log('course',$namespace,\%storehash,$delflag,$username,
5070: $domain,$cnum,$cdom);
1.1184 raeburn 5071: if (($trole ne 'st') || ($sec ne '')) {
5072: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5073: }
5074: }
5075: return;
5076: }
5077:
1.1184 raeburn 5078: sub domainrolelog {
5079: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5080: if ($area =~ m{^/($match_domain)/$}) {
5081: my $cdom = $1;
5082: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5083: my $namespace = 'rolelog';
5084: my %storehash = (
5085: role => $trole,
5086: start => $tstart,
5087: end => $tend,
5088: context => $context,
5089: );
1.1188 raeburn 5090: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5091: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5092: }
5093: return;
5094:
5095: }
5096:
5097: sub coauthorrolelog {
5098: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5099: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5100: my $audom = $1;
5101: my $auname = $2;
5102: my $namespace = 'rolelog';
5103: my %storehash = (
5104: role => $trole,
5105: start => $tstart,
5106: end => $tend,
5107: context => $context,
5108: );
1.1188 raeburn 5109: &write_log('author',$namespace,\%storehash,$delflag,$username,
5110: $domain,$auname,$audom);
1.1184 raeburn 5111: }
5112: return;
5113: }
5114:
1.351 www 5115: sub get_course_adv_roles {
1.948 raeburn 5116: my ($cid,$codes) = @_;
1.620 albertel 5117: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5118: my %coursehash=&coursedescription($cid);
1.988 raeburn 5119: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5120: my %nothide=();
1.800 albertel 5121: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5122: if ($user !~ /:/) {
5123: $nothide{join(':',split(/[\@]/,$user))}=1;
5124: } else {
5125: $nothide{$user}=1;
5126: }
1.470 www 5127: }
1.1219 raeburn 5128: my @possdoms = ($coursehash{'domain'});
5129: if ($coursehash{'checkforpriv'}) {
5130: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5131: }
1.351 www 5132: my %returnhash=();
5133: my %dumphash=
5134: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5135: my $now=time;
1.997 raeburn 5136: my %privileged;
1.1000 raeburn 5137: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5138: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5139: if (($tstart) && ($tstart<0)) { next; }
5140: if (($tend) && ($tend<$now)) { next; }
5141: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5142: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5143: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5144: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5145: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5146: if ($role eq 'cr') { next; }
1.948 raeburn 5147: if ($codes) {
5148: if ($section) { $role .= ':'.$section; }
5149: if ($returnhash{$role}) {
5150: $returnhash{$role}.=','.$username.':'.$domain;
5151: } else {
5152: $returnhash{$role}=$username.':'.$domain;
5153: }
1.351 www 5154: } else {
1.988 raeburn 5155: my $key=&plaintext($role,$crstype);
1.973 bisitz 5156: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5157: if ($returnhash{$key}) {
5158: $returnhash{$key}.=','.$username.':'.$domain;
5159: } else {
5160: $returnhash{$key}=$username.':'.$domain;
5161: }
1.351 www 5162: }
1.948 raeburn 5163: }
1.400 www 5164: return %returnhash;
5165: }
5166:
5167: sub get_my_roles {
1.937 raeburn 5168: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5169: unless (defined($uname)) { $uname=$env{'user.name'}; }
5170: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5171: my (%dumphash,%nothide);
1.1086 raeburn 5172: if ($context eq 'userroles') {
1.1166 raeburn 5173: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5174: } else {
1.1219 raeburn 5175: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5176: if ($hidepriv) {
5177: my %coursehash=&coursedescription($udom.'_'.$uname);
5178: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5179: if ($user !~ /:/) {
5180: $nothide{join(':',split(/[\@]/,$user))} = 1;
5181: } else {
5182: $nothide{$user} = 1;
5183: }
5184: }
5185: }
1.858 raeburn 5186: }
1.400 www 5187: my %returnhash=();
5188: my $now=time;
1.999 raeburn 5189: my %privileged;
1.800 albertel 5190: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5191: my ($role,$tend,$tstart);
5192: if ($context eq 'userroles') {
1.1149 raeburn 5193: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5194: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5195: } else {
5196: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5197: }
1.400 www 5198: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5199: my $status = 'active';
1.939 raeburn 5200: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5201: $status = 'previous';
5202: }
5203: if (($tstart) && ($now<$tstart)) {
5204: $status = 'future';
5205: }
5206: if (ref($types) eq 'ARRAY') {
5207: if (!grep(/^\Q$status\E$/,@{$types})) {
5208: next;
5209: }
5210: } else {
5211: if ($status ne 'active') {
5212: next;
5213: }
5214: }
1.867 raeburn 5215: my ($rolecode,$username,$domain,$section,$area);
5216: if ($context eq 'userroles') {
1.1186 raeburn 5217: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5218: (undef,$domain,$username,$section) = split(/\//,$area);
5219: } else {
5220: ($role,$username,$domain,$section) = split(/\:/,$entry);
5221: }
1.832 raeburn 5222: if (ref($roledoms) eq 'ARRAY') {
5223: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5224: next;
5225: }
5226: }
5227: if (ref($roles) eq 'ARRAY') {
5228: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5229: if ($role =~ /^cr\//) {
5230: if (!grep(/^cr$/,@{$roles})) {
5231: next;
5232: }
1.1104 raeburn 5233: } elsif ($role =~ /^gr\//) {
5234: if (!grep(/^gr$/,@{$roles})) {
5235: next;
5236: }
1.922 raeburn 5237: } else {
5238: next;
5239: }
1.832 raeburn 5240: }
1.867 raeburn 5241: }
1.937 raeburn 5242: if ($hidepriv) {
1.1219 raeburn 5243: my @privroles = ('dc','su');
1.999 raeburn 5244: if ($context eq 'userroles') {
1.1219 raeburn 5245: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5246: } else {
1.1219 raeburn 5247: my $possdoms = [$domain];
5248: if (ref($roledoms) eq 'ARRAY') {
5249: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5250: }
1.1219 raeburn 5251: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5252: if (!$nothide{$username.':'.$domain}) {
5253: next;
5254: }
5255: }
1.937 raeburn 5256: }
5257: }
1.933 raeburn 5258: if ($withsec) {
5259: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5260: $tstart.':'.$tend;
5261: } else {
5262: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5263: }
1.832 raeburn 5264: }
1.373 www 5265: return %returnhash;
1.399 www 5266: }
5267:
1.1333 raeburn 5268: sub get_all_adhocroles {
5269: my ($dom) = @_;
5270: my @roles_by_num = ();
5271: my %domdefaults = &get_domain_defaults($dom);
5272: my (%description,%access_in_dom,%access_info);
5273: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5274: my $count = 0;
5275: my %domcurrent = %{$domdefaults{'adhocroles'}};
5276: my %ordered;
5277: foreach my $role (sort(keys(%domcurrent))) {
5278: my ($order,$desc,$access_in_dom);
5279: if (ref($domcurrent{$role}) eq 'HASH') {
5280: $order = $domcurrent{$role}{'order'};
5281: $desc = $domcurrent{$role}{'desc'};
5282: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5283: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5284: }
5285: if ($order eq '') {
5286: $order = $count;
5287: }
5288: $ordered{$order} = $role;
5289: if ($desc ne '') {
5290: $description{$role} = $desc;
5291: } else {
5292: $description{$role}= $role;
5293: }
5294: $count++;
5295: }
5296: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5297: push(@roles_by_num,$ordered{$item});
5298: }
5299: }
5300: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5301: }
5302:
1.1332 raeburn 5303: sub get_my_adhocroles {
1.1333 raeburn 5304: my ($cid,$checkreg) = @_;
5305: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5306: if ($env{'request.course.id'} eq $cid) {
5307: $cdom = $env{'course.'.$cid.'.domain'};
5308: $cnum = $env{'course.'.$cid.'.num'};
5309: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5310: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5311: $cdom = $1;
5312: $cnum = $2;
5313: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5314: $cdom,$cnum);
5315: }
5316: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5317: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5318: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5319: if ($rosterhash{$user} ne '') {
5320: my $type = (split(/:/,$rosterhash{$user}))[5];
5321: return ([],{}) if ($type eq 'auto');
5322: }
5323: }
5324: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5325: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5326: my $then=$env{'user.login.time'};
5327: my $update=$env{'user.update.time'};
1.1335 raeburn 5328: if (!$update) {
5329: $update = $then;
5330: }
5331: my @liveroles;
1.1334 raeburn 5332: foreach my $role ('dh','da') {
5333: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5334: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5335: my $limit = $update;
5336: if ($env{'request.role'} eq "$role./$cdom/") {
5337: $limit = $then;
5338: }
1.1335 raeburn 5339: my $activerole = 1;
5340: if ($tstart && $tstart>$limit) { $activerole = 0; }
5341: if ($tend && $tend <$limit) { $activerole = 0; }
5342: if ($activerole) {
5343: push(@liveroles,$role);
5344: }
1.1334 raeburn 5345: }
1.1332 raeburn 5346: }
1.1335 raeburn 5347: if (@liveroles) {
1.1332 raeburn 5348: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5349: my ($accessref,$accessinfo,%access_in_dom);
5350: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5351: if (ref($roles_by_num) eq 'ARRAY') {
5352: if (@{$roles_by_num}) {
1.1332 raeburn 5353: my %settings;
5354: if ($env{'request.course.id'} eq $cid) {
5355: foreach my $envkey (keys(%env)) {
5356: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5357: $settings{$1} = $env{$envkey};
5358: }
5359: }
5360: } else {
5361: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5362: }
5363: my %setincrs;
5364: if ($settings{'internal.adhocaccess'}) {
5365: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5366: }
5367: my @statuses;
5368: if ($env{'environment.inststatus'}) {
5369: @statuses = split(/,/,$env{'environment.inststatus'});
5370: }
5371: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5372: if (ref($accessref) eq 'HASH') {
5373: %access_in_dom = %{$accessref};
5374: }
5375: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5376: my ($curraccess,@okstatus,@personnel);
5377: if ($setincrs{$role}) {
5378: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5379: if ($curraccess eq 'status') {
5380: @okstatus = split(/\&/,$rest);
5381: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5382: @personnel = split(/\&/,$rest);
5383: }
5384: } else {
5385: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5386: if (ref($accessinfo) eq 'HASH') {
5387: if ($curraccess eq 'status') {
5388: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5389: @okstatus = @{$accessinfo->{$role}};
5390: }
5391: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5392: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5393: @personnel = @{$accessinfo->{$role}};
5394: }
1.1332 raeburn 5395: }
5396: }
5397: }
5398: if ($curraccess eq 'none') {
5399: next;
5400: } elsif ($curraccess eq 'all') {
5401: push(@possroles,$role);
1.1336 raeburn 5402: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5403: if (grep(/^dh$/,@liveroles)) {
5404: push(@possroles,$role);
5405: } else {
5406: next;
5407: }
1.1336 raeburn 5408: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5409: if (grep(/^da$/,@liveroles)) {
5410: push(@possroles,$role);
5411: } else {
5412: next;
5413: }
1.1332 raeburn 5414: } elsif ($curraccess eq 'status') {
5415: if (@okstatus) {
5416: if (!@statuses) {
5417: if (grep(/^default$/,@okstatus)) {
5418: push(@possroles,$role);
5419: }
5420: } else {
5421: foreach my $status (@okstatus) {
5422: if (grep(/^\Q$status\E$/,@statuses)) {
5423: push(@possroles,$role);
5424: last;
5425: }
5426: }
5427: }
5428: }
5429: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5430: if (grep(/^\Q$user\E$/,@personnel)) {
5431: if ($curraccess eq 'exc') {
5432: push(@possroles,$role);
5433: }
5434: } elsif ($curraccess eq 'inc') {
5435: push(@possroles,$role);
5436: }
5437: }
5438: }
5439: }
5440: }
5441: }
5442: }
5443: }
5444: }
1.1333 raeburn 5445: unless (ref($description) eq 'HASH') {
5446: if (ref($roles_by_num) eq 'ARRAY') {
5447: my %desc;
5448: map { $desc{$_} = $_; } (@{$roles_by_num});
5449: $description = \%desc;
5450: } else {
5451: $description = {};
5452: }
5453: }
5454: return (\@possroles,$description);
1.1332 raeburn 5455: }
5456:
1.399 www 5457: # ----------------------------------------------------- Frontpage Announcements
5458: #
5459: #
5460:
5461: sub postannounce {
5462: my ($server,$text)=@_;
1.844 albertel 5463: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5464: unless ($text=~/\w/) { $text=''; }
5465: return &reply('setannounce:'.&escape($text),$server);
5466: }
5467:
5468: sub getannounce {
1.448 albertel 5469:
1.1359 raeburn 5470: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5471: my $announcement='';
1.800 albertel 5472: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5473: close($fh);
1.399 www 5474: if ($announcement=~/\w/) {
5475: return
5476: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5477: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5478: } else {
5479: return '';
5480: }
5481: } else {
5482: return '';
5483: }
1.351 www 5484: }
1.353 www 5485:
5486: # ---------------------------------------------------------- Course ID routines
5487: # Deal with domain's nohist_courseid.db files
5488: #
5489:
5490: sub courseidput {
1.921 raeburn 5491: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5492: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5493: my $outcome;
5494: if ($caller eq 'timeonly') {
5495: my $cids = '';
5496: foreach my $item (keys(%$storehash)) {
5497: $cids.=&escape($item).'&';
5498: }
5499: $cids=~s/\&$//;
5500: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5501: $coursehome);
5502: } else {
5503: my $items = '';
5504: foreach my $item (keys(%$storehash)) {
5505: $items.= &escape($item).'='.
5506: &freeze_escape($$storehash{$item}).'&';
5507: }
5508: $items=~s/\&$//;
5509: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5510: $coursehome);
1.918 raeburn 5511: }
5512: if ($outcome eq 'unknown_cmd') {
5513: my $what;
5514: foreach my $cid (keys(%$storehash)) {
5515: $what .= &escape($cid).'=';
1.921 raeburn 5516: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5517: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5518: }
5519: $what =~ s/\:$/&/;
5520: }
5521: $what =~ s/\&$//;
5522: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5523: } else {
5524: return $outcome;
5525: }
1.353 www 5526: }
5527:
5528: sub courseiddump {
1.921 raeburn 5529: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5530: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5531: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5532: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5533: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5534: my $as_hash = 1;
5535: my %returnhash;
5536: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5537: my %libserv = &all_library();
5538: foreach my $tryserver (keys(%libserv)) {
5539: if ( ( $hostidflag == 1
5540: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5541: || (!defined($hostidflag)) ) {
5542:
1.918 raeburn 5543: if (($domfilter eq '') ||
5544: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5545: my $rep;
5546: if (grep { $_ eq $tryserver } current_machine_ids()) {
5547: $rep = LONCAPA::Lond::dump_course_id_handler(
5548: join(":", (&host_domain($tryserver), $sincefilter,
5549: &escape($descfilter), &escape($instcodefilter),
5550: &escape($ownerfilter), &escape($coursefilter),
5551: &escape($typefilter), &escape($regexp_ok),
5552: $as_hash, &escape($selfenrollonly),
5553: &escape($catfilter), $showhidden, $caller,
5554: &escape($cloner), &escape($cc_clone), $cloneonly,
5555: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5556: &escape($creationcontext),$domcloner,$hasuniquecode,
5557: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5558: } else {
5559: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5560: $sincefilter.':'.&escape($descfilter).':'.
5561: &escape($instcodefilter).':'.&escape($ownerfilter).
5562: ':'.&escape($coursefilter).':'.&escape($typefilter).
5563: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5564: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5565: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5566: &escape($cc_clone).':'.$cloneonly.':'.
5567: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5568: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5569: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5570: }
5571:
1.918 raeburn 5572: my @pairs=split(/\&/,$rep);
5573: foreach my $item (@pairs) {
5574: my ($key,$value)=split(/\=/,$item,2);
5575: $key = &unescape($key);
5576: next if ($key =~ /^error: 2 /);
5577: my $result = &thaw_unescape($value);
5578: if (ref($result) eq 'HASH') {
5579: $returnhash{$key}=$result;
5580: } else {
1.921 raeburn 5581: my @responses = split(/:/,$value);
5582: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5583: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5584: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5585: }
1.1008 raeburn 5586: }
1.353 www 5587: }
5588: }
5589: }
5590: }
5591: return %returnhash;
5592: }
5593:
1.1055 raeburn 5594: sub courselastaccess {
5595: my ($cdom,$cnum,$hostidref) = @_;
5596: my %returnhash;
5597: if ($cdom && $cnum) {
5598: my $chome = &homeserver($cnum,$cdom);
5599: if ($chome ne 'no_host') {
5600: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5601: &extract_lastaccess(\%returnhash,$rep);
5602: }
5603: } else {
5604: if (!$cdom) { $cdom=''; }
5605: my %libserv = &all_library();
5606: foreach my $tryserver (keys(%libserv)) {
5607: if (ref($hostidref) eq 'ARRAY') {
5608: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5609: }
5610: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5611: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5612: &extract_lastaccess(\%returnhash,$rep);
5613: }
5614: }
5615: }
5616: return %returnhash;
5617: }
5618:
5619: sub extract_lastaccess {
5620: my ($returnhash,$rep) = @_;
5621: if (ref($returnhash) eq 'HASH') {
5622: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5623: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5624: $rep eq '') {
5625: my @pairs=split(/\&/,$rep);
5626: foreach my $item (@pairs) {
5627: my ($key,$value)=split(/\=/,$item,2);
5628: $key = &unescape($key);
5629: next if ($key =~ /^error: 2 /);
5630: $returnhash->{$key} = &thaw_unescape($value);
5631: }
5632: }
5633: }
5634: return;
5635: }
5636:
1.658 raeburn 5637: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5638:
5639: sub dcmailput {
1.685 raeburn 5640: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5641: my $status = &Apache::lonnet::critical(
1.740 www 5642: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5643: &escape($message),$server);
1.662 raeburn 5644: return $status;
5645: }
5646:
1.658 raeburn 5647: sub dcmaildump {
5648: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5649: my %returnhash=();
1.846 albertel 5650:
5651: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5652: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5653: &escape($enddate).':';
5654: my @esc_senders=map { &escape($_)} @$senders;
5655: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5656: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5657: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5658: if (($key) && ($value)) {
5659: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5660: }
5661: }
5662: }
5663: return %returnhash;
5664: }
1.662 raeburn 5665: # ---------------------------------------------------------- Domain roles
5666:
5667: sub get_domain_roles {
5668: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5669: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5670: $startdate = '.';
5671: }
1.1018 raeburn 5672: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5673: $enddate = '.';
5674: }
1.922 raeburn 5675: my $rolelist;
5676: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5677: $rolelist = join('&',@{$roles});
1.922 raeburn 5678: }
1.662 raeburn 5679: my %personnel = ();
1.841 albertel 5680:
5681: my %servers = &get_servers($dom,'library');
5682: foreach my $tryserver (keys(%servers)) {
5683: %{$personnel{$tryserver}}=();
5684: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5685: &escape($startdate).':'.
5686: &escape($enddate).':'.
5687: &escape($rolelist), $tryserver))) {
5688: my ($key,$value) = split(/\=/,$line,2);
5689: if (($key) && ($value)) {
5690: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5691: }
5692: }
1.662 raeburn 5693: }
5694: return %personnel;
5695: }
1.658 raeburn 5696:
1.1332 raeburn 5697: sub get_active_domroles {
5698: my ($dom,$roles) = @_;
5699: return () unless (ref($roles) eq 'ARRAY');
5700: my $now = time;
5701: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5702: my %domroles;
5703: foreach my $server (keys(%dompersonnel)) {
5704: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5705: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5706: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5707: }
5708: }
5709: return %domroles;
5710: }
5711:
1.1057 www 5712: # ----------------------------------------------------------- Interval timing
1.149 www 5713:
1.1153 www 5714: {
5715: # Caches needed for speedup of navmaps
5716: # We don't want to cache this for very long at all (5 seconds at most)
5717: #
5718: # The user for whom we cache
5719: my $cachedkey='';
5720: # The cached times for this user
5721: my %cachedtimes=();
5722: # When this was last done
1.1282 raeburn 5723: my $cachedtime='';
1.1153 www 5724:
5725: sub load_all_first_access {
1.1308 raeburn 5726: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5727: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5728: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5729: (!$ignorecache)) {
1.1154 raeburn 5730: return;
5731: }
5732: $cachedtime=time;
5733: $cachedkey=$uname.':'.$udom;
5734: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5735: }
5736:
1.504 albertel 5737: sub get_first_access {
1.1308 raeburn 5738: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5739: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5740: if ($argsymb) { $symb=$argsymb; }
5741: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5742: if ($argmap) { $map = $argmap; }
1.926 albertel 5743: if ($type eq 'course') {
5744: $res='course';
5745: } elsif ($type eq 'map') {
1.588 albertel 5746: $res=&symbread($map);
5747: } else {
5748: $res=$symb;
5749: }
1.1308 raeburn 5750: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5751: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5752: }
5753:
5754: sub set_first_access {
1.1162 raeburn 5755: my ($type,$interval)=@_;
1.790 albertel 5756: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5757: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5758: if ($type eq 'course') {
5759: $res='course';
5760: } elsif ($type eq 'map') {
1.588 albertel 5761: $res=&symbread($map);
5762: } else {
5763: $res=$symb;
5764: }
1.1153 www 5765: $cachedkey='';
1.1162 raeburn 5766: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5767: if ($firstaccess) {
5768: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5769: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5770: "in $courseid");
1.1386 raeburn 5771: return 'already_set';
5772: } else {
1.1162 raeburn 5773: my $start = time;
5774: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5775: $udom,$uname);
5776: if ($putres eq 'ok') {
5777: &put('timerinterval',{"$courseid\0$res"=>$interval},
5778: $udom,$uname);
5779: &appenv(
5780: {
5781: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5782: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5783: }
5784: );
1.1365 raeburn 5785: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5786: $cachedtimes{"$courseid\0$res"} = $start;
5787: }
1.1386 raeburn 5788: } elsif ($putres ne 'refused') {
5789: &logthis("Result: $putres when attempting to set first access time ".
5790: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5791: }
5792: return $putres;
1.505 albertel 5793: }
5794: return 'already_set';
1.504 albertel 5795: }
1.1153 www 5796: }
1.1282 raeburn 5797:
1.110 www 5798: # --------------------------------------------- Set Expire Date for Spreadsheet
5799:
5800: sub expirespread {
5801: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5802: my $cid=$env{'request.course.id'};
1.110 www 5803: if ($cid) {
5804: my $now=time;
5805: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5806: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5807: $env{'course.'.$cid.'.num'}.
1.110 www 5808: ':nohist_expirationdates:'.
5809: &escape($key).'='.$now,
1.620 albertel 5810: $env{'course.'.$cid.'.home'})
1.110 www 5811: }
5812: return 'ok';
1.14 www 5813: }
5814:
1.109 www 5815: # ----------------------------------------------------- Devalidate Spreadsheets
5816:
5817: sub devalidate {
1.325 www 5818: my ($symb,$uname,$udom)=@_;
1.620 albertel 5819: my $cid=$env{'request.course.id'};
1.109 www 5820: if ($cid) {
1.391 matthew 5821: # delete the stored spreadsheets for
5822: # - the student level sheet of this user in course's homespace
5823: # - the assessment level sheet for this resource
5824: # for this user in user's homespace
1.553 albertel 5825: # - current conditional state info
1.325 www 5826: my $key=$uname.':'.$udom.':';
1.109 www 5827: my $status=
1.299 matthew 5828: &del('nohist_calculatedsheets',
1.391 matthew 5829: [$key.'studentcalc:'],
1.620 albertel 5830: $env{'course.'.$cid.'.domain'},
5831: $env{'course.'.$cid.'.num'})
1.133 albertel 5832: .' '.
5833: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5834: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5835: unless ($status eq 'ok ok') {
5836: &logthis('Could not devalidate spreadsheet '.
1.325 www 5837: $uname.' at '.$udom.' for '.
1.109 www 5838: $symb.': '.$status);
1.133 albertel 5839: }
1.553 albertel 5840: &delenv('user.state.'.$cid);
1.109 www 5841: }
5842: }
5843:
1.265 albertel 5844: sub get_scalar {
5845: my ($string,$end) = @_;
5846: my $value;
5847: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5848: $value = $1;
5849: } elsif ($$string =~ s/^([^&]*?)&//) {
5850: $value = $1;
5851: }
5852: return &unescape($value);
5853: }
5854:
5855: sub array2str {
5856: my (@array) = @_;
5857: my $result=&arrayref2str(\@array);
5858: $result=~s/^__ARRAY_REF__//;
5859: $result=~s/__END_ARRAY_REF__$//;
5860: return $result;
5861: }
5862:
1.204 albertel 5863: sub arrayref2str {
5864: my ($arrayref) = @_;
1.265 albertel 5865: my $result='__ARRAY_REF__';
1.204 albertel 5866: foreach my $elem (@$arrayref) {
1.265 albertel 5867: if(ref($elem) eq 'ARRAY') {
5868: $result.=&arrayref2str($elem).'&';
5869: } elsif(ref($elem) eq 'HASH') {
5870: $result.=&hashref2str($elem).'&';
5871: } elsif(ref($elem)) {
5872: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5873: } else {
5874: $result.=&escape($elem).'&';
5875: }
5876: }
5877: $result=~s/\&$//;
1.265 albertel 5878: $result .= '__END_ARRAY_REF__';
1.204 albertel 5879: return $result;
5880: }
5881:
1.168 albertel 5882: sub hash2str {
1.204 albertel 5883: my (%hash) = @_;
5884: my $result=&hashref2str(\%hash);
1.265 albertel 5885: $result=~s/^__HASH_REF__//;
5886: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5887: return $result;
5888: }
5889:
5890: sub hashref2str {
5891: my ($hashref)=@_;
1.265 albertel 5892: my $result='__HASH_REF__';
1.800 albertel 5893: foreach my $key (sort(keys(%$hashref))) {
5894: if (ref($key) eq 'ARRAY') {
5895: $result.=&arrayref2str($key).'=';
5896: } elsif (ref($key) eq 'HASH') {
5897: $result.=&hashref2str($key).'=';
5898: } elsif (ref($key)) {
1.265 albertel 5899: $result.='=';
1.800 albertel 5900: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5901: } else {
1.1132 raeburn 5902: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5903: }
5904:
1.800 albertel 5905: if(ref($hashref->{$key}) eq 'ARRAY') {
5906: $result.=&arrayref2str($hashref->{$key}).'&';
5907: } elsif(ref($hashref->{$key}) eq 'HASH') {
5908: $result.=&hashref2str($hashref->{$key}).'&';
5909: } elsif(ref($hashref->{$key})) {
1.265 albertel 5910: $result.='&';
1.800 albertel 5911: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5912: } else {
1.800 albertel 5913: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5914: }
5915: }
1.168 albertel 5916: $result=~s/\&$//;
1.265 albertel 5917: $result .= '__END_HASH_REF__';
1.168 albertel 5918: return $result;
5919: }
5920:
5921: sub str2hash {
1.265 albertel 5922: my ($string)=@_;
5923: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5924: return %$hash;
5925: }
5926:
5927: sub str2hashref {
1.168 albertel 5928: my ($string) = @_;
1.265 albertel 5929:
5930: my %hash;
5931:
5932: if($string !~ /^__HASH_REF__/) {
5933: if (! ($string eq '' || !defined($string))) {
5934: $hash{'error'}='Not hash reference';
5935: }
5936: return (\%hash, $string);
5937: }
5938:
5939: $string =~ s/^__HASH_REF__//;
5940:
5941: while($string !~ /^__END_HASH_REF__/) {
5942: #key
5943: my $key='';
5944: if($string =~ /^__HASH_REF__/) {
5945: ($key, $string)=&str2hashref($string);
5946: if(defined($key->{'error'})) {
5947: $hash{'error'}='Bad data';
5948: return (\%hash, $string);
5949: }
5950: } elsif($string =~ /^__ARRAY_REF__/) {
5951: ($key, $string)=&str2arrayref($string);
5952: if($key->[0] eq 'Array reference error') {
5953: $hash{'error'}='Bad data';
5954: return (\%hash, $string);
5955: }
5956: } else {
5957: $string =~ s/^(.*?)=//;
1.267 albertel 5958: $key=&unescape($1);
1.265 albertel 5959: }
5960: $string =~ s/^=//;
5961:
5962: #value
5963: my $value='';
5964: if($string =~ /^__HASH_REF__/) {
5965: ($value, $string)=&str2hashref($string);
5966: if(defined($value->{'error'})) {
5967: $hash{'error'}='Bad data';
5968: return (\%hash, $string);
5969: }
5970: } elsif($string =~ /^__ARRAY_REF__/) {
5971: ($value, $string)=&str2arrayref($string);
5972: if($value->[0] eq 'Array reference error') {
5973: $hash{'error'}='Bad data';
5974: return (\%hash, $string);
5975: }
5976: } else {
5977: $value=&get_scalar(\$string,'__END_HASH_REF__');
5978: }
5979: $string =~ s/^&//;
5980:
5981: $hash{$key}=$value;
1.204 albertel 5982: }
1.265 albertel 5983:
5984: $string =~ s/^__END_HASH_REF__//;
5985:
5986: return (\%hash, $string);
1.204 albertel 5987: }
5988:
5989: sub str2array {
1.265 albertel 5990: my ($string)=@_;
5991: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5992: return @$array;
5993: }
5994:
5995: sub str2arrayref {
1.204 albertel 5996: my ($string) = @_;
1.265 albertel 5997: my @array;
5998:
5999: if($string !~ /^__ARRAY_REF__/) {
6000: if (! ($string eq '' || !defined($string))) {
6001: $array[0]='Array reference error';
6002: }
6003: return (\@array, $string);
6004: }
6005:
6006: $string =~ s/^__ARRAY_REF__//;
6007:
6008: while($string !~ /^__END_ARRAY_REF__/) {
6009: my $value='';
6010: if($string =~ /^__HASH_REF__/) {
6011: ($value, $string)=&str2hashref($string);
6012: if(defined($value->{'error'})) {
6013: $array[0] ='Array reference error';
6014: return (\@array, $string);
6015: }
6016: } elsif($string =~ /^__ARRAY_REF__/) {
6017: ($value, $string)=&str2arrayref($string);
6018: if($value->[0] eq 'Array reference error') {
6019: $array[0] ='Array reference error';
6020: return (\@array, $string);
6021: }
6022: } else {
6023: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6024: }
6025: $string =~ s/^&//;
6026:
6027: push(@array, $value);
1.191 harris41 6028: }
1.265 albertel 6029:
6030: $string =~ s/^__END_ARRAY_REF__//;
6031:
6032: return (\@array, $string);
1.168 albertel 6033: }
6034:
1.167 albertel 6035: # -------------------------------------------------------------------Temp Store
6036:
1.168 albertel 6037: sub tmpreset {
6038: my ($symb,$namespace,$domain,$stuname) = @_;
6039: if (!$symb) {
6040: $symb=&symbread();
1.620 albertel 6041: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6042: }
6043: $symb=escape($symb);
6044:
1.620 albertel 6045: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6046: $namespace=~s/\//\_/g;
6047: $namespace=~s/\W//g;
6048:
1.620 albertel 6049: if (!$domain) { $domain=$env{'user.domain'}; }
6050: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6051: if ($domain eq 'public' && $stuname eq 'public') {
6052: $stuname=$ENV{'REMOTE_ADDR'};
6053: }
1.1117 foxr 6054: my $path=LONCAPA::tempdir();
1.168 albertel 6055: my %hash;
6056: if (tie(%hash,'GDBM_File',
6057: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6058: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6059: foreach my $key (keys(%hash)) {
1.180 albertel 6060: if ($key=~ /:$symb/) {
1.168 albertel 6061: delete($hash{$key});
6062: }
6063: }
6064: }
6065: }
6066:
1.167 albertel 6067: sub tmpstore {
1.168 albertel 6068: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6069:
6070: if (!$symb) {
6071: $symb=&symbread();
1.620 albertel 6072: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6073: }
6074: $symb=escape($symb);
6075:
6076: if (!$namespace) {
6077: # I don't think we would ever want to store this for a course.
6078: # it seems this will only be used if we don't have a course.
1.620 albertel 6079: #$namespace=$env{'request.course.id'};
1.168 albertel 6080: #if (!$namespace) {
1.620 albertel 6081: $namespace=$env{'request.state'};
1.168 albertel 6082: #}
6083: }
6084: $namespace=~s/\//\_/g;
6085: $namespace=~s/\W//g;
1.620 albertel 6086: if (!$domain) { $domain=$env{'user.domain'}; }
6087: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6088: if ($domain eq 'public' && $stuname eq 'public') {
6089: $stuname=$ENV{'REMOTE_ADDR'};
6090: }
1.168 albertel 6091: my $now=time;
6092: my %hash;
1.1117 foxr 6093: my $path=LONCAPA::tempdir();
1.168 albertel 6094: if (tie(%hash,'GDBM_File',
6095: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6096: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6097: $hash{"version:$symb"}++;
6098: my $version=$hash{"version:$symb"};
6099: my $allkeys='';
6100: foreach my $key (keys(%$storehash)) {
6101: $allkeys.=$key.':';
1.591 albertel 6102: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6103: }
6104: $hash{"$version:$symb:timestamp"}=$now;
6105: $allkeys.='timestamp';
6106: $hash{"$version:keys:$symb"}=$allkeys;
6107: if (untie(%hash)) {
6108: return 'ok';
6109: } else {
6110: return "error:$!";
6111: }
6112: } else {
6113: return "error:$!";
6114: }
6115: }
1.167 albertel 6116:
1.168 albertel 6117: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6118:
1.168 albertel 6119: sub tmprestore {
6120: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6121:
1.168 albertel 6122: if (!$symb) {
6123: $symb=&symbread();
1.620 albertel 6124: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6125: }
6126: $symb=escape($symb);
6127:
1.620 albertel 6128: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6129:
1.620 albertel 6130: if (!$domain) { $domain=$env{'user.domain'}; }
6131: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6132: if ($domain eq 'public' && $stuname eq 'public') {
6133: $stuname=$ENV{'REMOTE_ADDR'};
6134: }
1.168 albertel 6135: my %returnhash;
6136: $namespace=~s/\//\_/g;
6137: $namespace=~s/\W//g;
6138: my %hash;
1.1117 foxr 6139: my $path=LONCAPA::tempdir();
1.168 albertel 6140: if (tie(%hash,'GDBM_File',
6141: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6142: &GDBM_READER(),0640)) {
1.168 albertel 6143: my $version=$hash{"version:$symb"};
6144: $returnhash{'version'}=$version;
6145: my $scope;
6146: for ($scope=1;$scope<=$version;$scope++) {
6147: my $vkeys=$hash{"$scope:keys:$symb"};
6148: my @keys=split(/:/,$vkeys);
6149: my $key;
6150: $returnhash{"$scope:keys"}=$vkeys;
6151: foreach $key (@keys) {
1.591 albertel 6152: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6153: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6154: }
6155: }
1.168 albertel 6156: if (!(untie(%hash))) {
6157: return "error:$!";
6158: }
6159: } else {
6160: return "error:$!";
6161: }
6162: return %returnhash;
1.167 albertel 6163: }
6164:
1.9 www 6165: # ----------------------------------------------------------------------- Store
6166:
6167: sub store {
1.1269 raeburn 6168: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6169: my $home='';
6170:
1.168 albertel 6171: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6172:
1.213 www 6173: $symb=&symbclean($symb);
1.122 albertel 6174: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6175:
1.620 albertel 6176: if (!$domain) { $domain=$env{'user.domain'}; }
6177: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6178:
6179: &devalidate($symb,$stuname,$domain);
1.109 www 6180:
6181: $symb=escape($symb);
1.187 www 6182: if (!$namespace) {
1.620 albertel 6183: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6184: return '';
6185: }
6186: }
1.620 albertel 6187: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6188:
6189: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6190: $$storehash{'host'}=$perlvar{'lonHostID'};
6191:
1.12 www 6192: my $namevalue='';
1.800 albertel 6193: foreach my $key (keys(%$storehash)) {
6194: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6195: }
1.12 www 6196: $namevalue=~s/\&$//;
1.187 www 6197: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6198: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6199: }
6200:
1.47 www 6201: # -------------------------------------------------------------- Critical Store
6202:
6203: sub cstore {
1.1269 raeburn 6204: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6205: my $home='';
6206:
1.168 albertel 6207: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6208:
1.213 www 6209: $symb=&symbclean($symb);
1.122 albertel 6210: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6211:
1.620 albertel 6212: if (!$domain) { $domain=$env{'user.domain'}; }
6213: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6214:
6215: &devalidate($symb,$stuname,$domain);
1.109 www 6216:
6217: $symb=escape($symb);
1.187 www 6218: if (!$namespace) {
1.620 albertel 6219: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6220: return '';
6221: }
6222: }
1.620 albertel 6223: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6224:
6225: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6226: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6227:
1.47 www 6228: my $namevalue='';
1.800 albertel 6229: foreach my $key (keys(%$storehash)) {
6230: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6231: }
1.47 www 6232: $namevalue=~s/\&$//;
1.187 www 6233: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6234: return critical
1.1269 raeburn 6235: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6236: }
6237:
1.9 www 6238: # --------------------------------------------------------------------- Restore
6239:
6240: sub restore {
1.124 www 6241: my ($symb,$namespace,$domain,$stuname) = @_;
6242: my $home='';
6243:
1.168 albertel 6244: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6245:
1.122 albertel 6246: if (!$symb) {
1.1224 raeburn 6247: return if ($namespace eq 'courserequests');
6248: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6249: } else {
1.1224 raeburn 6250: unless ($namespace eq 'courserequests') {
6251: $symb=&escape(&symbclean($symb));
6252: }
1.122 albertel 6253: }
1.188 www 6254: if (!$namespace) {
1.620 albertel 6255: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6256: return '';
6257: }
6258: }
1.620 albertel 6259: if (!$domain) { $domain=$env{'user.domain'}; }
6260: if (!$stuname) { $stuname=$env{'user.name'}; }
6261: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6262: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6263:
1.12 www 6264: my %returnhash=();
1.800 albertel 6265: foreach my $line (split(/\&/,$answer)) {
6266: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6267: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6268: }
1.75 www 6269: my $version;
6270: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6271: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6272: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6273: }
1.75 www 6274: }
1.13 www 6275: return %returnhash;
1.34 www 6276: }
6277:
6278: # ---------------------------------------------------------- Course Description
1.1118 foxr 6279: #
6280: #
1.34 www 6281:
6282: sub coursedescription {
1.731 albertel 6283: my ($courseid,$args)=@_;
1.34 www 6284: $courseid=~s/^\///;
1.49 www 6285: $courseid=~s/\_/\//g;
1.34 www 6286: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6287: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6288: my $normalid=$cdomain.'_'.$cnum;
6289: # need to always cache even if we get errors otherwise we keep
6290: # trying and trying and trying to get the course description.
6291: my %envhash=();
6292: my %returnhash=();
1.731 albertel 6293:
6294: my $expiretime=600;
6295: if ($env{'request.course.id'} eq $normalid) {
6296: $expiretime=120;
6297: }
6298:
6299: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6300: if (!$args->{'freshen_cache'}
6301: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6302: foreach my $key (keys(%env)) {
6303: next if ($key !~ /^\Q$prefix\E(.*)/);
6304: my ($setting) = $1;
6305: $returnhash{$setting} = $env{$key};
6306: }
6307: return %returnhash;
6308: }
6309:
1.1118 foxr 6310: # get the data again
6311:
1.731 albertel 6312: if (!$args->{'one_time'}) {
6313: $envhash{'course.'.$normalid.'.last_cache'}=time;
6314: }
1.811 albertel 6315:
1.34 www 6316: if ($chome ne 'no_host') {
1.302 albertel 6317: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6318: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6319: my $username = $env{'user.name'}; # Defult username
6320: if(defined $args->{'user'}) {
6321: $username = $args->{'user'};
6322: }
1.129 albertel 6323: $returnhash{'home'}= $chome;
6324: $returnhash{'domain'} = $cdomain;
6325: $returnhash{'num'} = $cnum;
1.741 raeburn 6326: if (!defined($returnhash{'type'})) {
6327: $returnhash{'type'} = 'Course';
6328: }
1.130 albertel 6329: while (my ($name,$value) = each %returnhash) {
1.53 www 6330: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6331: }
1.270 www 6332: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6333: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6334: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6335: $envhash{'course.'.$normalid.'.home'}=$chome;
6336: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6337: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6338: }
6339: }
1.731 albertel 6340: if (!$args->{'one_time'}) {
1.949 raeburn 6341: &appenv(\%envhash);
1.731 albertel 6342: }
1.302 albertel 6343: return %returnhash;
1.461 www 6344: }
6345:
1.1080 raeburn 6346: sub update_released_required {
6347: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6348: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6349: $cid = $env{'request.course.id'};
6350: $cdom = $env{'course.'.$cid.'.domain'};
6351: $cnum = $env{'course.'.$cid.'.num'};
6352: $chome = $env{'course.'.$cid.'.home'};
6353: }
6354: if ($needsrelease) {
6355: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6356: my $needsupdate;
6357: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6358: $needsupdate = 1;
6359: } else {
6360: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6361: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6362: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6363: $needsupdate = 1;
6364: }
6365: }
6366: if ($needsupdate) {
6367: my %needshash = (
6368: 'internal.releaserequired' => $needsrelease,
6369: );
6370: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6371: if ($putresult eq 'ok') {
6372: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6373: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6374: if (ref($crsinfo{$cid}) eq 'HASH') {
6375: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6376: &courseidput($cdom,\%crsinfo,$chome,'notime');
6377: }
6378: }
6379: }
6380: }
6381: return;
6382: }
6383:
1.461 www 6384: # -------------------------------------------------See if a user is privileged
6385:
6386: sub privileged {
1.1219 raeburn 6387: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6388: my $now = time;
1.1219 raeburn 6389: my $roles;
6390: if (ref($possroles) eq 'ARRAY') {
6391: $roles = $possroles;
6392: } else {
6393: $roles = ['dc','su'];
6394: }
6395: if (ref($possdomains) eq 'ARRAY') {
6396: my %privileged = &privileged_by_domain($possdomains,$roles);
6397: foreach my $dom (@{$possdomains}) {
6398: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6399: (ref($privileged{$dom}) eq 'HASH')) {
6400: foreach my $role (@{$roles}) {
6401: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6402: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6403: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6404: return 1 unless (($end && $end < $now) ||
6405: ($start && $start > $now));
6406: }
6407: }
6408: }
6409: }
6410: }
6411: } else {
6412: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6413: my $now = time;
1.1170 droeschl 6414:
1.1275 musolffc 6415: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6416: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6417: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6418: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6419: or ($tstart && $tstart > $now);
1.1170 droeschl 6420: }
1.1219 raeburn 6421: }
6422: }
6423: return 0;
6424: }
1.1170 droeschl 6425:
1.1219 raeburn 6426: sub privileged_by_domain {
6427: my ($domains,$roles) = @_;
6428: my %privileged = ();
6429: my $cachetime = 60*60*24;
6430: my $now = time;
6431: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6432: return %privileged;
6433: }
6434: foreach my $dom (@{$domains}) {
6435: next if (ref($privileged{$dom}) eq 'HASH');
6436: my $needroles;
6437: foreach my $role (@{$roles}) {
6438: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6439: if (defined($cached)) {
6440: if (ref($result) eq 'HASH') {
6441: $privileged{$dom}{$role} = $result;
6442: }
6443: } else {
6444: $needroles = 1;
6445: }
6446: }
6447: if ($needroles) {
6448: my %dompersonnel = &get_domain_roles($dom,$roles);
6449: $privileged{$dom} = {};
6450: foreach my $server (keys(%dompersonnel)) {
6451: if (ref($dompersonnel{$server}) eq 'HASH') {
6452: foreach my $item (keys(%{$dompersonnel{$server}})) {
6453: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6454: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6455: next if ($end && $end < $now);
6456: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6457: $dompersonnel{$server}{$item};
6458: }
6459: }
6460: }
6461: if (ref($privileged{$dom}) eq 'HASH') {
6462: foreach my $role (@{$roles}) {
6463: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6464: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6465: } else {
6466: my %hash = ();
6467: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6468: }
6469: }
6470: }
6471: }
6472: }
6473: return %privileged;
1.9 www 6474: }
1.1 albertel 6475:
1.103 harris41 6476: # -------------------------------------------------------- Get user privileges
1.11 www 6477:
6478: sub rolesinit {
1.1169 droeschl 6479: my ($domain, $username) = @_;
6480: my %userroles = ('user.login.time' => time);
6481: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6482:
6483: # firstaccess and timerinterval are related to timed maps/resources.
6484: # also, blocking can be triggered by an activating timer
6485: # it's saved in the user's %env.
6486: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6487: my %timerinterval = &dump('timerinterval', $domain, $username);
6488: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6489: %timerintchk, %timerintenv);
6490:
1.1162 raeburn 6491: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6492: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6493: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6494: }
1.1169 droeschl 6495:
1.1162 raeburn 6496: foreach my $key (keys(%timerinterval)) {
6497: my ($cid,$rest) = split(/\0/,$key);
6498: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6499: }
1.1169 droeschl 6500:
1.11 www 6501: my %allroles=();
1.1162 raeburn 6502: my %allgroups=();
1.11 www 6503:
1.1274 raeburn 6504: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6505: my $role = $rolesdump{$area};
6506: $area =~ s/\_\w\w$//;
6507:
6508: my ($trole, $tend, $tstart, $group_privs);
6509:
6510: if ($role =~ /^cr/) {
6511: # Custom role, defined by a user
6512: # e.g., user.role.cr/msu/smith/mynewrole
6513: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6514: $trole = $1;
6515: ($tend, $tstart) = split('_', $2);
6516: } else {
6517: $trole = $role;
6518: }
6519: } elsif ($role =~ m|^gr/|) {
6520: # Role of member in a group, defined within a course/community
6521: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6522: ($trole, $tend, $tstart) = split(/_/, $role);
6523: next if $tstart eq '-1';
6524: ($trole, $group_privs) = split(/\//, $trole);
6525: $group_privs = &unescape($group_privs);
6526: } else {
6527: # Just a normal role, defined in roles.tab
6528: ($trole, $tend, $tstart) = split(/_/,$role);
6529: }
6530:
6531: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6532: $username);
6533: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6534:
6535: # role expired or not available yet?
6536: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6537: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6538:
6539: next if $area eq '' or $trole eq '';
6540:
6541: my $spec = "$trole.$area";
6542: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6543:
6544: if ($trole =~ /^cr\//) {
6545: # Custom role, defined by a user
6546: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6547: } elsif ($trole eq 'gr') {
6548: # Role of a member in a group, defined within a course/community
6549: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6550: next;
6551: } else {
6552: # Normal role, defined in roles.tab
6553: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6554: }
6555:
6556: my $cid = $tdomain.'_'.$trest;
6557: unless ($firstaccchk{$cid}) {
6558: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6559: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6560: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6561: $coursetimerstarts{$cid}{$item};
6562: }
6563: }
6564: $firstaccchk{$cid} = 1;
6565: }
6566: unless ($timerintchk{$cid}) {
6567: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6568: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6569: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6570: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6571: }
1.12 www 6572: }
1.1169 droeschl 6573: $timerintchk{$cid} = 1;
1.191 harris41 6574: }
1.11 www 6575: }
1.1169 droeschl 6576:
1.1341 raeburn 6577: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6578: \%allroles, \%allgroups);
1.1169 droeschl 6579: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6580: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6581:
1.1162 raeburn 6582: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6583: }
6584:
1.567 raeburn 6585: sub set_arearole {
1.1215 raeburn 6586: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6587: unless ($nolog) {
1.567 raeburn 6588: # log the associated role with the area
1.1215 raeburn 6589: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6590: }
1.743 albertel 6591: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6592: }
6593:
6594: sub custom_roleprivs {
6595: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6596: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6597: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6598: if (&hostname($homsvr) ne '') {
1.567 raeburn 6599: my ($rdummy,$roledef)=
6600: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6601: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6602: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6603: if (defined($syspriv)) {
1.1043 raeburn 6604: if ($trest =~ /^$match_community$/) {
6605: $syspriv =~ s/bre\&S//;
6606: }
1.567 raeburn 6607: $$allroles{'cm./'}.=':'.$syspriv;
6608: $$allroles{$spec.'./'}.=':'.$syspriv;
6609: }
6610: if ($tdomain ne '') {
6611: if (defined($dompriv)) {
6612: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6613: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6614: }
6615: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6616: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6617: my $rolename = $1;
6618: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6619: }
1.567 raeburn 6620: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6621: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6622: }
6623: }
6624: }
6625: }
6626: }
6627:
1.1332 raeburn 6628: sub course_adhocrole_privs {
6629: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6630: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6631: if ($overrides{"internal.adhocpriv.$rolename"}) {
6632: my (%currprivs,%storeprivs);
6633: foreach my $item (split(/:/,$coursepriv)) {
6634: my ($priv,$restrict) = split(/\&/,$item);
6635: $currprivs{$priv} = $restrict;
6636: }
6637: my (%possadd,%possremove,%full);
6638: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6639: my ($priv,$restrict)=split(/\&/,$item);
6640: $full{$priv} = $restrict;
6641: }
6642: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6643: next if ($item eq '');
6644: my ($rule,$rest) = split(/=/,$item);
6645: next unless (($rule eq 'off') || ($rule eq 'on'));
6646: foreach my $priv (split(/:/,$rest)) {
6647: if ($priv ne '') {
6648: if ($rule eq 'off') {
6649: $possremove{$priv} = 1;
6650: } else {
6651: $possadd{$priv} = 1;
6652: }
6653: }
6654: }
6655: }
6656: foreach my $priv (sort(keys(%full))) {
6657: if (exists($currprivs{$priv})) {
6658: unless (exists($possremove{$priv})) {
6659: $storeprivs{$priv} = $currprivs{$priv};
6660: }
6661: } elsif (exists($possadd{$priv})) {
6662: $storeprivs{$priv} = $full{$priv};
6663: }
6664: }
6665: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6666: }
6667: return $coursepriv;
6668: }
6669:
1.678 raeburn 6670: sub group_roleprivs {
6671: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6672: my $access = 1;
6673: my $now = time;
6674: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6675: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6676: if ($access) {
1.811 albertel 6677: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6678: $$allgroups{$course}{$group} .=':'.$group_privs;
6679: }
6680: }
1.567 raeburn 6681:
6682: sub standard_roleprivs {
6683: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6684: if (defined($pr{$trole.':s'})) {
6685: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6686: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6687: }
6688: if ($tdomain ne '') {
6689: if (defined($pr{$trole.':d'})) {
6690: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6691: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6692: }
6693: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6694: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6695: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6696: }
6697: }
6698: }
6699:
6700: sub set_userprivs {
1.1064 raeburn 6701: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6702: my $author=0;
6703: my $adv=0;
1.1341 raeburn 6704: my $rar=0;
1.678 raeburn 6705: my %grouproles = ();
6706: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6707: my @groupkeys;
1.1000 raeburn 6708: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6709: push(@groupkeys,$role);
6710: }
6711: if (ref($groups_roles) eq 'HASH') {
6712: foreach my $key (keys(%{$groups_roles})) {
6713: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6714: push(@groupkeys,$key);
6715: }
6716: }
6717: }
6718: if (@groupkeys > 0) {
6719: foreach my $role (@groupkeys) {
6720: my ($trole,$area,$sec,$extendedarea);
6721: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6722: $trole = $1;
6723: $area = $2;
6724: $sec = $3;
6725: $extendedarea = $area.$sec;
6726: if (exists($$allgroups{$area})) {
6727: foreach my $group (keys(%{$$allgroups{$area}})) {
6728: my $spec = $trole.'.'.$extendedarea;
6729: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6730: $$allgroups{$area}{$group};
1.1064 raeburn 6731: }
1.678 raeburn 6732: }
6733: }
6734: }
6735: }
6736: }
1.800 albertel 6737: foreach my $group (keys(%grouproles)) {
6738: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6739: }
1.800 albertel 6740: foreach my $role (keys(%{$allroles})) {
6741: my %thesepriv;
1.941 raeburn 6742: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6743: foreach my $item (split(/:/,$$allroles{$role})) {
6744: if ($item ne '') {
6745: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6746: if ($restrictions eq '') {
6747: $thesepriv{$privilege}='F';
6748: } elsif ($thesepriv{$privilege} ne 'F') {
6749: $thesepriv{$privilege}.=$restrictions;
6750: }
6751: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6752: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6753: }
6754: }
6755: my $thesestr='';
1.1104 raeburn 6756: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6757: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6758: }
6759: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6760: }
1.1341 raeburn 6761: return ($author,$adv,$rar);
1.567 raeburn 6762: }
6763:
1.994 raeburn 6764: sub role_status {
1.1104 raeburn 6765: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6766: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6767: my ($one,$two) = split(m{\./},$rolekey,2);
6768: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6769: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6770: $$where = '/'.$two;
1.994 raeburn 6771: $$trolecode=$$role.'.'.$$where;
6772: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6773: $$tstatus='is';
1.1104 raeburn 6774: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6775: $$tstatus='future';
1.1034 raeburn 6776: if ($$tstart<$now) {
6777: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6778: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6779: my (%allroles,%allgroups,$group_privs,
6780: %groups_roles,@rolecodes);
1.1002 raeburn 6781: my %userroles = (
6782: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6783: );
1.1064 raeburn 6784: @rolecodes = ('cm');
1.1002 raeburn 6785: my $spec=$$role.'.'.$$where;
6786: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6787: if ($$role =~ /^cr\//) {
6788: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6789: push(@rolecodes,'cr');
1.1002 raeburn 6790: } elsif ($$role eq 'gr') {
1.1064 raeburn 6791: push(@rolecodes,$$role);
1.1002 raeburn 6792: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6793: $env{'user.name'});
1.1064 raeburn 6794: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6795: (undef,my $group_privs) = split(/\//,$trole);
6796: $group_privs = &unescape($group_privs);
6797: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6798: 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 6799: &get_groups_roles($tdomain,$trest,
6800: \%course_roles,\@rolecodes,
6801: \%groups_roles);
1.1002 raeburn 6802: } else {
1.1064 raeburn 6803: push(@rolecodes,$$role);
1.1002 raeburn 6804: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6805: }
1.1341 raeburn 6806: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6807: \%groups_roles);
1.1064 raeburn 6808: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6809: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6810: }
6811: }
1.1034 raeburn 6812: $$tstatus = 'is';
1.1002 raeburn 6813: }
1.994 raeburn 6814: }
6815: if ($$tend) {
1.1104 raeburn 6816: if ($$tend<$update) {
1.994 raeburn 6817: $$tstatus='expired';
6818: } elsif ($$tend<$now) {
6819: $$tstatus='will_not';
6820: }
6821: }
6822: }
6823: }
6824: }
6825:
1.1104 raeburn 6826: sub get_groups_roles {
6827: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6828: return unless((ref($cdom_courseroles) eq 'HASH') &&
6829: (ref($rolecodes) eq 'ARRAY') &&
6830: (ref($groups_roles) eq 'HASH'));
6831: if (keys(%{$cdom_courseroles}) > 0) {
6832: my ($cnum) = ($rest =~ /^($match_courseid)/);
6833: if ($cdom ne '' && $cnum ne '') {
6834: foreach my $key (keys(%{$cdom_courseroles})) {
6835: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6836: my $crsrole = $1;
6837: my $crssec = $2;
6838: if ($crsrole =~ /^cr/) {
6839: unless (grep(/^cr$/,@{$rolecodes})) {
6840: push(@{$rolecodes},'cr');
6841: }
6842: } else {
6843: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6844: push(@{$rolecodes},$crsrole);
6845: }
6846: }
6847: my $rolekey = "$crsrole./$cdom/$cnum";
6848: if ($crssec ne '') {
6849: $rolekey .= "/$crssec";
6850: }
6851: $rolekey .= './';
6852: $groups_roles->{$rolekey} = $rolecodes;
6853: }
6854: }
6855: }
6856: }
6857: return;
6858: }
6859:
6860: sub delete_env_groupprivs {
6861: my ($where,$courseroles,$possroles) = @_;
6862: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6863: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6864: unless (ref($courseroles->{$udom}) eq 'HASH') {
6865: %{$courseroles->{$udom}} =
6866: &get_my_roles('','','userroles',['active'],
6867: $possroles,[$udom],1);
6868: }
6869: if (ref($courseroles->{$udom}) eq 'HASH') {
6870: foreach my $item (keys(%{$courseroles->{$udom}})) {
6871: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6872: my $area = '/'.$cdom.'/'.$cnum;
6873: my $privkey = "user.priv.$crsrole.$area";
6874: if ($crssec ne '') {
6875: $privkey .= '/'.$crssec;
6876: }
6877: $privkey .= ".$area/$group";
6878: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6879: }
6880: }
6881: return;
6882: }
6883:
1.994 raeburn 6884: sub check_adhoc_privs {
1.1329 raeburn 6885: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6886: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6887: if ($sec) {
6888: $cckey .= '/'.$sec;
6889: }
1.1185 raeburn 6890: my $setprivs;
1.994 raeburn 6891: if ($env{$cckey}) {
6892: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6893: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6894: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6895: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6896: $setprivs = 1;
1.994 raeburn 6897: }
6898: } else {
1.1330 raeburn 6899: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6900: $setprivs = 1;
1.994 raeburn 6901: }
1.1185 raeburn 6902: return $setprivs;
1.994 raeburn 6903: }
6904:
6905: sub set_adhoc_privileges {
1.1326 raeburn 6906: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6907: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6908: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6909: if ($sec ne '') {
6910: $area .= '/'.$sec;
6911: }
1.994 raeburn 6912: my $spec = $role.'.'.$area;
6913: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6914: $env{'user.name'},1);
1.1326 raeburn 6915: my %rolehash = ();
1.1332 raeburn 6916: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6917: my $rolename = $1;
1.1326 raeburn 6918: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6919: my %domdef = &get_domain_defaults($dcdom);
6920: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6921: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6922: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6923: }
6924: }
1.1326 raeburn 6925: } else {
6926: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6927: }
1.1341 raeburn 6928: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6929: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6930: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 6931: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
6932: ($caller eq 'tiny')) {
1.1088 raeburn 6933: &appenv( {'request.role' => $spec,
6934: 'request.role.domain' => $dcdom,
1.1332 raeburn 6935: 'request.course.sec' => $sec,
1.1088 raeburn 6936: }
6937: );
6938: my $tadv=0;
6939: if (&allowed('adv') eq 'F') { $tadv=1; }
6940: &appenv({'request.role.adv' => $tadv});
6941: }
1.994 raeburn 6942: }
6943:
1.12 www 6944: # --------------------------------------------------------------- get interface
6945:
6946: sub get {
1.131 albertel 6947: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6948: my $items='';
1.800 albertel 6949: foreach my $item (@$storearr) {
6950: $items.=&escape($item).'&';
1.191 harris41 6951: }
1.12 www 6952: $items=~s/\&$//;
1.620 albertel 6953: if (!$udomain) { $udomain=$env{'user.domain'}; }
6954: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6955: my $uhome=&homeserver($uname,$udomain);
6956:
1.133 albertel 6957: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6958: my @pairs=split(/\&/,$rep);
1.273 albertel 6959: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6960: return @pairs;
6961: }
1.15 www 6962: my %returnhash=();
1.42 www 6963: my $i=0;
1.800 albertel 6964: foreach my $item (@$storearr) {
6965: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6966: $i++;
1.191 harris41 6967: }
1.15 www 6968: return %returnhash;
1.27 www 6969: }
6970:
6971: # --------------------------------------------------------------- del interface
6972:
6973: sub del {
1.133 albertel 6974: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6975: my $items='';
1.800 albertel 6976: foreach my $item (@$storearr) {
6977: $items.=&escape($item).'&';
1.191 harris41 6978: }
1.984 neumanie 6979:
1.27 www 6980: $items=~s/\&$//;
1.620 albertel 6981: if (!$udomain) { $udomain=$env{'user.domain'}; }
6982: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6983: my $uhome=&homeserver($uname,$udomain);
6984: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6985: }
6986:
6987: # -------------------------------------------------------------- dump interface
6988:
1.1180 droeschl 6989: sub unserialize {
6990: my ($rep, $escapedkeys) = @_;
6991:
6992: return {} if $rep =~ /^error/;
6993:
6994: my %returnhash=();
1.1252 raeburn 6995: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6996: my ($key, $value) = split(/=/, $item, 2);
6997: $key = unescape($key) unless $escapedkeys;
6998: next if $key =~ /^error: 2 /;
1.1252 raeburn 6999: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7000: }
7001: #return %returnhash;
7002: return \%returnhash;
7003: }
7004:
7005: # see Lond::dump_with_regexp
7006: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7007: sub dump {
1.1180 droeschl 7008: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 7009: if (!$udomain) { $udomain=$env{'user.domain'}; }
7010: if (!$uname) { $uname=$env{'user.name'}; }
7011: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7012:
1.1266 raeburn 7013: if ($regexp) {
7014: $regexp=&escape($regexp);
7015: } else {
7016: $regexp='.';
7017: }
1.1180 droeschl 7018: if (grep { $_ eq $uhome } current_machine_ids()) {
7019: # user is hosted on this machine
1.1266 raeburn 7020: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7021: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7022: return %{unserialize($reply, $escapedkeys)};
7023: }
1.1166 raeburn 7024: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 7025: my @pairs=split(/\&/,$rep);
7026: my %returnhash=();
1.1098 foxr 7027: if (!($rep =~ /^error/ )) {
7028: foreach my $item (@pairs) {
7029: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7030: $key = unescape($key) unless $escapedkeys;
7031: #$key = &unescape($key);
1.1098 foxr 7032: next if ($key =~ /^error: 2 /);
7033: $returnhash{$key}=&thaw_unescape($value);
7034: }
1.755 albertel 7035: }
7036: return %returnhash;
1.407 www 7037: }
7038:
1.1098 foxr 7039:
1.717 albertel 7040: # --------------------------------------------------------- dumpstore interface
7041:
7042: sub dumpstore {
7043: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7044: # same as dump but keys must be escaped. They may contain colon separated
7045: # lists of values that may themself contain colons (e.g. symbs).
7046: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7047: }
7048:
1.407 www 7049: # -------------------------------------------------------------- keys interface
7050:
7051: sub getkeys {
7052: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7053: if (!$udomain) { $udomain=$env{'user.domain'}; }
7054: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7055: my $uhome=&homeserver($uname,$udomain);
7056: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7057: my @keyarray=();
1.800 albertel 7058: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7059: next if ($key =~ /^error: 2 /);
1.800 albertel 7060: push(@keyarray,&unescape($key));
1.407 www 7061: }
7062: return @keyarray;
1.318 matthew 7063: }
7064:
1.319 matthew 7065: # --------------------------------------------------------------- currentdump
7066: sub currentdump {
1.328 matthew 7067: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7068: $courseid = $env{'request.course.id'} if (! defined($courseid));
7069: $sdom = $env{'user.domain'} if (! defined($sdom));
7070: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7071: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7072: my $rep;
7073:
7074: if (grep { $_ eq $uhome } current_machine_ids()) {
7075: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7076: $courseid)));
7077: } else {
7078: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7079: }
7080:
1.318 matthew 7081: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7082: #
1.318 matthew 7083: my %returnhash=();
1.319 matthew 7084: #
1.1343 raeburn 7085: if ($rep eq 'unknown_cmd') {
1.319 matthew 7086: # an old lond will not know currentdump
7087: # Do a dump and make it look like a currentdump
1.822 albertel 7088: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7089: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7090: my %hash = @tmp;
7091: @tmp=();
1.424 matthew 7092: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7093: } else {
7094: my @pairs=split(/\&/,$rep);
1.800 albertel 7095: foreach my $pair (@pairs) {
7096: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7097: my ($symb,$param) = split(/:/,$key);
7098: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7099: &thaw_unescape($value);
1.319 matthew 7100: }
1.191 harris41 7101: }
1.12 www 7102: return %returnhash;
1.424 matthew 7103: }
7104:
7105: sub convert_dump_to_currentdump{
7106: my %hash = %{shift()};
7107: my %returnhash;
7108: # Code ripped from lond, essentially. The only difference
7109: # here is the unescaping done by lonnet::dump(). Conceivably
7110: # we might run in to problems with parameter names =~ /^v\./
7111: while (my ($key,$value) = each(%hash)) {
7112: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7113: $symb = &unescape($symb);
7114: $param = &unescape($param);
1.424 matthew 7115: next if ($v eq 'version' || $symb eq 'keys');
7116: next if (exists($returnhash{$symb}) &&
7117: exists($returnhash{$symb}->{$param}) &&
7118: $returnhash{$symb}->{'v.'.$param} > $v);
7119: $returnhash{$symb}->{$param}=$value;
7120: $returnhash{$symb}->{'v.'.$param}=$v;
7121: }
7122: #
7123: # Remove all of the keys in the hashes which keep track of
7124: # the version of the parameter.
7125: while (my ($symb,$param_hash) = each(%returnhash)) {
7126: # use a foreach because we are going to delete from the hash.
7127: foreach my $key (keys(%$param_hash)) {
7128: delete($param_hash->{$key}) if ($key =~ /^v\./);
7129: }
7130: }
7131: return \%returnhash;
1.12 www 7132: }
7133:
1.627 albertel 7134: # ------------------------------------------------------ critical inc interface
7135:
7136: sub cinc {
7137: return &inc(@_,'critical');
7138: }
7139:
1.449 matthew 7140: # --------------------------------------------------------------- inc interface
7141:
7142: sub inc {
1.627 albertel 7143: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7144: if (!$udomain) { $udomain=$env{'user.domain'}; }
7145: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7146: my $uhome=&homeserver($uname,$udomain);
7147: my $items='';
7148: if (! ref($store)) {
7149: # got a single value, so use that instead
7150: $items = &escape($store).'=&';
7151: } elsif (ref($store) eq 'SCALAR') {
7152: $items = &escape($$store).'=&';
7153: } elsif (ref($store) eq 'ARRAY') {
7154: $items = join('=&',map {&escape($_);} @{$store});
7155: } elsif (ref($store) eq 'HASH') {
7156: while (my($key,$value) = each(%{$store})) {
7157: $items.= &escape($key).'='.&escape($value).'&';
7158: }
7159: }
7160: $items=~s/\&$//;
1.627 albertel 7161: if ($critical) {
7162: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7163: } else {
7164: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7165: }
1.449 matthew 7166: }
7167:
1.12 www 7168: # --------------------------------------------------------------- put interface
7169:
7170: sub put {
1.134 albertel 7171: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7172: if (!$udomain) { $udomain=$env{'user.domain'}; }
7173: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7174: my $uhome=&homeserver($uname,$udomain);
1.12 www 7175: my $items='';
1.800 albertel 7176: foreach my $item (keys(%$storehash)) {
7177: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7178: }
1.12 www 7179: $items=~s/\&$//;
1.134 albertel 7180: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7181: }
7182:
1.631 albertel 7183: # ------------------------------------------------------------ newput interface
7184:
7185: sub newput {
7186: my ($namespace,$storehash,$udomain,$uname)=@_;
7187: if (!$udomain) { $udomain=$env{'user.domain'}; }
7188: if (!$uname) { $uname=$env{'user.name'}; }
7189: my $uhome=&homeserver($uname,$udomain);
7190: my $items='';
7191: foreach my $key (keys(%$storehash)) {
7192: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7193: }
7194: $items=~s/\&$//;
7195: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7196: }
7197:
7198: # --------------------------------------------------------- putstore interface
7199:
1.524 raeburn 7200: sub putstore {
1.1269 raeburn 7201: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7202: if (!$udomain) { $udomain=$env{'user.domain'}; }
7203: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7204: my $uhome=&homeserver($uname,$udomain);
7205: my $items='';
1.715 albertel 7206: foreach my $key (keys(%$storehash)) {
7207: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7208: }
1.715 albertel 7209: $items=~s/\&$//;
1.716 albertel 7210: my $esc_symb=&escape($symb);
7211: my $esc_v=&escape($version);
1.715 albertel 7212: my $reply =
1.716 albertel 7213: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7214: $uhome);
1.1269 raeburn 7215: if (($tolog) && ($reply eq 'ok')) {
7216: my $namevalue='';
7217: foreach my $key (keys(%{$storehash})) {
7218: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7219: }
7220: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7221: '&host='.&escape($perlvar{'lonHostID'}).
7222: '&version='.$esc_v.
7223: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7224: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7225: }
1.715 albertel 7226: if ($reply eq 'unknown_cmd') {
1.716 albertel 7227: # gfall back to way things use to be done
1.715 albertel 7228: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7229: $uname);
1.524 raeburn 7230: }
1.715 albertel 7231: return $reply;
7232: }
7233:
7234: sub old_putstore {
1.716 albertel 7235: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7236: if (!$udomain) { $udomain=$env{'user.domain'}; }
7237: if (!$uname) { $uname=$env{'user.name'}; }
7238: my $uhome=&homeserver($uname,$udomain);
7239: my %newstorehash;
1.800 albertel 7240: foreach my $item (keys(%$storehash)) {
7241: my $key = $version.':'.&escape($symb).':'.$item;
7242: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7243: }
7244: my $items='';
7245: my %allitems = ();
1.800 albertel 7246: foreach my $item (keys(%newstorehash)) {
7247: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7248: my $key = $1.':keys:'.$2;
7249: $allitems{$key} .= $3.':';
7250: }
1.800 albertel 7251: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7252: }
1.800 albertel 7253: foreach my $item (keys(%allitems)) {
7254: $allitems{$item} =~ s/\:$//;
7255: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7256: }
7257: $items=~s/\&$//;
7258: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7259: }
7260:
1.47 www 7261: # ------------------------------------------------------ critical put interface
7262:
7263: sub cput {
1.134 albertel 7264: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7265: if (!$udomain) { $udomain=$env{'user.domain'}; }
7266: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7267: my $uhome=&homeserver($uname,$udomain);
1.47 www 7268: my $items='';
1.800 albertel 7269: foreach my $item (keys(%$storehash)) {
7270: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7271: }
1.47 www 7272: $items=~s/\&$//;
1.134 albertel 7273: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7274: }
7275:
7276: # -------------------------------------------------------------- eget interface
7277:
7278: sub eget {
1.133 albertel 7279: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7280: my $items='';
1.800 albertel 7281: foreach my $item (@$storearr) {
7282: $items.=&escape($item).'&';
1.191 harris41 7283: }
1.12 www 7284: $items=~s/\&$//;
1.620 albertel 7285: if (!$udomain) { $udomain=$env{'user.domain'}; }
7286: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7287: my $uhome=&homeserver($uname,$udomain);
7288: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7289: my @pairs=split(/\&/,$rep);
7290: my %returnhash=();
1.42 www 7291: my $i=0;
1.800 albertel 7292: foreach my $item (@$storearr) {
7293: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7294: $i++;
1.191 harris41 7295: }
1.12 www 7296: return %returnhash;
7297: }
7298:
1.667 albertel 7299: # ------------------------------------------------------------ tmpput interface
7300: sub tmpput {
1.802 raeburn 7301: my ($storehash,$server,$context)=@_;
1.667 albertel 7302: my $items='';
1.800 albertel 7303: foreach my $item (keys(%$storehash)) {
7304: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7305: }
7306: $items=~s/\&$//;
1.802 raeburn 7307: if (defined($context)) {
7308: $items .= ':'.&escape($context);
7309: }
1.667 albertel 7310: return &reply("tmpput:$items",$server);
7311: }
7312:
7313: # ------------------------------------------------------------ tmpget interface
7314: sub tmpget {
1.688 albertel 7315: my ($token,$server)=@_;
7316: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7317: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7318: my %returnhash;
1.1328 raeburn 7319: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7320: return %returnhash;
7321: }
1.667 albertel 7322: foreach my $item (split(/\&/,$rep)) {
7323: my ($key,$value)=split(/=/,$item);
7324: $returnhash{&unescape($key)}=&thaw_unescape($value);
7325: }
7326: return %returnhash;
7327: }
7328:
1.1113 raeburn 7329: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7330: sub tmpdel {
7331: my ($token,$server)=@_;
7332: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7333: return &reply("tmpdel:$token",$server);
7334: }
7335:
1.1198 raeburn 7336: # ------------------------------------------------------------ get_timebased_id
7337:
7338: sub get_timebased_id {
7339: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7340: $maxtries) = @_;
7341: my ($newid,$error,$dellock);
7342: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7343: return ('','ok','invalid call to get suffix');
7344: }
7345:
7346: # set defaults for any optional args for which values were not supplied
7347: if ($who eq '') {
7348: $who = $env{'user.name'}.':'.$env{'user.domain'};
7349: }
7350: if (!$locktries) {
7351: $locktries = 3;
7352: }
7353: if (!$maxtries) {
7354: $maxtries = 10;
7355: }
7356:
7357: if (($cdom eq '') || ($cnum eq '')) {
7358: if ($env{'request.course.id'}) {
7359: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7360: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7361: }
7362: if (($cdom eq '') || ($cnum eq '')) {
7363: return ('','ok','call to get suffix not in course context');
7364: }
7365: }
7366:
7367: # construct locking item
7368: my $lockhash = {
7369: $prefix."\0".'locked_'.$keyid => $who,
7370: };
7371: my $tries = 0;
7372:
7373: # attempt to get lock on nohist_$namespace file
7374: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7375: while (($gotlock ne 'ok') && $tries <$locktries) {
7376: $tries ++;
7377: sleep 1;
7378: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7379: }
7380:
7381: # attempt to get unique identifier, based on current timestamp
7382: if ($gotlock eq 'ok') {
7383: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7384: my $id = time;
7385: $newid = $id;
1.1268 raeburn 7386: if ($idtype eq 'addcode') {
7387: $newid .= &sixnum_code();
7388: }
1.1198 raeburn 7389: my $idtries = 0;
7390: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7391: if ($idtype eq 'concat') {
7392: $newid = $id.$idtries;
1.1268 raeburn 7393: } elsif ($idtype eq 'addcode') {
7394: $newid = $newid.&sixnum_code();
1.1198 raeburn 7395: } else {
7396: $newid ++;
7397: }
7398: $idtries ++;
7399: }
7400: if (!exists($inuse{$prefix."\0".$newid})) {
7401: my %new_item = (
7402: $prefix."\0".$newid => $who,
7403: );
7404: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7405: $cdom,$cnum);
7406: if ($putresult ne 'ok') {
7407: undef($newid);
7408: $error = 'error saving new item: '.$putresult;
7409: }
7410: } else {
1.1268 raeburn 7411: undef($newid);
1.1198 raeburn 7412: $error = ('error: no unique suffix available for the new item ');
7413: }
7414: # remove lock
7415: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7416: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7417: } else {
7418: $error = "error: could not obtain lockfile\n";
7419: $dellock = 'ok';
1.1276 raeburn 7420: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7421: $dellock = 'nolock';
7422: }
1.1198 raeburn 7423: }
7424: return ($newid,$dellock,$error);
7425: }
7426:
1.1268 raeburn 7427: sub sixnum_code {
7428: my $code;
7429: for (0..6) {
7430: $code .= int( rand(9) );
7431: }
7432: return $code;
7433: }
7434:
1.765 albertel 7435: # -------------------------------------------------- portfolio access checking
7436:
7437: sub portfolio_access {
1.1270 raeburn 7438: my ($requrl,$clientip) = @_;
1.765 albertel 7439: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7440: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7441: if ($result) {
7442: my %setters;
7443: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7444: my ($startblock,$endblock) =
7445: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7446: if ($startblock && $endblock) {
7447: return 'B';
7448: }
7449: } else {
7450: my ($startblock,$endblock) =
7451: &Apache::loncommon::blockcheck(\%setters,'port');
7452: if ($startblock && $endblock) {
7453: return 'B';
7454: }
7455: }
7456: }
1.765 albertel 7457: if ($result eq 'ok') {
1.766 albertel 7458: return 'F';
1.765 albertel 7459: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7460: return 'A';
1.765 albertel 7461: }
1.766 albertel 7462: return '';
1.765 albertel 7463: }
7464:
7465: sub get_portfolio_access {
1.1270 raeburn 7466: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7467:
7468: if (!ref($access_hash)) {
7469: my $current_perms = &get_portfile_permissions($udom,$unum);
7470: my %access_controls = &get_access_controls($current_perms,$group,
7471: $file_name);
7472: $access_hash = $access_controls{$file_name};
7473: }
7474:
1.1270 raeburn 7475: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7476: my $now = time;
7477: if (ref($access_hash) eq 'HASH') {
7478: foreach my $key (keys(%{$access_hash})) {
7479: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7480: if ($start > $now) {
7481: next;
7482: }
7483: if ($end && $end<$now) {
7484: next;
7485: }
7486: if ($scope eq 'public') {
7487: $public = $key;
7488: last;
7489: } elsif ($scope eq 'guest') {
7490: $guest = $key;
7491: } elsif ($scope eq 'domains') {
7492: push(@domains,$key);
7493: } elsif ($scope eq 'users') {
7494: push(@users,$key);
7495: } elsif ($scope eq 'course') {
7496: push(@courses,$key);
7497: } elsif ($scope eq 'group') {
7498: push(@groups,$key);
1.1270 raeburn 7499: } elsif ($scope eq 'ip') {
7500: push(@ips,$key);
1.765 albertel 7501: }
7502: }
7503: if ($public) {
7504: return 'ok';
1.1270 raeburn 7505: } elsif (@ips > 0) {
7506: my $allowed;
7507: foreach my $ipkey (@ips) {
7508: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7509: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7510: $allowed = 1;
7511: last;
7512: }
7513: }
7514: }
7515: if ($allowed) {
7516: return 'ok';
7517: }
1.765 albertel 7518: }
7519: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7520: if ($guest) {
7521: return $guest;
7522: }
7523: } else {
7524: if (@domains > 0) {
7525: foreach my $domkey (@domains) {
7526: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7527: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7528: return 'ok';
7529: }
7530: }
7531: }
7532: }
7533: if (@users > 0) {
7534: foreach my $userkey (@users) {
1.865 raeburn 7535: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7536: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7537: if (ref($item) eq 'HASH') {
7538: if (($item->{'uname'} eq $env{'user.name'}) &&
7539: ($item->{'udom'} eq $env{'user.domain'})) {
7540: return 'ok';
7541: }
7542: }
7543: }
7544: }
1.765 albertel 7545: }
7546: }
7547: my %roleshash;
7548: my @courses_and_groups = @courses;
7549: push(@courses_and_groups,@groups);
7550: if (@courses_and_groups > 0) {
7551: my (%allgroups,%allroles);
7552: my ($start,$end,$role,$sec,$group);
7553: foreach my $envkey (%env) {
1.1060 raeburn 7554: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7555: my $cid = $2.'_'.$3;
7556: if ($1 eq 'gr') {
7557: $group = $4;
7558: $allgroups{$cid}{$group} = $env{$envkey};
7559: } else {
7560: if ($4 eq '') {
7561: $sec = 'none';
7562: } else {
7563: $sec = $4;
7564: }
7565: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7566: }
1.811 albertel 7567: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7568: my $cid = $2.'_'.$3;
7569: if ($4 eq '') {
7570: $sec = 'none';
7571: } else {
7572: $sec = $4;
7573: }
7574: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7575: }
7576: }
7577: if (keys(%allroles) == 0) {
7578: return;
7579: }
7580: foreach my $key (@courses_and_groups) {
7581: my %content = %{$$access_hash{$key}};
7582: my $cnum = $content{'number'};
7583: my $cdom = $content{'domain'};
7584: my $cid = $cdom.'_'.$cnum;
7585: if (!exists($allroles{$cid})) {
7586: next;
7587: }
7588: foreach my $role_id (keys(%{$content{'roles'}})) {
7589: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7590: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7591: my @status = @{$content{'roles'}{$role_id}{'access'}};
7592: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7593: foreach my $role (keys(%{$allroles{$cid}})) {
7594: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7595: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7596: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7597: if (grep/^all$/,@sections) {
7598: return 'ok';
7599: } else {
7600: if (grep/^$sec$/,@sections) {
7601: return 'ok';
7602: }
7603: }
7604: }
7605: }
7606: if (keys(%{$allgroups{$cid}}) == 0) {
7607: if (grep/^none$/,@groups) {
7608: return 'ok';
7609: }
7610: } else {
7611: if (grep/^all$/,@groups) {
7612: return 'ok';
7613: }
7614: foreach my $group (keys(%{$allgroups{$cid}})) {
7615: if (grep/^$group$/,@groups) {
7616: return 'ok';
7617: }
7618: }
7619: }
7620: }
7621: }
7622: }
7623: }
7624: }
7625: if ($guest) {
7626: return $guest;
7627: }
7628: }
7629: }
7630: return;
7631: }
7632:
7633: sub course_group_datechecker {
7634: my ($dates,$now,$status) = @_;
7635: my ($start,$end) = split(/\./,$dates);
7636: if (!$start && !$end) {
7637: return 'ok';
7638: }
7639: if (grep/^active$/,@{$status}) {
7640: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7641: return 'ok';
7642: }
7643: }
7644: if (grep/^previous$/,@{$status}) {
7645: if ($end > $now ) {
7646: return 'ok';
7647: }
7648: }
7649: if (grep/^future$/,@{$status}) {
7650: if ($start > $now) {
7651: return 'ok';
7652: }
7653: }
7654: return;
7655: }
7656:
7657: sub parse_portfolio_url {
7658: my ($url) = @_;
7659:
7660: my ($type,$udom,$unum,$group,$file_name);
7661:
1.823 albertel 7662: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7663: $type = 1;
7664: $udom = $1;
7665: $unum = $2;
7666: $file_name = $3;
1.823 albertel 7667: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7668: $type = 2;
7669: $udom = $1;
7670: $unum = $2;
7671: $group = $3;
7672: $file_name = $3.'/'.$4;
7673: }
7674: if (wantarray) {
7675: return ($type,$udom,$unum,$file_name,$group);
7676: }
7677: return $type;
7678: }
7679:
7680: sub is_portfolio_url {
7681: my ($url) = @_;
7682: return scalar(&parse_portfolio_url($url));
7683: }
7684:
1.798 raeburn 7685: sub is_portfolio_file {
7686: my ($file) = @_;
1.820 raeburn 7687: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7688: return 1;
7689: }
7690: return;
7691: }
7692:
1.976 raeburn 7693: sub usertools_access {
1.1084 raeburn 7694: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7695: my ($access,%tools);
7696: if ($context eq '') {
7697: $context = 'tools';
7698: }
7699: if ($context eq 'requestcourses') {
7700: %tools = (
7701: official => 1,
7702: unofficial => 1,
1.1006 raeburn 7703: community => 1,
1.1246 raeburn 7704: textbook => 1,
1.1305 raeburn 7705: placement => 1,
1.1368 raeburn 7706: lti => 1,
1.985 raeburn 7707: );
1.1183 raeburn 7708: } elsif ($context eq 'requestauthor') {
7709: %tools = (
7710: requestauthor => 1,
7711: );
1.985 raeburn 7712: } else {
7713: %tools = (
7714: aboutme => 1,
7715: blog => 1,
1.1177 raeburn 7716: webdav => 1,
1.985 raeburn 7717: portfolio => 1,
7718: );
7719: }
1.976 raeburn 7720: return if (!defined($tools{$tool}));
7721:
1.1242 raeburn 7722: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7723: $udom = $env{'user.domain'};
7724: $uname = $env{'user.name'};
7725: }
7726:
1.978 raeburn 7727: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7728: if ($action ne 'reload') {
1.985 raeburn 7729: if ($context eq 'requestcourses') {
7730: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7731: } elsif ($context eq 'requestauthor') {
7732: return $env{'environment.canrequest.author'};
1.985 raeburn 7733: } else {
7734: return $env{'environment.availabletools.'.$tool};
7735: }
7736: }
1.976 raeburn 7737: }
7738:
1.1183 raeburn 7739: my ($toolstatus,$inststatus,$envkey);
7740: if ($context eq 'requestauthor') {
7741: $envkey = $context;
7742: } else {
7743: $envkey = $context.'.'.$tool;
7744: }
1.976 raeburn 7745:
1.985 raeburn 7746: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7747: ($action ne 'reload')) {
1.1183 raeburn 7748: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7749: $inststatus = $env{'environment.inststatus'};
7750: } else {
1.1084 raeburn 7751: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7752: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7753: $inststatus = $userenvref->{'inststatus'};
7754: } else {
1.1183 raeburn 7755: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7756: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7757: $inststatus = $userenv{'inststatus'};
7758: }
1.976 raeburn 7759: }
7760:
7761: if ($toolstatus ne '') {
7762: if ($toolstatus) {
7763: $access = 1;
7764: } else {
7765: $access = 0;
7766: }
7767: return $access;
7768: }
7769:
1.1084 raeburn 7770: my ($is_adv,%domdef);
7771: if (ref($is_advref) eq 'HASH') {
7772: $is_adv = $is_advref->{'is_adv'};
7773: } else {
7774: $is_adv = &is_advanced_user($udom,$uname);
7775: }
7776: if (ref($domdefref) eq 'HASH') {
7777: %domdef = %{$domdefref};
7778: } else {
7779: %domdef = &get_domain_defaults($udom);
7780: }
1.976 raeburn 7781: if (ref($domdef{$tool}) eq 'HASH') {
7782: if ($is_adv) {
7783: if ($domdef{$tool}{'_LC_adv'} ne '') {
7784: if ($domdef{$tool}{'_LC_adv'}) {
7785: $access = 1;
7786: } else {
7787: $access = 0;
7788: }
7789: return $access;
7790: }
7791: }
7792: if ($inststatus ne '') {
7793: my ($hasaccess,$hasnoaccess);
7794: foreach my $affiliation (split(/:/,$inststatus)) {
7795: if ($domdef{$tool}{$affiliation} ne '') {
7796: if ($domdef{$tool}{$affiliation}) {
7797: $hasaccess = 1;
7798: } else {
7799: $hasnoaccess = 1;
7800: }
7801: }
7802: }
7803: if ($hasaccess || $hasnoaccess) {
7804: if ($hasaccess) {
7805: $access = 1;
7806: } elsif ($hasnoaccess) {
7807: $access = 0;
7808: }
7809: return $access;
7810: }
7811: } else {
7812: if ($domdef{$tool}{'default'} ne '') {
7813: if ($domdef{$tool}{'default'}) {
7814: $access = 1;
7815: } elsif ($domdef{$tool}{'default'} == 0) {
7816: $access = 0;
7817: }
7818: return $access;
7819: }
7820: }
7821: } else {
1.1177 raeburn 7822: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7823: $access = 1;
7824: } else {
7825: $access = 0;
7826: }
1.976 raeburn 7827: return $access;
7828: }
7829: }
7830:
1.1050 raeburn 7831: sub is_course_owner {
7832: my ($cdom,$cnum,$udom,$uname) = @_;
7833: if (($udom eq '') || ($uname eq '')) {
7834: $udom = $env{'user.domain'};
7835: $uname = $env{'user.name'};
7836: }
7837: unless (($udom eq '') || ($uname eq '')) {
7838: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7839: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7840: return 1;
7841: } else {
7842: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7843: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7844: return 1;
7845: }
7846: }
7847: }
7848: }
7849: return;
7850: }
7851:
1.976 raeburn 7852: sub is_advanced_user {
7853: my ($udom,$uname) = @_;
1.1085 raeburn 7854: if ($udom ne '' && $uname ne '') {
7855: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7856: if (wantarray) {
7857: return ($env{'user.adv'},$env{'user.author'});
7858: } else {
7859: return $env{'user.adv'};
7860: }
1.1085 raeburn 7861: }
7862: }
1.976 raeburn 7863: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7864: my %allroles;
1.1128 raeburn 7865: my ($is_adv,$is_author);
1.976 raeburn 7866: foreach my $role (keys(%roleshash)) {
7867: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7868: my $area = '/'.$tdomain.'/'.$trest;
7869: if ($sec ne '') {
7870: $area .= '/'.$sec;
7871: }
7872: if (($area ne '') && ($trole ne '')) {
7873: my $spec=$trole.'.'.$area;
7874: if ($trole =~ /^cr\//) {
7875: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7876: } elsif ($trole ne 'gr') {
7877: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7878: }
1.1128 raeburn 7879: if ($trole eq 'au') {
7880: $is_author = 1;
7881: }
1.976 raeburn 7882: }
7883: }
7884: foreach my $role (keys(%allroles)) {
7885: last if ($is_adv);
7886: foreach my $item (split(/:/,$allroles{$role})) {
7887: if ($item ne '') {
7888: my ($privilege,$restrictions)=split(/&/,$item);
7889: if ($privilege eq 'adv') {
7890: $is_adv = 1;
7891: last;
7892: }
7893: }
7894: }
7895: }
1.1128 raeburn 7896: if (wantarray) {
7897: return ($is_adv,$is_author);
7898: }
1.976 raeburn 7899: return $is_adv;
7900: }
1.798 raeburn 7901:
1.1035 raeburn 7902: sub check_can_request {
1.1368 raeburn 7903: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 7904: my $canreq = 0;
1.1368 raeburn 7905: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7906: $uname = $env{'user.name'};
7907: $udom = $env{'user.domain'};
7908: }
1.1035 raeburn 7909: my ($types,$typename) = &Apache::loncommon::course_types();
7910: my @options = ('approval','validate','autolimit');
7911: my $optregex = join('|',@options);
7912: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7913: foreach my $type (@{$types}) {
1.1368 raeburn 7914: if (&usertools_access($uname,$udom,$type,undef,
7915: 'requestcourses')) {
1.1035 raeburn 7916: $canreq ++;
1.1036 raeburn 7917: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 7918: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 7919: }
1.1368 raeburn 7920: if ($dom eq $udom) {
1.1035 raeburn 7921: $can_request->{$type} = 1;
7922: }
7923: }
1.1368 raeburn 7924: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
7925: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 7926: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7927: if (@curr > 0) {
1.1036 raeburn 7928: foreach my $item (@curr) {
7929: if (ref($request_domains) eq 'HASH') {
7930: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7931: if ($otherdom ne '') {
7932: if (ref($request_domains->{$type}) eq 'ARRAY') {
7933: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7934: push(@{$request_domains->{$type}},$otherdom);
7935: }
7936: } else {
7937: push(@{$request_domains->{$type}},$otherdom);
7938: }
7939: }
7940: }
7941: }
1.1368 raeburn 7942: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 7943: $canreq ++;
1.1035 raeburn 7944: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7945: $can_request->{$type} = 1;
7946: }
7947: }
7948: }
7949: }
7950: }
7951: }
7952: return $canreq;
7953: }
7954:
1.341 www 7955: # ---------------------------------------------- Custom access rule evaluation
7956:
7957: sub customaccess {
7958: my ($priv,$uri)=@_;
1.807 albertel 7959: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7960: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7961: $udom = &LONCAPA::clean_domain($udom);
7962: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7963: my $access=0;
1.800 albertel 7964: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7965: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7966: if ($type eq 'user') {
7967: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7968: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7969: if ($tdom) {
7970: if ($tdom ne $env{'user.domain'}) { next; }
7971: }
1.896 albertel 7972: if ($tuname) {
7973: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7974: }
7975: $access=($effect eq 'allow');
7976: last;
7977: }
7978: } else {
7979: if ($role) {
7980: if ($role ne $urole) { next; }
7981: }
7982: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7983: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7984: if ($tdom) {
7985: if ($tdom ne $udom) { next; }
7986: }
7987: if ($tcrs) {
7988: if ($tcrs ne $ucrs) { next; }
7989: }
7990: if ($tsec) {
7991: if ($tsec ne $usec) { next; }
7992: }
7993: $access=($effect eq 'allow');
7994: last;
7995: }
7996: if ($realm eq '' && $role eq '') {
7997: $access=($effect eq 'allow');
7998: }
1.402 bowersj2 7999: }
1.341 www 8000: }
8001: return $access;
8002: }
8003:
1.103 harris41 8004: # ------------------------------------------------- Check for a user privilege
1.12 www 8005:
8006: sub allowed {
1.1281 raeburn 8007: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 8008: my $ver_orguri=$uri;
1.439 www 8009: $uri=&deversion($uri);
1.152 www 8010: my $orguri=$uri;
1.52 www 8011: $uri=&declutter($uri);
1.809 raeburn 8012:
1.810 raeburn 8013: if ($priv eq 'evb') {
8014: # Evade communication block restrictions for specified role in a course
8015: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8016: return $1;
8017: } else {
8018: return;
8019: }
8020: }
8021:
1.620 albertel 8022: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8023: # Free bre access to adm and meta resources
1.1343 raeburn 8024: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 8025: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8026: && ($priv eq 'bre')) {
1.14 www 8027: return 'F';
1.159 www 8028: }
8029:
1.545 banghart 8030: # Free bre access to user's own portfolio contents
1.714 raeburn 8031: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8032: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8033: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8034: my %setters;
8035: my ($startblock,$endblock) =
8036: &Apache::loncommon::blockcheck(\%setters,'port');
8037: if ($startblock && $endblock) {
8038: return 'B';
8039: } else {
8040: return 'F';
8041: }
1.545 banghart 8042: }
8043:
1.762 raeburn 8044: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8045: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8046: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8047: if (exists($env{'request.course.id'})) {
8048: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8049: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8050: if (($domain eq $cdom) && ($name eq $cnum)) {
8051: my $courseprivid=$env{'request.course.id'};
8052: $courseprivid=~s/\_/\//;
8053: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8054: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8055: return $1;
1.762 raeburn 8056: } else {
8057: if ($env{'request.course.sec'}) {
8058: $courseprivid.='/'.$env{'request.course.sec'};
8059: }
8060: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8061: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8062: return $2;
8063: }
1.714 raeburn 8064: }
8065: }
8066: }
8067: }
8068:
1.159 www 8069: # Free bre to public access
8070:
8071: if ($priv eq 'bre') {
1.1362 raeburn 8072: my $copyright;
8073: unless ($uri =~ /ext\.tool/) {
8074: $copyright=&metadata($uri,'copyright');
8075: }
1.620 albertel 8076: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8077: return 'F';
8078: }
1.238 www 8079: if ($copyright eq 'priv') {
8080: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8081: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8082: return '';
8083: }
8084: }
8085: if ($copyright eq 'domain') {
8086: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8087: unless (($env{'user.domain'} eq $1) ||
8088: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8089: return '';
8090: }
1.262 matthew 8091: }
1.620 albertel 8092: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8093: # Library role, so allow browsing of resources in this domain.
8094: return 'F';
1.238 www 8095: }
1.341 www 8096: if ($copyright eq 'custom') {
8097: unless (&customaccess($priv,$uri)) { return ''; }
8098: }
1.14 www 8099: }
1.264 matthew 8100: # Domain coordinator is trying to create a course
1.620 albertel 8101: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8102: # uri is the requested domain in this case.
8103: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8104: # a role of dc for the domain in question.
1.620 albertel 8105: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8106: }
1.29 www 8107:
1.52 www 8108: my $thisallowed='';
8109: my $statecond=0;
8110: my $courseprivid='';
8111:
1.1039 raeburn 8112: my $ownaccess;
1.1043 raeburn 8113: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8114: if (($priv eq 'bro') && ($env{'user.author'})) {
8115: if ($uri eq '') {
8116: $ownaccess = 1;
8117: } else {
8118: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8119: my $udom = $env{'user.domain'};
8120: my $uname = $env{'user.name'};
8121: if ($uri =~ m{^\Q$udom\E/?$}) {
8122: $ownaccess = 1;
1.1040 raeburn 8123: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8124: unless ($uri =~ m{\.\./}) {
8125: $ownaccess = 1;
8126: }
8127: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8128: my $now = time;
8129: if ($uri =~ m{^([^/]+)/?$}) {
8130: my $adom = $1;
8131: foreach my $key (keys(%env)) {
1.1042 raeburn 8132: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 8133: my ($start,$end) = split('.',$env{$key});
8134: if (($now >= $start) && (!$end || $end < $now)) {
8135: $ownaccess = 1;
8136: last;
8137: }
8138: }
8139: }
8140: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8141: my $adom = $1;
8142: my $aname = $2;
1.1042 raeburn 8143: foreach my $role ('ca','aa') {
8144: if ($env{"user.role.$role./$adom/$aname"}) {
8145: my ($start,$end) =
8146: split('.',$env{"user.role.$role./$adom/$aname"});
8147: if (($now >= $start) && (!$end || $end < $now)) {
8148: $ownaccess = 1;
8149: last;
8150: }
1.1039 raeburn 8151: }
8152: }
8153: }
8154: }
8155: }
8156: }
8157: }
8158:
1.52 www 8159: # Course
8160:
1.620 albertel 8161: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8162: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8163: $thisallowed.=$1;
8164: }
1.52 www 8165: }
1.29 www 8166:
1.52 www 8167: # Domain
8168:
1.620 albertel 8169: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8170: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8171: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8172: $thisallowed.=$1;
8173: }
1.12 www 8174: }
1.52 www 8175:
1.1141 raeburn 8176: # User who is not author or co-author might still be able to edit
8177: # resource of an author in the domain (e.g., if Domain Coordinator).
8178: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8179: (&allowed('mdc',$env{'request.course.id'}))) {
8180: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8181: $thisallowed.=$1;
8182: }
8183: }
8184:
1.52 www 8185: # Course: uri itself is a course
1.66 www 8186: my $courseuri=$uri;
8187: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8188: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8189:
1.620 albertel 8190: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8191: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8192: if ($priv eq 'mip') {
8193: my $rem = $1;
8194: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8195: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8196: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8197: if ($cdom ne '') {
1.1410 raeburn 8198: my %passwdconf = &get_passwdconf($cdom);
8199: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8200: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8201: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8202: my @inststatuses = split(':',$env{'environment.inststatus'});
8203: unless (@inststatuses) {
8204: @inststatuses = ('default');
8205: }
8206: foreach my $status (@inststatuses) {
8207: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8208: $thisallowed.=$rem;
8209: }
8210: }
8211: }
8212: }
1.1409 raeburn 8213: }
8214: }
8215: }
8216: } else {
8217: unless (($priv eq 'bro') && (!$ownaccess)) {
8218: $thisallowed.=$1;
8219: }
1.1039 raeburn 8220: }
1.12 www 8221: }
1.29 www 8222:
1.665 albertel 8223: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8224: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8225: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8226: $thisallowed='';
1.671 raeburn 8227: my ($match)=&is_on_map($uri);
8228: if ($match) {
8229: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8230: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8231: my $value = $1;
1.1402 raeburn 8232: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8233: if ($deeplinkblock) {
8234: $thisallowed='D';
8235: } elsif ($noblockcheck) {
1.1281 raeburn 8236: $thisallowed.=$value;
1.1162 raeburn 8237: } else {
1.1281 raeburn 8238: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8239: if (@blockers > 0) {
8240: $thisallowed = 'B';
8241: } else {
8242: $thisallowed.=$value;
8243: }
1.1162 raeburn 8244: }
1.671 raeburn 8245: }
8246: } else {
1.705 albertel 8247: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8248: if ($refuri) {
8249: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8250: $thisallowed='F';
1.671 raeburn 8251: } else {
8252: $refuri=&declutter($refuri);
8253: my ($match) = &is_on_map($refuri);
8254: if ($match) {
1.1402 raeburn 8255: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8256: if ($deeplinkblock) {
8257: $thisallowed='D';
8258: } elsif ($noblockcheck) {
1.1281 raeburn 8259: $thisallowed='F';
1.1162 raeburn 8260: } else {
1.1281 raeburn 8261: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8262: if (@blockers > 0) {
8263: $thisallowed = 'B';
8264: } else {
8265: $thisallowed='F';
8266: }
1.1162 raeburn 8267: }
1.671 raeburn 8268: }
1.669 raeburn 8269: }
1.671 raeburn 8270: }
8271: }
1.314 www 8272: }
1.492 albertel 8273:
1.766 albertel 8274: if ($priv eq 'bre'
8275: && $thisallowed ne 'F'
8276: && $thisallowed ne '2'
8277: && &is_portfolio_url($uri)) {
1.1270 raeburn 8278: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8279: }
1.1250 raeburn 8280:
1.52 www 8281: # Full access at system, domain or course-wide level? Exit.
1.29 www 8282: if ($thisallowed=~/F/) {
8283: return 'F';
8284: }
8285:
1.52 www 8286: # If this is generating or modifying users, exit with special codes
1.29 www 8287:
1.643 www 8288: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8289: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8290: my ($audom,$auname)=split('/',$uri);
1.643 www 8291: # no author name given, so this just checks on the general right to make a co-author in this domain
8292: unless ($auname) { return $thisallowed; }
8293: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8294: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8295: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8296: ($audom ne $env{'request.role.domain'}))) { return ''; }
8297: }
1.52 www 8298: return $thisallowed;
8299: }
8300: #
1.103 harris41 8301: # Gathered so far: system, domain and course wide privileges
1.52 www 8302: #
8303: # Course: See if uri or referer is an individual resource that is part of
8304: # the course
8305:
1.620 albertel 8306: if ($env{'request.course.id'}) {
1.232 www 8307:
1.1409 raeburn 8308: # If this is modifying password (internal auth) domains must match for user and user's role.
8309:
8310: if ($priv eq 'mip') {
8311: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8312: return $thisallowed;
8313: } else {
8314: return '';
8315: }
8316: }
8317:
1.620 albertel 8318: $courseprivid=$env{'request.course.id'};
8319: if ($env{'request.course.sec'}) {
8320: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8321: }
8322: $courseprivid=~s/\_/\//;
8323: my $checkreferer=1;
1.232 www 8324: my ($match,$cond)=&is_on_map($uri);
8325: if ($match) {
8326: $statecond=$cond;
1.620 albertel 8327: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8328: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8329: my $value = $1;
8330: if ($priv eq 'bre') {
1.1281 raeburn 8331: if ($noblockcheck) {
8332: $thisallowed.=$value;
1.1162 raeburn 8333: } else {
1.1281 raeburn 8334: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8335: if (@blockers > 0) {
8336: $thisallowed = 'B';
8337: } else {
8338: $thisallowed.=$value;
8339: }
1.1162 raeburn 8340: }
8341: } else {
8342: $thisallowed.=$value;
8343: }
1.52 www 8344: $checkreferer=0;
8345: }
1.29 www 8346: }
1.83 www 8347:
1.148 www 8348: if ($checkreferer) {
1.620 albertel 8349: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8350: unless ($refuri) {
1.800 albertel 8351: foreach my $key (keys(%env)) {
8352: if ($key=~/^httpref\..*\*/) {
8353: my $pattern=$key;
1.156 www 8354: $pattern=~s/^httpref\.\/res\///;
1.148 www 8355: $pattern=~s/\*/\[\^\/\]\+/g;
8356: $pattern=~s/\//\\\//g;
1.152 www 8357: if ($orguri=~/$pattern/) {
1.800 albertel 8358: $refuri=$env{$key};
1.148 www 8359: }
8360: }
1.191 harris41 8361: }
1.148 www 8362: }
1.232 www 8363:
1.148 www 8364: if ($refuri) {
1.152 www 8365: $refuri=&declutter($refuri);
1.232 www 8366: my ($match,$cond)=&is_on_map($refuri);
8367: if ($match) {
8368: my $refstatecond=$cond;
1.620 albertel 8369: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8370: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8371: my $value = $1;
8372: if ($priv eq 'bre') {
1.1402 raeburn 8373: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8374: if ($deeplinkblock) {
8375: $thisallowed = 'D';
8376: } elsif ($noblockcheck) {
1.1281 raeburn 8377: $thisallowed.=$value;
1.1162 raeburn 8378: } else {
1.1281 raeburn 8379: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8380: if (@blockers > 0) {
8381: $thisallowed = 'B';
8382: } else {
8383: $thisallowed.=$value;
8384: }
1.1162 raeburn 8385: }
8386: } else {
8387: $thisallowed.=$value;
8388: }
1.53 www 8389: $uri=$refuri;
8390: $statecond=$refstatecond;
1.52 www 8391: }
8392: }
1.148 www 8393: }
1.29 www 8394: }
1.52 www 8395: }
1.29 www 8396:
1.52 www 8397: #
1.103 harris41 8398: # Gathered now: all privileges that could apply, and condition number
1.52 www 8399: #
8400: #
8401: # Full or no access?
8402: #
1.29 www 8403:
1.52 www 8404: if ($thisallowed=~/F/) {
8405: return 'F';
8406: }
1.29 www 8407:
1.52 www 8408: unless ($thisallowed) {
8409: return '';
8410: }
1.29 www 8411:
1.52 www 8412: # Restrictions exist, deal with them
8413: #
8414: # C:according to course preferences
8415: # R:according to resource settings
8416: # L:unless locked
8417: # X:according to user session state
8418: #
8419:
8420: # Possibly locked functionality, check all courses
1.54 www 8421: # Locks might take effect only after 10 minutes cache expiration for other
8422: # courses, and 2 minutes for current course
1.52 www 8423:
8424: my $envkey;
8425: if ($thisallowed=~/L/) {
1.1000 raeburn 8426: foreach $envkey (keys(%env)) {
1.54 www 8427: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8428: my $courseid=$2;
8429: my $roleid=$1.'.'.$2;
1.92 www 8430: $courseid=~s/^\///;
1.54 www 8431: my $expiretime=600;
1.620 albertel 8432: if ($env{'request.role'} eq $roleid) {
1.54 www 8433: $expiretime=120;
8434: }
8435: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8436: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8437: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8438: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8439: }
1.620 albertel 8440: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8441: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8442: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8443: &log($env{'user.domain'},$env{'user.name'},
8444: $env{'user.home'},
1.57 www 8445: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8446: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8447: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8448: return '';
8449: }
8450: }
1.620 albertel 8451: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8452: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8453: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8454: &log($env{'user.domain'},$env{'user.name'},
8455: $env{'user.home'},
1.57 www 8456: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8457: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8458: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8459: return '';
8460: }
8461: }
8462: }
1.29 www 8463: }
1.52 www 8464: }
8465:
8466: #
8467: # Rest of the restrictions depend on selected course
8468: #
8469:
1.620 albertel 8470: unless ($env{'request.course.id'}) {
1.766 albertel 8471: if ($thisallowed eq 'A') {
8472: return 'A';
1.814 raeburn 8473: } elsif ($thisallowed eq 'B') {
8474: return 'B';
1.766 albertel 8475: } else {
8476: return '1';
8477: }
1.52 www 8478: }
1.29 www 8479:
1.52 www 8480: #
8481: # Now user is definitely in a course
8482: #
1.53 www 8483:
8484:
8485: # Course preferences
8486:
8487: if ($thisallowed=~/C/) {
1.620 albertel 8488: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8489: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8490: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8491: =~/\Q$rolecode\E/) {
1.1304 raeburn 8492: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8493: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8494: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8495: $env{'request.course.id'});
8496: }
1.237 www 8497: return '';
8498: }
8499:
1.620 albertel 8500: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8501: =~/\Q$unamedom\E/) {
1.1304 raeburn 8502: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8503: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8504: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8505: $env{'request.course.id'});
8506: }
1.54 www 8507: return '';
8508: }
1.53 www 8509: }
8510:
8511: # Resource preferences
8512:
8513: if ($thisallowed=~/R/) {
1.620 albertel 8514: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8515: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8516: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8517: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8518: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8519: }
8520: return '';
1.54 www 8521: }
1.53 www 8522: }
1.30 www 8523:
1.246 www 8524: # Restricted by state or randomout?
1.30 www 8525:
1.52 www 8526: if ($thisallowed=~/X/) {
1.620 albertel 8527: if ($env{'acc.randomout'}) {
1.579 albertel 8528: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8529: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8530: return '';
8531: }
1.247 www 8532: }
8533: if (&condval($statecond)) {
1.52 www 8534: return '2';
8535: } else {
8536: return '';
8537: }
8538: }
1.30 www 8539:
1.766 albertel 8540: if ($thisallowed eq 'A') {
8541: return 'A';
1.814 raeburn 8542: } elsif ($thisallowed eq 'B') {
8543: return 'B';
1.1402 raeburn 8544: } elsif ($thisallowed eq 'D') {
8545: return 'D';
1.766 albertel 8546: }
1.52 www 8547: return 'F';
1.232 www 8548: }
1.1162 raeburn 8549:
1.1192 raeburn 8550: # ------------------------------------------- Check construction space access
8551:
8552: sub constructaccess {
8553: my ($url,$setpriv)=@_;
8554:
8555: # We do not allow editing of previous versions of files
8556: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8557:
8558: # Get username and domain from URL
8559: my ($ownername,$ownerdomain,$ownerhome);
8560:
8561: ($ownerdomain,$ownername) =
1.1325 raeburn 8562: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8563:
8564: # The URL does not really point to any authorspace, forget it
8565: unless (($ownername) && ($ownerdomain)) { return ''; }
8566:
8567: # Now we need to see if the user has access to the authorspace of
8568: # $ownername at $ownerdomain
8569:
8570: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8571: # Real author for this?
8572: $ownerhome = $env{'user.home'};
8573: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8574: return ($ownername,$ownerdomain,$ownerhome);
8575: }
8576: } else {
8577: # Co-author for this?
8578: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8579: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8580: $ownerhome = &homeserver($ownername,$ownerdomain);
8581: return ($ownername,$ownerdomain,$ownerhome);
8582: }
1.1312 raeburn 8583: if ($env{'request.course.id'}) {
8584: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8585: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8586: if (&allowed('mdc',$env{'request.course.id'})) {
8587: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8588: return ($ownername,$ownerdomain,$ownerhome);
8589: }
8590: }
8591: }
1.1192 raeburn 8592: }
8593:
8594: # We don't have any access right now. If we are not possibly going to do anything about this,
8595: # we might as well leave
8596: unless ($setpriv) { return ''; }
8597:
8598: # Backdoor access?
8599: my $allowed=&allowed('eco',$ownerdomain);
8600: # Nope
8601: unless ($allowed) { return ''; }
8602: # Looks like we may have access, but could be locked by the owner of the construction space
8603: if ($allowed eq 'U') {
8604: my %blocked=&get('environment',['domcoord.author'],
8605: $ownerdomain,$ownername);
8606: # Is blocked by owner
8607: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8608: }
8609: if (($allowed eq 'F') || ($allowed eq 'U')) {
8610: # Grant temporary access
8611: my $then=$env{'user.login.time'};
1.1209 raeburn 8612: my $update=$env{'user.update.time'};
1.1192 raeburn 8613: if (!$update) { $update = $then; }
8614: my $refresh=$env{'user.refresh.time'};
8615: if (!$refresh) { $refresh = $update; }
8616: my $now = time;
8617: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8618: $now,'ca','constructaccess');
8619: $ownerhome = &homeserver($ownername,$ownerdomain);
8620: return($ownername,$ownerdomain,$ownerhome);
8621: }
8622: # No business here
8623: return '';
8624: }
8625:
1.1282 raeburn 8626: # ----------------------------------------------------------- Content Blocking
8627:
8628: {
8629: # Caches for faster Course Contents display where content blocking
8630: # is in operation (i.e., interval param set) for timed quiz.
8631: #
8632: # User for whom data are being temporarily cached.
8633: my $cacheduser='';
8634: # Cached blockers for this user (a hash of blocking items).
8635: my %cachedblockers=();
8636: # When the data were last cached.
8637: my $cachedlast='';
8638:
8639: sub load_all_blockers {
8640: my ($uname,$udom,$blocks)=@_;
8641: if (($uname ne '') && ($udom ne '')) {
8642: if (($cacheduser eq $uname.':'.$udom) &&
8643: (abs($cachedlast-time)<5)) {
8644: return;
8645: }
8646: }
8647: $cachedlast=time;
8648: $cacheduser=$uname.':'.$udom;
8649: %cachedblockers = &get_commblock_resources($blocks);
8650: }
8651:
1.1162 raeburn 8652: sub get_comm_blocks {
8653: my ($cdom,$cnum) = @_;
8654: if ($cdom eq '' || $cnum eq '') {
8655: return unless ($env{'request.course.id'});
8656: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8657: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8658: }
8659: my %commblocks;
8660: my $hashid=$cdom.'_'.$cnum;
8661: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8662: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8663: %commblocks = %{$blocksref};
8664: } else {
8665: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8666: my $cachetime = 600;
8667: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8668: }
8669: return %commblocks;
8670: }
8671:
1.1282 raeburn 8672: sub get_commblock_resources {
8673: my ($blocks) = @_;
8674: my %blockers = ();
8675: return %blockers unless ($env{'request.course.id'});
8676: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8677: my %commblocks;
8678: if (ref($blocks) eq 'HASH') {
8679: %commblocks = %{$blocks};
8680: } else {
8681: %commblocks = &get_comm_blocks();
8682: }
1.1282 raeburn 8683: return %blockers unless (keys(%commblocks) > 0);
8684: my $navmap = Apache::lonnavmaps::navmap->new();
8685: return %blockers unless (ref($navmap));
1.1162 raeburn 8686: my $now = time;
8687: foreach my $block (keys(%commblocks)) {
8688: if ($block =~ /^(\d+)____(\d+)$/) {
8689: my ($start,$end) = ($1,$2);
8690: if ($start <= $now && $end >= $now) {
8691: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8692: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8693: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8694: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8695: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8696: }
8697: }
8698: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8699: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8700: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8701: }
8702: }
8703: }
8704: }
8705: }
8706: } elsif ($block =~ /^firstaccess____(.+)$/) {
8707: my $item = $1;
1.1163 raeburn 8708: my @to_test;
1.1162 raeburn 8709: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8710: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8711: my @interval;
8712: my $type = 'map';
8713: if ($item eq 'course') {
8714: $type = 'course';
8715: @interval=&EXT("resource.0.interval");
8716: } else {
8717: if ($item =~ /___\d+___/) {
8718: $type = 'resource';
8719: @interval=&EXT("resource.0.interval",$item);
8720: if (ref($navmap)) {
8721: my $res = $navmap->getBySymb($item);
8722: push(@to_test,$res);
8723: }
1.1162 raeburn 8724: } else {
1.1282 raeburn 8725: my $mapsymb = &symbread($item,1);
8726: if ($mapsymb) {
8727: if (ref($navmap)) {
8728: my $mapres = $navmap->getBySymb($mapsymb);
8729: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8730: foreach my $res (@to_test) {
8731: my $symb = $res->symb();
8732: next if ($symb eq $mapsymb);
8733: if ($symb ne '') {
8734: @interval=&EXT("resource.0.interval",$symb);
8735: if ($interval[1] eq 'map') {
8736: last;
1.1162 raeburn 8737: }
8738: }
8739: }
8740: }
8741: }
8742: }
1.1282 raeburn 8743: }
1.1310 raeburn 8744: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8745: my $timelimit = $1;
1.1282 raeburn 8746: my $first_access;
8747: if ($type eq 'resource') {
8748: $first_access=&get_first_access($interval[1],$item);
8749: } elsif ($type eq 'map') {
8750: $first_access=&get_first_access($interval[1],undef,$item);
8751: } else {
8752: $first_access=&get_first_access($interval[1]);
8753: }
8754: if ($first_access) {
1.1292 raeburn 8755: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8756: if ($timesup > $now) {
8757: my $activeblock;
8758: foreach my $res (@to_test) {
1.1283 raeburn 8759: if ($res->answerable()) {
1.1282 raeburn 8760: $activeblock = 1;
8761: last;
8762: }
8763: }
8764: if ($activeblock) {
8765: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8766: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8767: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8768: }
8769: }
8770: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8771: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8772: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8773: }
1.1162 raeburn 8774: }
8775: }
8776: }
8777: }
8778: }
8779: }
8780: }
8781: }
8782: }
1.1282 raeburn 8783: return %blockers;
1.1162 raeburn 8784: }
8785:
1.1282 raeburn 8786: sub has_comm_blocking {
8787: my ($priv,$symb,$uri,$blocks) = @_;
8788: my @blockers;
8789: return unless ($env{'request.course.id'});
8790: return unless ($priv eq 'bre');
8791: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8792: return if ($env{'request.state'} eq 'construct');
8793: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8794: return unless (keys(%cachedblockers) > 0);
8795: my (%possibles,@symbs);
8796: if (!$symb) {
8797: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8798: }
1.1282 raeburn 8799: if ($symb) {
8800: @symbs = ($symb);
8801: } elsif (keys(%possibles)) {
8802: @symbs = keys(%possibles);
8803: }
8804: my $noblock;
8805: foreach my $symb (@symbs) {
8806: last if ($noblock);
8807: my ($map,$resid,$resurl)=&decode_symb($symb);
8808: foreach my $block (keys(%cachedblockers)) {
8809: if ($block =~ /^firstaccess____(.+)$/) {
8810: my $item = $1;
8811: if (($item eq $map) || ($item eq $symb)) {
8812: $noblock = 1;
8813: last;
8814: }
8815: }
8816: if (ref($cachedblockers{$block}) eq 'HASH') {
8817: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8818: if ($cachedblockers{$block}{'resources'}{$symb}) {
8819: unless (grep(/^\Q$block\E$/,@blockers)) {
8820: push(@blockers,$block);
8821: }
8822: }
8823: }
1.1162 raeburn 8824: }
1.1282 raeburn 8825: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8826: if ($cachedblockers{$block}{'maps'}{$map}) {
8827: unless (grep(/^\Q$block\E$/,@blockers)) {
8828: push(@blockers,$block);
8829: }
8830: }
1.1162 raeburn 8831: }
8832: }
8833: }
1.1282 raeburn 8834: return if ($noblock);
8835: return @blockers;
8836: }
1.1162 raeburn 8837: }
8838:
1.1402 raeburn 8839: sub deeplink_check {
8840: my ($priv,$symb,$uri) = @_;
8841: return unless ($env{'request.course.id'});
8842: return unless ($priv eq 'bre');
8843: return if ($env{'request.state'} eq 'construct');
8844: return if ($env{'request.role.adv'});
8845: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8846: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8847: my (%possibles,@symbs);
8848: if (!$symb) {
8849: $symb = &symbread($uri,1,1,1,\%possibles);
8850: }
8851: if ($symb) {
8852: @symbs = ($symb);
8853: } elsif (keys(%possibles)) {
8854: @symbs = keys(%possibles);
8855: }
8856:
8857: my ($login,$switchrole,$allow);
8858: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8859: my $key = $1;
8860: my $tinyurl;
8861: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8862: if (defined($cached)) {
8863: $tinyurl = $result;
8864: } else {
8865: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8866: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8867: if ($currtiny{$key} ne '') {
8868: $tinyurl = $currtiny{$key};
8869: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8870: }
8871: }
8872: if ($tinyurl ne '') {
8873: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8874: if ($cnumreq eq $cnum) {
8875: $login = $posslogin;
8876: } else {
8877: $switchrole = 1;
8878: }
8879: }
8880: }
8881: foreach my $symb (@symbs) {
8882: last if ($allow);
8883: my $deeplink = &EXT("resource.0.deeplink",$symb);
8884: if ($deeplink eq '') {
8885: $allow = 1;
8886: } else {
8887: my ($listed,$scope,$access) = split(/,/,$deeplink);
8888: if ($access eq 'any') {
8889: $allow = 1;
8890: } elsif ($login) {
8891: if ($access eq 'only') {
8892: if ($scope eq 'res') {
8893: if ($symb eq $login) {
8894: $allow = 1;
8895: }
8896: } elsif ($scope eq 'map') {
8897: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
8898: } elsif ($scope eq 'rec') {
8899: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
8900: }
8901: } else {
8902: my ($acctype,$item) = split(/:/,$access);
8903: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
8904: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
8905: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8906: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
8907: $allow = 1;
8908: }
8909: }
8910: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
8911: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
8912: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8913: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
8914: $allow = 1;
8915: }
8916: }
8917: }
8918: }
8919: }
8920: }
8921: }
8922: return if ($allow);
8923: return 1;
8924: }
8925:
1.1282 raeburn 8926: # -------------------------------- Deversion and split uri into path an filename
8927:
1.1133 foxr 8928: #
1.1282 raeburn 8929: # Removes the version from a URI and
1.1133 foxr 8930: # splits it in to its filename and path to the filename.
8931: # Seems like File::Basename could have done this more clearly.
8932: # Parameters:
8933: # $uri - input URI
8934: # Returns:
8935: # Two element list consisting of
8936: # $pathname - the URI up to and excluding the trailing /
8937: # $filename - The part of the URI following the last /
8938: # NOTE:
8939: # Another realization of this is simply:
8940: # use File::Basename;
8941: # ...
8942: # $uri = shift;
8943: # $filename = basename($uri);
8944: # $path = dirname($uri);
8945: # return ($filename, $path);
8946: #
8947: # The implementation below is probably faster however.
8948: #
1.710 albertel 8949: sub split_uri_for_cond {
8950: my $uri=&deversion(&declutter(shift));
8951: my @uriparts=split(/\//,$uri);
8952: my $filename=pop(@uriparts);
8953: my $pathname=join('/',@uriparts);
8954: return ($pathname,$filename);
8955: }
1.232 www 8956: # --------------------------------------------------- Is a resource on the map?
8957:
8958: sub is_on_map {
1.710 albertel 8959: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8960: #Trying to find the conditional for the file
1.620 albertel 8961: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8962: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8963: if ($match) {
1.289 bowersj2 8964: return (1,$1);
8965: } else {
1.434 www 8966: return (0,0);
1.289 bowersj2 8967: }
1.12 www 8968: }
8969:
1.427 www 8970: # --------------------------------------------------------- Get symb from alias
8971:
8972: sub get_symb_from_alias {
8973: my $symb=shift;
8974: my ($map,$resid,$url)=&decode_symb($symb);
8975: # Already is a symb
8976: if ($url) { return $symb; }
8977: # Must be an alias
8978: my $aliassymb='';
8979: my %bighash;
1.620 albertel 8980: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8981: &GDBM_READER(),0640)) {
8982: my $rid=$bighash{'mapalias_'.$symb};
8983: if ($rid) {
8984: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8985: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8986: $resid,$bighash{'src_'.$rid});
1.427 www 8987: }
8988: untie %bighash;
8989: }
8990: return $aliassymb;
8991: }
8992:
1.12 www 8993: # ----------------------------------------------------------------- Define Role
8994:
8995: sub definerole {
8996: if (allowed('mcr','/')) {
1.1326 raeburn 8997: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8998: foreach my $role (split(':',$sysrole)) {
8999: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9000: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9001: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9002: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9003: return "refused:s:$crole&$cqual";
9004: }
9005: }
1.191 harris41 9006: }
1.800 albertel 9007: foreach my $role (split(':',$domrole)) {
9008: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9009: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9010: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9011: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9012: return "refused:d:$crole&$cqual";
9013: }
9014: }
1.191 harris41 9015: }
1.800 albertel 9016: foreach my $role (split(':',$courole)) {
9017: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9018: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9019: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9020: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9021: return "refused:c:$crole&$cqual";
9022: }
9023: }
1.191 harris41 9024: }
1.1326 raeburn 9025: my $uhome;
9026: if (($uname ne '') && ($udom ne '')) {
9027: $uhome = &homeserver($uname,$udom);
9028: return $uhome if ($uhome eq 'no_host');
9029: } else {
9030: $uname = $env{'user.name'};
9031: $udom = $env{'user.domain'};
9032: $uhome = $env{'user.home'};
9033: }
1.620 albertel 9034: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9035: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9036: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9037: return reply($command,$uhome);
1.12 www 9038: } else {
9039: return 'refused';
9040: }
1.105 harris41 9041: }
9042:
9043: # ---------------- Make a metadata query against the network of library servers
9044:
9045: sub metadata_query {
1.1237 raeburn 9046: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9047: my %rhash;
1.845 albertel 9048: my %libserv = &all_library();
1.244 matthew 9049: my @server_list = (defined($server_array) ? @$server_array
9050: : keys(%libserv) );
9051: for my $server (@server_list) {
1.1237 raeburn 9052: my $domains = '';
9053: if (ref($domains_hash) eq 'HASH') {
9054: $domains = $domains_hash->{$server};
9055: }
1.118 harris41 9056: unless ($custom or $customshow) {
1.1237 raeburn 9057: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9058: $rhash{$server}=$reply;
9059: }
9060: else {
9061: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9062: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9063: $server);
9064: $rhash{$server}=$reply;
9065: }
1.112 harris41 9066: }
1.118 harris41 9067: return \%rhash;
1.240 www 9068: }
9069:
9070: # ----------------------------------------- Send log queries and wait for reply
9071:
9072: sub log_query {
9073: my ($uname,$udom,$query,%filters)=@_;
9074: my $uhome=&homeserver($uname,$udom);
9075: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9076: my $uhost=&hostname($uhome);
1.800 albertel 9077: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9078: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9079: $uhome);
1.479 albertel 9080: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9081: return get_query_reply($queryid);
9082: }
9083:
1.818 raeburn 9084: # -------------------------- Update MySQL table for portfolio file
9085:
9086: sub update_portfolio_table {
1.821 raeburn 9087: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9088: if ($group ne '') {
9089: $file_name =~s /^\Q$group\E//;
9090: }
1.818 raeburn 9091: my $homeserver = &homeserver($uname,$udom);
9092: my $queryid=
1.821 raeburn 9093: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9094: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9095: my $reply = &get_query_reply($queryid);
9096: return $reply;
9097: }
9098:
1.899 raeburn 9099: # -------------------------- Update MySQL allusers table
9100:
9101: sub update_allusers_table {
9102: my ($uname,$udom,$names) = @_;
9103: my $homeserver = &homeserver($uname,$udom);
9104: my $queryid=
9105: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9106: 'lastname='.&escape($names->{'lastname'}).'%%'.
9107: 'firstname='.&escape($names->{'firstname'}).'%%'.
9108: 'middlename='.&escape($names->{'middlename'}).'%%'.
9109: 'generation='.&escape($names->{'generation'}).'%%'.
9110: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9111: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9112: return;
1.899 raeburn 9113: }
9114:
1.508 raeburn 9115: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9116:
9117: sub fetch_enrollment_query {
1.511 raeburn 9118: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9119: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9120: my $maxtries = 1;
1.508 raeburn 9121: if ($context eq 'automated') {
9122: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9123: $sleep = 2;
9124: $loopmax = 100;
1.547 raeburn 9125: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9126: } else {
9127: $homeserver = &homeserver($cnum,$dom);
9128: }
1.838 albertel 9129: my $host=&hostname($homeserver);
1.506 raeburn 9130: my $cmd = '';
1.1000 raeburn 9131: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9132: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9133: }
9134: $cmd =~ s/%%$//;
9135: $cmd = &escape($cmd);
9136: my $query = 'fetchenrollment';
1.620 albertel 9137: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9138: unless ($queryid=~/^\Q$host\E\_/) {
9139: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9140: return 'error: '.$queryid;
9141: }
1.1317 raeburn 9142: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9143: my $tries = 1;
9144: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9145: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9146: $tries ++;
9147: }
1.526 raeburn 9148: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9149: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9150: } else {
1.901 albertel 9151: my @responses = split(/:/,$reply);
1.1322 raeburn 9152: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9153: foreach my $line (@responses) {
9154: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9155: $$replyref{$key} = $value;
9156: }
9157: } else {
1.1117 foxr 9158: my $pathname = LONCAPA::tempdir();
1.800 albertel 9159: foreach my $line (@responses) {
9160: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9161: $$replyref{$key} = $value;
9162: if ($value > 0) {
1.800 albertel 9163: foreach my $item (@{$$affiliatesref{$key}}) {
9164: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9165: my $destname = $pathname.'/'.$filename;
9166: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9167: if ($xml_classlist =~ /^error/) {
9168: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9169: } else {
1.1359 raeburn 9170: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9171: print FILE &unescape($xml_classlist);
9172: close(FILE);
1.526 raeburn 9173: } else {
9174: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9175: }
9176: }
9177: }
9178: }
9179: }
9180: }
9181: return 'ok';
9182: }
9183: return 'error';
9184: }
9185:
1.242 www 9186: sub get_query_reply {
1.1317 raeburn 9187: my ($queryid,$sleep,$loopmax) = @_;;
9188: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9189: $sleep = 0.2;
9190: }
9191: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9192: $loopmax = 100;
9193: }
1.1117 foxr 9194: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9195: my $reply='';
1.1317 raeburn 9196: for (1..$loopmax) {
9197: sleep($sleep);
1.240 www 9198: if (-e $replyfile.'.end') {
1.1359 raeburn 9199: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9200: $reply = join('',<$fh>);
9201: close($fh);
1.240 www 9202: } else { return 'error: reply_file_error'; }
1.242 www 9203: return &unescape($reply);
9204: }
1.240 www 9205: }
1.242 www 9206: return 'timeout:'.$queryid;
1.240 www 9207: }
9208:
9209: sub courselog_query {
1.241 www 9210: #
9211: # possible filters:
9212: # url: url or symb
9213: # username
9214: # domain
9215: # action: view, submit, grade
9216: # start: timestamp
9217: # end: timestamp
9218: #
1.240 www 9219: my (%filters)=@_;
1.620 albertel 9220: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9221: if ($filters{'url'}) {
9222: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9223: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9224: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9225: }
1.620 albertel 9226: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9227: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9228: return &log_query($cname,$cdom,'courselog',%filters);
9229: }
9230:
9231: sub userlog_query {
1.858 raeburn 9232: #
9233: # possible filters:
9234: # action: log check role
9235: # start: timestamp
9236: # end: timestamp
9237: #
1.240 www 9238: my ($uname,$udom,%filters)=@_;
9239: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9240: }
9241:
1.506 raeburn 9242: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9243:
9244: sub auto_run {
1.508 raeburn 9245: my ($cnum,$cdom) = @_;
1.876 raeburn 9246: my $response = 0;
9247: my $settings;
9248: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9249: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9250: $settings = $domconfig{'autoenroll'};
9251: if ($settings->{'run'} eq '1') {
9252: $response = 1;
9253: }
9254: } else {
1.934 raeburn 9255: my $homeserver;
9256: if (&is_course($cdom,$cnum)) {
9257: $homeserver = &homeserver($cnum,$cdom);
9258: } else {
9259: $homeserver = &domain($cdom,'primary');
9260: }
9261: if ($homeserver ne 'no_host') {
9262: $response = &reply('autorun:'.$cdom,$homeserver);
9263: }
1.876 raeburn 9264: }
1.506 raeburn 9265: return $response;
9266: }
1.776 albertel 9267:
1.506 raeburn 9268: sub auto_get_sections {
1.508 raeburn 9269: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9270: my $homeserver;
9271: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9272: $homeserver = &homeserver($cnum,$cdom);
9273: }
9274: if (!defined($homeserver)) {
9275: if ($cdom =~ /^$match_domain$/) {
9276: $homeserver = &domain($cdom,'primary');
9277: }
9278: }
9279: my @secs;
9280: if (defined($homeserver)) {
9281: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9282: unless ($response eq 'refused') {
9283: @secs = split(/:/,$response);
9284: }
1.506 raeburn 9285: }
9286: return @secs;
9287: }
1.776 albertel 9288:
1.506 raeburn 9289: sub auto_new_course {
1.1099 raeburn 9290: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9291: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9292: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9293: return $response;
9294: }
1.776 albertel 9295:
1.506 raeburn 9296: sub auto_validate_courseID {
1.508 raeburn 9297: my ($cnum,$cdom,$inst_course_id) = @_;
9298: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9299: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9300: return $response;
9301: }
1.776 albertel 9302:
1.1007 raeburn 9303: sub auto_validate_instcode {
1.1020 raeburn 9304: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9305: my ($homeserver,$response);
9306: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9307: $homeserver = &homeserver($cnum,$cdom);
9308: }
9309: if (!defined($homeserver)) {
9310: if ($cdom =~ /^$match_domain$/) {
9311: $homeserver = &domain($cdom,'primary');
9312: }
9313: }
1.1065 raeburn 9314: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9315: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9316: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9317: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9318: }
9319:
1.506 raeburn 9320: sub auto_create_password {
1.873 raeburn 9321: my ($cnum,$cdom,$authparam,$udom) = @_;
9322: my ($homeserver,$response);
1.506 raeburn 9323: my $create_passwd = 0;
9324: my $authchk = '';
1.873 raeburn 9325: if ($udom =~ /^$match_domain$/) {
9326: $homeserver = &domain($udom,'primary');
9327: }
9328: if ($homeserver eq '') {
9329: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9330: $homeserver = &homeserver($cnum,$cdom);
9331: }
9332: }
9333: if ($homeserver eq '') {
9334: $authchk = 'nodomain';
1.506 raeburn 9335: } else {
1.873 raeburn 9336: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9337: if ($response eq 'refused') {
9338: $authchk = 'refused';
9339: } else {
1.901 albertel 9340: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9341: }
1.506 raeburn 9342: }
9343: return ($authparam,$create_passwd,$authchk);
9344: }
9345:
1.706 raeburn 9346: sub auto_photo_permission {
9347: my ($cnum,$cdom,$students) = @_;
9348: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9349: my ($outcome,$perm_reqd,$conditions) =
9350: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9351: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9352: return (undef,undef);
9353: }
1.706 raeburn 9354: return ($outcome,$perm_reqd,$conditions);
9355: }
9356:
9357: sub auto_checkphotos {
9358: my ($uname,$udom,$pid) = @_;
9359: my $homeserver = &homeserver($uname,$udom);
9360: my ($result,$resulttype);
9361: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9362: &escape($uname).':'.&escape($pid),
9363: $homeserver));
1.709 albertel 9364: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9365: return (undef,undef);
9366: }
1.706 raeburn 9367: if ($outcome) {
9368: ($result,$resulttype) = split(/:/,$outcome);
9369: }
9370: return ($result,$resulttype);
9371: }
9372:
9373: sub auto_photochoice {
9374: my ($cnum,$cdom) = @_;
9375: my $homeserver = &homeserver($cnum,$cdom);
9376: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9377: &escape($cdom),
9378: $homeserver)));
1.709 albertel 9379: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9380: return (undef,undef);
9381: }
1.706 raeburn 9382: return ($update,$comment);
9383: }
9384:
9385: sub auto_photoupdate {
9386: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9387: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9388: my $host=&hostname($homeserver);
1.706 raeburn 9389: my $cmd = '';
9390: my $maxtries = 1;
1.800 albertel 9391: foreach my $affiliate (keys(%{$affiliatesref})) {
9392: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9393: }
9394: $cmd =~ s/%%$//;
9395: $cmd = &escape($cmd);
9396: my $query = 'institutionalphotos';
9397: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9398: unless ($queryid=~/^\Q$host\E\_/) {
9399: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9400: return 'error: '.$queryid;
9401: }
9402: my $reply = &get_query_reply($queryid);
9403: my $tries = 1;
9404: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9405: $reply = &get_query_reply($queryid);
9406: $tries ++;
9407: }
9408: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9409: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9410: } else {
9411: my @responses = split(/:/,$reply);
9412: my $outcome = shift(@responses);
9413: foreach my $item (@responses) {
9414: my ($key,$value) = split(/=/,$item);
9415: $$photo{$key} = $value;
9416: }
9417: return $outcome;
9418: }
9419: return 'error';
9420: }
9421:
1.521 raeburn 9422: sub auto_instcode_format {
1.793 albertel 9423: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9424: $cat_order) = @_;
1.521 raeburn 9425: my $courses = '';
1.772 raeburn 9426: my @homeservers;
1.521 raeburn 9427: if ($caller eq 'global') {
1.841 albertel 9428: my %servers = &get_servers($codedom,'library');
9429: foreach my $tryserver (keys(%servers)) {
9430: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9431: push(@homeservers,$tryserver);
9432: }
1.584 raeburn 9433: }
1.1022 raeburn 9434: } elsif ($caller eq 'requests') {
9435: if ($codedom =~ /^$match_domain$/) {
9436: my $chome = &domain($codedom,'primary');
9437: unless ($chome eq 'no_host') {
9438: push(@homeservers,$chome);
9439: }
9440: }
1.521 raeburn 9441: } else {
1.772 raeburn 9442: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9443: }
1.793 albertel 9444: foreach my $code (keys(%{$instcodes})) {
9445: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9446: }
9447: chop($courses);
1.772 raeburn 9448: my $ok_response = 0;
9449: my $response;
9450: while (@homeservers > 0 && $ok_response == 0) {
9451: my $server = shift(@homeservers);
9452: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9453: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9454: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9455: split(/:/,$response);
1.772 raeburn 9456: %{$codes} = (%{$codes},&str2hash($codes_str));
9457: push(@{$codetitles},&str2array($codetitles_str));
9458: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9459: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9460: $ok_response = 1;
9461: }
9462: }
9463: if ($ok_response) {
1.521 raeburn 9464: return 'ok';
1.772 raeburn 9465: } else {
9466: return $response;
1.521 raeburn 9467: }
9468: }
9469:
1.792 raeburn 9470: sub auto_instcode_defaults {
9471: my ($domain,$returnhash,$code_order) = @_;
9472: my @homeservers;
1.841 albertel 9473:
9474: my %servers = &get_servers($domain,'library');
9475: foreach my $tryserver (keys(%servers)) {
9476: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9477: push(@homeservers,$tryserver);
9478: }
1.792 raeburn 9479: }
1.841 albertel 9480:
1.792 raeburn 9481: my $response;
1.841 albertel 9482: foreach my $server (@homeservers) {
1.792 raeburn 9483: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9484: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9485:
9486: foreach my $pair (split(/\&/,$response)) {
9487: my ($name,$value)=split(/\=/,$pair);
9488: if ($name eq 'code_order') {
9489: @{$code_order} = split(/\&/,&unescape($value));
9490: } else {
9491: $returnhash->{&unescape($name)}=&unescape($value);
9492: }
9493: }
9494: return 'ok';
1.792 raeburn 9495: }
1.841 albertel 9496:
9497: return $response;
1.1003 raeburn 9498: }
9499:
9500: sub auto_possible_instcodes {
1.1007 raeburn 9501: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9502: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9503: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9504: return;
9505: }
1.1003 raeburn 9506: my (@homeservers,$uhome);
9507: if (defined(&domain($domain,'primary'))) {
9508: $uhome=&domain($domain,'primary');
9509: push(@homeservers,&domain($domain,'primary'));
9510: } else {
9511: my %servers = &get_servers($domain,'library');
9512: foreach my $tryserver (keys(%servers)) {
9513: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9514: push(@homeservers,$tryserver);
9515: }
9516: }
9517: }
9518: my $response;
9519: foreach my $server (@homeservers) {
9520: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9521: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9522: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9523: split(':',$response);
9524: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9525: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9526: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9527: my ($name,$value)=split('=',$item);
9528: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9529: }
9530: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9531: my ($name,$value)=split('=',$item);
9532: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9533: }
9534: return 'ok';
9535: }
9536: return $response;
9537: }
1.792 raeburn 9538:
1.1010 raeburn 9539: sub auto_courserequest_checks {
9540: my ($dom) = @_;
1.1020 raeburn 9541: my ($homeserver,%validations);
9542: if ($dom =~ /^$match_domain$/) {
9543: $homeserver = &domain($dom,'primary');
9544: }
9545: unless ($homeserver eq 'no_host') {
9546: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9547: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9548: my @items = split(/&/,$response);
9549: foreach my $item (@items) {
9550: my ($key,$value) = split('=',$item);
9551: $validations{&unescape($key)} = &thaw_unescape($value);
9552: }
9553: }
9554: }
1.1010 raeburn 9555: return %validations;
9556: }
9557:
1.1020 raeburn 9558: sub auto_courserequest_validation {
1.1255 raeburn 9559: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9560: my ($homeserver,$response);
9561: if ($dom =~ /^$match_domain$/) {
9562: $homeserver = &domain($dom,'primary');
9563: }
1.1255 raeburn 9564: unless ($homeserver eq 'no_host') {
9565: my $customdata;
9566: if (ref($custominfo) eq 'HASH') {
9567: $customdata = &freeze_escape($custominfo);
9568: }
1.1020 raeburn 9569: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9570: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9571: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9572: $customdata,$homeserver));
1.1020 raeburn 9573: }
9574: return $response;
9575: }
9576:
1.777 albertel 9577: sub auto_validate_class_sec {
1.918 raeburn 9578: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9579: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9580: my $ownerlist;
9581: if (ref($owners) eq 'ARRAY') {
9582: $ownerlist = join(',',@{$owners});
9583: } else {
9584: $ownerlist = $owners;
9585: }
1.773 raeburn 9586: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9587: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9588: return $response;
9589: }
9590:
1.1367 raeburn 9591: sub auto_validate_instclasses {
9592: my ($cdom,$cnum,$owners,$classesref) = @_;
9593: my ($homeserver,%validations);
9594: $homeserver = &homeserver($cnum,$cdom);
9595: unless ($homeserver eq 'no_host') {
9596: my $ownerlist;
9597: if (ref($owners) eq 'ARRAY') {
9598: $ownerlist = join(',',@{$owners});
9599: } else {
9600: $ownerlist = $owners;
9601: }
9602: if (ref($classesref) eq 'HASH') {
9603: my $classes = &freeze_escape($classesref);
9604: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9605: ':'.$cdom.':'.$classes,$homeserver);
9606: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9607: my @items = split(/&/,$response);
9608: foreach my $item (@items) {
9609: my ($key,$value) = split('=',$item);
9610: $validations{&unescape($key)} = &thaw_unescape($value);
9611: }
9612: }
9613: }
9614: }
9615: return %validations;
9616: }
9617:
1.1248 raeburn 9618: sub auto_crsreq_update {
9619: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9620: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9621: my ($homeserver,%crsreqresponse);
9622: if ($cdom =~ /^$match_domain$/) {
9623: $homeserver = &domain($cdom,'primary');
9624: }
9625: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9626: my $info;
9627: if (ref($inbound) eq 'HASH') {
9628: $info = &freeze_escape($inbound);
9629: }
9630: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9631: ':'.&escape($action).':'.&escape($ownername).':'.
9632: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9633: &escape($title).':'.&escape($code).':'.
9634: &escape($accessstart).':'.&escape($accessend).':'.$info,
9635: $homeserver);
1.1248 raeburn 9636: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9637: my @items = split(/&/,$response);
9638: foreach my $item (@items) {
9639: my ($key,$value) = split('=',$item);
9640: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9641: }
9642: }
9643: }
9644: return \%crsreqresponse;
9645: }
9646:
1.1305 raeburn 9647: sub auto_export_grades {
1.1309 raeburn 9648: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9649: my ($homeserver,%exportresponse);
9650: if ($cdom =~ /^$match_domain$/) {
9651: $homeserver = &domain($cdom,'primary');
9652: }
9653: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9654: my $info;
9655: if (ref($inforef) eq 'HASH') {
9656: $info = &freeze_escape($inforef);
9657: }
9658: if (ref($gradesref) eq 'HASH') {
9659: my $grades = &freeze_escape($gradesref);
9660: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9661: $info.':'.$grades,$homeserver);
9662: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9663: my @items = split(/&/,$response);
9664: foreach my $item (@items) {
9665: my ($key,$value) = split('=',$item);
9666: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9667: }
9668: }
9669: }
9670: }
9671: return \%exportresponse;
1.1305 raeburn 9672: }
9673:
1.1287 raeburn 9674: sub check_instcode_cloning {
9675: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9676: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9677: return;
9678: }
9679: my $canclone;
9680: if (@{$code_order} > 0) {
9681: my $instcoderegexp ='^';
9682: my @clonecodes = split(/\&/,$cloner);
9683: foreach my $item (@{$code_order}) {
9684: if (grep(/^\Q$item\E=/,@clonecodes)) {
9685: foreach my $pair (@clonecodes) {
9686: my ($key,$val) = split(/\=/,$pair,2);
9687: $val = &unescape($val);
9688: if ($key eq $item) {
9689: $instcoderegexp .= '('.$val.')';
9690: last;
9691: }
9692: }
9693: } else {
9694: $instcoderegexp .= $codedefaults->{$item};
9695: }
9696: }
9697: $instcoderegexp .= '$';
9698: my (@from,@to);
9699: eval {
9700: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9701: (@to) = ($clonetocode =~ /$instcoderegexp/);
9702: };
9703: if ((@from > 0) && (@to > 0)) {
9704: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9705: if (!@diffs) {
9706: $canclone = 1;
9707: }
9708: }
9709: }
9710: return $canclone;
9711: }
9712:
9713: sub default_instcode_cloning {
9714: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9715: my (%codedefaults,@code_order,$canclone);
9716: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9717: %codedefaults = %{$codedefaultsref};
9718: @code_order = @{$codeorderref};
9719: } elsif ($clonedom) {
9720: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9721: }
9722: if (($domdefclone) && (@code_order)) {
9723: my @clonecodes = split(/\+/,$domdefclone);
9724: my $instcoderegexp ='^';
9725: foreach my $item (@code_order) {
9726: if (grep(/^\Q$item\E$/,@clonecodes)) {
9727: $instcoderegexp .= '('.$codedefaults{$item}.')';
9728: } else {
9729: $instcoderegexp .= $codedefaults{$item};
9730: }
9731: }
9732: $instcoderegexp .= '$';
9733: my (@from,@to);
9734: eval {
9735: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9736: (@to) = ($clonetocode =~ /$instcoderegexp/);
9737: };
9738: if ((@from > 0) && (@to > 0)) {
9739: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9740: if (!@diffs) {
9741: $canclone = 1;
9742: }
9743: }
9744: }
9745: return $canclone;
9746: }
9747:
1.679 raeburn 9748: # ------------------------------------------------------- Course Group routines
9749:
9750: sub get_coursegroups {
1.809 raeburn 9751: my ($cdom,$cnum,$group,$namespace) = @_;
9752: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9753: }
9754:
1.679 raeburn 9755: sub modify_coursegroup {
9756: my ($cdom,$cnum,$groupsettings) = @_;
9757: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9758: }
9759:
1.809 raeburn 9760: sub toggle_coursegroup_status {
9761: my ($cdom,$cnum,$group,$action) = @_;
9762: my ($from_namespace,$to_namespace);
9763: if ($action eq 'delete') {
9764: $from_namespace = 'coursegroups';
9765: $to_namespace = 'deleted_groups';
9766: } else {
9767: $from_namespace = 'deleted_groups';
9768: $to_namespace = 'coursegroups';
9769: }
9770: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9771: if (my $tmp = &error(%curr_group)) {
9772: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9773: return ('read error',$tmp);
9774: } else {
9775: my %savedsettings = %curr_group;
1.809 raeburn 9776: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9777: my $deloutcome;
9778: if ($result eq 'ok') {
1.809 raeburn 9779: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9780: } else {
9781: return ('write error',$result);
9782: }
9783: if ($deloutcome eq 'ok') {
9784: return 'ok';
9785: } else {
9786: return ('delete error',$deloutcome);
9787: }
9788: }
9789: }
9790:
1.679 raeburn 9791: sub modify_group_roles {
1.957 raeburn 9792: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9793: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9794: my $role = 'gr/'.&escape($userprivs);
9795: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9796: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9797: if ($result eq 'ok') {
9798: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9799: }
1.679 raeburn 9800: return $result;
9801: }
9802:
9803: sub modify_coursegroup_membership {
9804: my ($cdom,$cnum,$membership) = @_;
9805: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9806: return $result;
9807: }
9808:
1.682 raeburn 9809: sub get_active_groups {
9810: my ($udom,$uname,$cdom,$cnum) = @_;
9811: my $now = time;
9812: my %groups = ();
9813: foreach my $key (keys(%env)) {
1.811 albertel 9814: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9815: my ($start,$end) = split(/\./,$env{$key});
9816: if (($end!=0) && ($end<$now)) { next; }
9817: if (($start!=0) && ($start>$now)) { next; }
9818: if ($1 eq $cdom && $2 eq $cnum) {
9819: $groups{$3} = $env{$key} ;
9820: }
9821: }
9822: }
9823: return %groups;
9824: }
9825:
1.683 raeburn 9826: sub get_group_membership {
9827: my ($cdom,$cnum,$group) = @_;
9828: return(&dump('groupmembership',$cdom,$cnum,$group));
9829: }
9830:
9831: sub get_users_groups {
9832: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9833: my @usersgroups;
1.683 raeburn 9834: my $cachetime=1800;
9835:
9836: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9837: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9838: if (defined($cached)) {
1.734 albertel 9839: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9840: } else {
9841: $grouplist = '';
1.816 raeburn 9842: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9843: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9844: my $access_end = $env{'course.'.$courseid.
9845: '.default_enrollment_end_date'};
9846: my $now = time;
9847: foreach my $key (keys(%roleshash)) {
9848: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9849: my $group = $1;
9850: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9851: my $start = $2;
9852: my $end = $1;
9853: if ($start == -1) { next; } # deleted from group
9854: if (($start!=0) && ($start>$now)) { next; }
9855: if (($end!=0) && ($end<$now)) {
9856: if ($access_end && $access_end < $now) {
9857: if ($access_end - $end < 86400) {
9858: push(@usersgroups,$group);
1.733 raeburn 9859: }
9860: }
1.817 raeburn 9861: next;
1.733 raeburn 9862: }
1.817 raeburn 9863: push(@usersgroups,$group);
1.683 raeburn 9864: }
9865: }
9866: }
1.817 raeburn 9867: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9868: $grouplist = join(':',@usersgroups);
9869: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9870: }
1.733 raeburn 9871: return @usersgroups;
1.683 raeburn 9872: }
9873:
9874: sub devalidate_getgroups_cache {
9875: my ($udom,$uname,$cdom,$cnum)=@_;
9876: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9877:
1.683 raeburn 9878: my $hashid="$udom:$uname:$courseid";
9879: &devalidate_cache_new('getgroups',$hashid);
9880: }
9881:
1.12 www 9882: # ------------------------------------------------------------------ Plain Text
9883:
9884: sub plaintext {
1.988 raeburn 9885: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9886: if ($short =~ m{^cr/}) {
1.758 albertel 9887: return (split('/',$short))[-1];
9888: }
1.742 raeburn 9889: if (!defined($cid)) {
9890: $cid = $env{'request.course.id'};
9891: }
9892: my %rolenames = (
1.1008 raeburn 9893: Course => 'std',
9894: Community => 'alt1',
1.1305 raeburn 9895: Placement => 'std',
1.742 raeburn 9896: );
1.1037 raeburn 9897: if ($cid ne '') {
9898: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9899: unless ($forcedefault) {
9900: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9901: &Apache::lonlocal::mt_escape(\$roletext);
9902: return &Apache::lonlocal::mt($roletext);
9903: }
9904: }
9905: }
9906: if ((defined($type)) && (defined($rolenames{$type})) &&
9907: (defined($rolenames{$type})) &&
9908: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9909: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9910: } elsif ($cid ne '') {
9911: my $crstype = $env{'course.'.$cid.'.type'};
9912: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9913: (defined($prp{$short}{$rolenames{$crstype}}))) {
9914: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9915: }
1.742 raeburn 9916: }
1.1037 raeburn 9917: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9918: }
9919:
9920: # ----------------------------------------------------------------- Assign Role
9921:
9922: sub assignrole {
1.957 raeburn 9923: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9924: $context)=@_;
1.21 www 9925: my $mrole;
9926: if ($role =~ /^cr\//) {
1.393 www 9927: my $cwosec=$url;
1.811 albertel 9928: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9929: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9930: my $refused = 1;
9931: if ($context eq 'requestcourses') {
9932: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9933: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9934: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9935: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9936: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9937: if ($crsenv{'internal.courseowner'} eq
9938: $env{'user.name'}.':'.$env{'user.domain'}) {
9939: $refused = '';
9940: }
9941: }
9942: }
9943: }
9944: }
9945: if ($refused) {
9946: &logthis('Refused custom assignrole: '.
9947: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9948: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9949: return 'refused';
9950: }
1.104 www 9951: }
1.21 www 9952: $mrole='cr';
1.678 raeburn 9953: } elsif ($role =~ /^gr\//) {
9954: my $cwogrp=$url;
1.811 albertel 9955: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9956: unless (&allowed('mdg',$cwogrp)) {
9957: &logthis('Refused group assignrole: '.
9958: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9959: $env{'user.name'}.' at '.$env{'user.domain'});
9960: return 'refused';
9961: }
9962: $mrole='gr';
1.21 www 9963: } else {
1.82 www 9964: my $cwosec=$url;
1.811 albertel 9965: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9966: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9967: my $refused;
9968: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9969: if (!(&allowed('c'.$role,$url))) {
9970: $refused = 1;
9971: }
9972: } else {
9973: $refused = 1;
9974: }
1.947 raeburn 9975: if ($refused) {
1.1045 raeburn 9976: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 9977: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 9978: my %crsenv;
9979: if ($role eq 'cc' || $role eq 'co') {
9980: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9981: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9982: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9983: if ($crsenv{'internal.courseowner'} eq
9984: $env{'user.name'}.':'.$env{'user.domain'}) {
9985: $refused = '';
9986: }
9987: }
9988: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9989: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9990: if ($crsenv{'internal.courseowner'} eq
9991: $env{'user.name'}.':'.$env{'user.domain'}) {
9992: $refused = '';
9993: }
9994: }
9995: }
9996: }
1.1368 raeburn 9997: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9998: if ($role eq 'st') {
9999: $refused = '';
1.1377 raeburn 10000: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10001: $refused = '';
10002: }
1.1017 raeburn 10003: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10004: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10005: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10006: my $wrongcc;
10007: if ($cnum =~ /^$match_community$/) {
10008: $wrongcc = 1 if ($role eq 'cc');
10009: } else {
10010: $wrongcc = 1 if ($role eq 'co');
10011: }
10012: unless ($wrongcc) {
10013: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10014: if ($crsenv{'internal.courseowner'} eq
10015: $env{'user.name'}.':'.$env{'user.domain'}) {
10016: $refused = '';
10017: }
1.1017 raeburn 10018: }
10019: }
1.1183 raeburn 10020: } elsif ($context eq 'requestauthor') {
10021: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10022: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10023: if ($env{'environment.requestauthor'} eq 'automatic') {
10024: $refused = '';
10025: } else {
10026: my %domdefaults = &get_domain_defaults($udom);
10027: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10028: my $checkbystatus;
10029: if ($env{'user.adv'}) {
10030: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10031: if ($disposition eq 'automatic') {
10032: $refused = '';
10033: } elsif ($disposition eq '') {
10034: $checkbystatus = 1;
10035: }
10036: } else {
10037: $checkbystatus = 1;
10038: }
10039: if ($checkbystatus) {
10040: if ($env{'environment.inststatus'}) {
10041: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10042: foreach my $type (@inststatuses) {
10043: if (($type ne '') &&
10044: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10045: $refused = '';
10046: }
10047: }
10048: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10049: $refused = '';
10050: }
10051: }
10052: }
10053: }
10054: }
1.1017 raeburn 10055: }
10056: if ($refused) {
1.947 raeburn 10057: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10058: ' '.$role.' '.$end.' '.$start.' by '.
10059: $env{'user.name'}.' at '.$env{'user.domain'});
10060: return 'refused';
10061: }
1.932 raeburn 10062: }
1.1131 raeburn 10063: } elsif ($role eq 'au') {
10064: if ($url ne '/'.$udom.'/') {
10065: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10066: ' to assign author role for '.$uname.':'.$udom.
10067: ' in domain: '.$url.' refused (wrong domain).');
10068: return 'refused';
10069: }
1.104 www 10070: }
1.21 www 10071: $mrole=$role;
10072: }
1.620 albertel 10073: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10074: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10075: if ($end) { $command.='_'.$end; }
1.21 www 10076: if ($start) {
10077: if ($end) {
1.81 www 10078: $command.='_'.$start;
1.21 www 10079: } else {
1.81 www 10080: $command.='_0_'.$start;
1.21 www 10081: }
10082: }
1.739 raeburn 10083: my $origstart = $start;
10084: my $origend = $end;
1.957 raeburn 10085: my $delflag;
1.357 www 10086: # actually delete
10087: if ($deleteflag) {
1.373 www 10088: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10089: # modify command to delete the role
1.620 albertel 10090: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10091: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10092: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10093: # set start and finish to negative values for userrolelog
10094: $start=-1;
10095: $end=-1;
1.957 raeburn 10096: $delflag = 1;
1.357 www 10097: }
10098: }
10099: # send command
1.349 www 10100: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10101: # log new user role if status is ok
1.349 www 10102: if ($answer eq 'ok') {
1.663 raeburn 10103: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10104: if (($role eq 'cc') || ($role eq 'in') ||
10105: ($role eq 'ep') || ($role eq 'ad') ||
10106: ($role eq 'ta') || ($role eq 'st') ||
10107: ($role=~/^cr/) || ($role eq 'gr') ||
10108: ($role eq 'co')) {
1.1200 raeburn 10109: # for course roles, perform group memberships changes triggered by role change.
10110: unless ($role =~ /^gr/) {
10111: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10112: $origstart,$selfenroll,$context);
10113: }
1.1184 raeburn 10114: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10115: $selfenroll,$context);
10116: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10117: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10118: ($role eq 'da')) {
1.1184 raeburn 10119: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10120: $context);
10121: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10122: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10123: $context);
10124: }
1.1053 raeburn 10125: if ($role eq 'cc') {
10126: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10127: }
1.349 www 10128: }
10129: return $answer;
1.169 harris41 10130: }
10131:
1.1053 raeburn 10132: sub autoupdate_coowners {
10133: my ($url,$end,$start,$uname,$udom) = @_;
10134: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10135: if (($cdom ne '') && ($cnum ne '')) {
10136: my $now = time;
10137: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10138: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10139: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10140: my $instcode = $coursehash{'internal.coursecode'};
10141: if ($instcode ne '') {
1.1056 raeburn 10142: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10143: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10144: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10145: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10146: if ($result eq 'valid') {
10147: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10148: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10149: push(@newcoowners,$coowner);
10150: }
10151: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10152: push(@newcoowners,$uname.':'.$udom);
10153: }
10154: @newcoowners = sort(@newcoowners);
10155: } else {
10156: push(@newcoowners,$uname.':'.$udom);
10157: }
10158: } else {
10159: if ($coursehash{'internal.co-owners'}) {
10160: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10161: unless ($coowner eq $uname.':'.$udom) {
10162: push(@newcoowners,$coowner);
10163: }
10164: }
10165: unless (@newcoowners > 0) {
10166: $delcoowners = 1;
10167: $coowners = '';
10168: }
10169: }
10170: }
10171: if (@newcoowners || $delcoowners) {
10172: &store_coowners($cdom,$cnum,$coursehash{'home'},
10173: $delcoowners,@newcoowners);
10174: }
10175: }
10176: }
10177: }
10178: }
10179: }
10180: }
10181:
10182: sub store_coowners {
10183: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10184: my $cid = $cdom.'_'.$cnum;
10185: my ($coowners,$delresult,$putresult);
10186: if (@newcoowners) {
10187: $coowners = join(',',@newcoowners);
10188: my %coownershash = (
10189: 'internal.co-owners' => $coowners,
10190: );
10191: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10192: if ($putresult eq 'ok') {
10193: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10194: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10195: }
10196: }
10197: }
10198: if ($delcoowners) {
10199: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10200: if ($delresult eq 'ok') {
10201: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10202: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10203: }
10204: }
10205: }
10206: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10207: my %crsinfo =
10208: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10209: if (ref($crsinfo{$cid}) eq 'HASH') {
10210: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10211: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10212: }
10213: }
10214: }
10215:
1.169 harris41 10216: # -------------------------------------------------- Modify user authentication
1.197 www 10217: # Overrides without validation
10218:
1.169 harris41 10219: sub modifyuserauth {
10220: my ($udom,$uname,$umode,$upass)=@_;
10221: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10222: my $allowed;
10223: if (&allowed('mau',$udom)) {
10224: $allowed = 1;
10225: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10226: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10227: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10228: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10229: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10230: if (($cdom ne '') && ($cnum ne '')) {
10231: my $is_owner = &is_course_owner($cdom,$cnum);
10232: if ($is_owner) {
10233: $allowed = 1;
10234: }
10235: }
10236: }
10237: unless ($allowed) { return 'refused'; }
1.197 www 10238: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10239: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10240: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10241: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10242: &escape($upass),$uhome);
1.620 albertel 10243: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10244: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10245: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10246: &log($udom,,$uname,$uhome,
1.620 albertel 10247: 'Authentication changed by '.$env{'user.domain'}.', '.
10248: $env{'user.name'}.', '.$umode.
1.197 www 10249: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 10250: unless ($reply eq 'ok') {
1.197 www 10251: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10252: return 'error: '.$reply;
10253: }
1.170 harris41 10254: return 'ok';
1.80 www 10255: }
10256:
1.81 www 10257: # --------------------------------------------------------------- Modify a user
1.80 www 10258:
1.81 www 10259: sub modifyuser {
1.206 matthew 10260: my ($udom, $uname, $uid,
10261: $umode, $upass, $first,
10262: $middle, $last, $gene,
1.1058 raeburn 10263: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10264: $udom= &LONCAPA::clean_domain($udom);
10265: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10266: my $showcandelete = 'none';
10267: if (ref($candelete) eq 'ARRAY') {
10268: if (@{$candelete} > 0) {
10269: $showcandelete = join(', ',@{$candelete});
10270: }
10271: }
1.81 www 10272: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10273: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10274: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10275: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10276: ' desiredhome not specified').
1.620 albertel 10277: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10278: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10279: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10280: my $newuser;
10281: if ($uhome eq 'no_host') {
10282: $newuser = 1;
1.1368 raeburn 10283: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10284: ($umode eq 'lti')) {
10285: return 'error: more information needed to create new user';
10286: }
1.1075 raeburn 10287: }
1.80 www 10288: # ----------------------------------------------------------------- Create User
1.406 albertel 10289: if (($uhome eq 'no_host') &&
1.1368 raeburn 10290: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10291: my $unhome='';
1.844 albertel 10292: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10293: $unhome = $desiredhome;
1.620 albertel 10294: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10295: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10296: } else { # load balancing routine for determining $unhome
1.81 www 10297: my $loadm=10000000;
1.841 albertel 10298: my %servers = &get_servers($udom,'library');
10299: foreach my $tryserver (keys(%servers)) {
10300: my $answer=reply('load',$tryserver);
10301: if (($answer=~/\d+/) && ($answer<$loadm)) {
10302: $loadm=$answer;
10303: $unhome=$tryserver;
10304: }
1.80 www 10305: }
10306: }
10307: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10308: return 'error: unable to find a home server for '.$uname.
10309: ' in domain '.$udom;
1.80 www 10310: }
10311: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10312: &escape($upass),$unhome);
10313: unless ($reply eq 'ok') {
10314: return 'error: '.$reply;
10315: }
1.230 stredwic 10316: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10317: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10318: return 'error: unable verify users home machine.';
1.80 www 10319: }
1.209 matthew 10320: } # End of creation of new user
1.80 www 10321: # ---------------------------------------------------------------------- Add ID
10322: if ($uid) {
10323: $uid=~tr/A-Z/a-z/;
10324: my %uidhash=&idrget($udom,$uname);
1.196 www 10325: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10326: && (!$forceid)) {
1.80 www 10327: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10328: return 'error: user id "'.$uid.'" does not match '.
10329: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10330: }
10331: } else {
1.1300 raeburn 10332: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10333: }
10334: }
10335: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10336: my @tmp=&get('environment',
1.899 raeburn 10337: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10338: 'permanentemail','inststatus'],
1.134 albertel 10339: $udom,$uname);
1.1075 raeburn 10340: my (%names,%oldnames);
1.313 matthew 10341: if ($tmp[0] =~ m/^error:.*/) {
10342: %names=();
10343: } else {
10344: %names = @tmp;
1.1075 raeburn 10345: %oldnames = %names;
1.313 matthew 10346: }
1.388 www 10347: #
1.1058 raeburn 10348: # If name, email and/or uid are blank (e.g., because an uploaded file
10349: # of users did not contain them), do not overwrite existing values
10350: # unless field is in $candelete array ref.
10351: #
10352:
10353: my @fields = ('firstname','middlename','lastname','generation',
10354: 'permanentemail','id');
10355: my %newvalues;
10356: if (ref($candelete) eq 'ARRAY') {
10357: foreach my $field (@fields) {
10358: if (grep(/^\Q$field\E$/,@{$candelete})) {
10359: if ($field eq 'firstname') {
10360: $names{$field} = $first;
10361: } elsif ($field eq 'middlename') {
10362: $names{$field} = $middle;
10363: } elsif ($field eq 'lastname') {
10364: $names{$field} = $last;
10365: } elsif ($field eq 'generation') {
10366: $names{$field} = $gene;
10367: } elsif ($field eq 'permanentemail') {
10368: $names{$field} = $email;
10369: } elsif ($field eq 'id') {
10370: $names{$field} = $uid;
10371: }
10372: }
10373: }
10374: }
1.388 www 10375: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10376: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10377: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10378: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10379: if ($email) {
10380: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10381: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10382: }
1.899 raeburn 10383: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10384: if (defined($inststatus)) {
10385: $names{'inststatus'} = '';
10386: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10387: if (ref($usertypes) eq 'HASH') {
10388: my @okstatuses;
10389: foreach my $item (split(/:/,$inststatus)) {
10390: if (defined($usertypes->{$item})) {
10391: push(@okstatuses,$item);
10392: }
10393: }
10394: if (@okstatuses) {
10395: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10396: }
10397: }
10398: }
1.1075 raeburn 10399: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10400: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10401: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10402: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10403: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10404: } else {
10405: $logmsg .= ' during self creation';
10406: }
1.1075 raeburn 10407: my $changed;
10408: if ($newuser) {
10409: $changed = 1;
10410: } else {
10411: foreach my $field (@fields) {
10412: if ($names{$field} ne $oldnames{$field}) {
10413: $changed = 1;
10414: last;
10415: }
10416: }
10417: }
10418: unless ($changed) {
10419: $logmsg = 'No changes in user information needed for: '.$logmsg;
10420: &logthis($logmsg);
10421: return 'ok';
10422: }
10423: my $reply = &put('environment', \%names, $udom,$uname);
10424: if ($reply ne 'ok') {
10425: return 'error: '.$reply;
10426: }
1.1087 raeburn 10427: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10428: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10429: }
1.1075 raeburn 10430: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10431: &devalidate_cache_new('namescache',$uname.':'.$udom);
10432: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10433: &logthis($logmsg);
1.134 albertel 10434: return 'ok';
1.80 www 10435: }
10436:
1.81 www 10437: # -------------------------------------------------------------- Modify student
1.80 www 10438:
1.81 www 10439: sub modifystudent {
10440: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10441: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10442: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10443: if (!$cid) {
1.620 albertel 10444: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10445: return 'not_in_class';
10446: }
1.80 www 10447: }
10448: # --------------------------------------------------------------- Make the user
1.81 www 10449: my $reply=&modifyuser
1.209 matthew 10450: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10451: $desiredhome,$email,$inststatus);
1.80 www 10452: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10453: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10454: # student's environment
1.297 matthew 10455: $uid = undef if (!$forceid);
1.455 albertel 10456: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10457: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10458: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10459: return $reply;
10460: }
10461:
10462: sub modify_student_enrollment {
1.1216 raeburn 10463: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10464: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10465: my ($cdom,$cnum,$chome);
10466: if (!$cid) {
1.620 albertel 10467: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10468: return 'not_in_class';
10469: }
1.620 albertel 10470: $cdom=$env{'course.'.$cid.'.domain'};
10471: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10472: } else {
10473: ($cdom,$cnum)=split(/_/,$cid);
10474: }
1.620 albertel 10475: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10476: if (!$chome) {
1.457 raeburn 10477: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10478: }
1.455 albertel 10479: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10480: # Make sure the user exists
1.81 www 10481: my $uhome=&homeserver($uname,$udom);
10482: if (($uhome eq '') || ($uhome eq 'no_host')) {
10483: return 'error: no such user';
10484: }
1.297 matthew 10485: # Get student data if we were not given enough information
10486: if (!defined($first) || $first eq '' ||
10487: !defined($last) || $last eq '' ||
10488: !defined($uid) || $uid eq '' ||
10489: !defined($middle) || $middle eq '' ||
10490: !defined($gene) || $gene eq '') {
1.294 matthew 10491: # They did not supply us with enough data to enroll the student, so
10492: # we need to pick up more information.
1.297 matthew 10493: my %tmp = &get('environment',
1.294 matthew 10494: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10495: ,$udom,$uname);
10496:
1.800 albertel 10497: #foreach my $key (keys(%tmp)) {
10498: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10499: #}
1.294 matthew 10500: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10501: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10502: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10503: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10504: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10505: }
1.556 albertel 10506: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10507: my $user = "$uname:$udom";
10508: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10509: my $reply=cput('classlist',
1.1148 raeburn 10510: {$user =>
1.1314 raeburn 10511: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10512: $cdom,$cnum);
1.1148 raeburn 10513: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10514: &devalidate_getsection_cache($udom,$uname,$cid);
10515: } else {
1.81 www 10516: return 'error: '.$reply;
10517: }
1.297 matthew 10518: # Add student role to user
1.83 www 10519: my $uurl='/'.$cid;
1.81 www 10520: $uurl=~s/\_/\//g;
10521: if ($usec) {
10522: $uurl.='/'.$usec;
10523: }
1.1148 raeburn 10524: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10525: $selfenroll,$context);
10526: if ($result ne 'ok') {
10527: if ($old_entry{$user} ne '') {
10528: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10529: } else {
10530: $reply = &del('classlist',[$user],$cdom,$cnum);
10531: }
10532: }
10533: return $result;
1.21 www 10534: }
10535:
1.556 albertel 10536: sub format_name {
10537: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10538: my $name;
10539: if ($first ne 'lastname') {
10540: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10541: } else {
10542: if ($lastname=~/\S/) {
10543: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10544: $name=~s/\s+,/,/;
10545: } else {
10546: $name.= $firstname.' '.$middlename.' '.$generation;
10547: }
10548: }
10549: $name=~s/^\s+//;
10550: $name=~s/\s+$//;
10551: $name=~s/\s+/ /g;
10552: return $name;
10553: }
10554:
1.84 www 10555: # ------------------------------------------------- Write to course preferences
10556:
10557: sub writecoursepref {
10558: my ($courseid,%prefs)=@_;
10559: $courseid=~s/^\///;
10560: $courseid=~s/\_/\//g;
10561: my ($cdomain,$cnum)=split(/\//,$courseid);
10562: my $chome=homeserver($cnum,$cdomain);
10563: if (($chome eq '') || ($chome eq 'no_host')) {
10564: return 'error: no such course';
10565: }
10566: my $cstring='';
1.800 albertel 10567: foreach my $pref (keys(%prefs)) {
10568: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10569: }
1.84 www 10570: $cstring=~s/\&$//;
10571: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10572: }
10573:
10574: # ---------------------------------------------------------- Make/modify course
10575:
10576: sub createcourse {
1.741 raeburn 10577: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10578: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10579: $url=&declutter($url);
10580: my $cid='';
1.1028 raeburn 10581: if ($context eq 'requestcourses') {
10582: my $can_create = 0;
10583: my ($ownername,$ownerdom) = split(':',$course_owner);
10584: if ($udom eq $ownerdom) {
10585: if (&usertools_access($ownername,$ownerdom,$category,undef,
10586: $context)) {
10587: $can_create = 1;
10588: }
10589: } else {
10590: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10591: $category);
10592: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10593: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10594: if (@curr > 0) {
10595: my @options = qw(approval validate autolimit);
10596: my $optregex = join('|',@options);
10597: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10598: $can_create = 1;
10599: }
10600: }
10601: }
10602: }
10603: if ($can_create) {
10604: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10605: unless (&allowed('ccc',$udom)) {
10606: return 'refused';
10607: }
1.1017 raeburn 10608: }
10609: } else {
10610: return 'refused';
10611: }
1.1028 raeburn 10612: } elsif (!&allowed('ccc',$udom)) {
10613: return 'refused';
1.84 www 10614: }
1.1011 raeburn 10615: # --------------------------------------------------------------- Get Unique ID
10616: my $uname;
10617: if ($cnum =~ /^$match_courseid$/) {
10618: my $chome=&homeserver($cnum,$udom,'true');
10619: if (($chome eq '') || ($chome eq 'no_host')) {
10620: $uname = $cnum;
10621: } else {
1.1038 raeburn 10622: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10623: }
10624: } else {
1.1038 raeburn 10625: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10626: }
10627: return $uname if ($uname =~ /^error/);
10628: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10629: if (!defined($course_server)) {
10630: if (defined(&domain($udom,'primary'))) {
10631: $course_server = &domain($udom,'primary');
10632: } else {
10633: $course_server = $env{'user.home'};
10634: }
10635: }
10636: my %host_servers =
10637: &Apache::lonnet::get_servers($udom,'library');
10638: unless ($host_servers{$course_server}) {
10639: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10640: }
1.84 www 10641: # ------------------------------------------------------------- Make the course
10642: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10643: $course_server);
1.84 www 10644: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10645: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10646: if (($uhome eq '') || ($uhome eq 'no_host')) {
10647: return 'error: no such course';
10648: }
1.271 www 10649: # ----------------------------------------------------------------- Course made
1.516 raeburn 10650: # log existence
1.1029 raeburn 10651: my $now = time;
1.918 raeburn 10652: my $newcourse = {
10653: $udom.'_'.$uname => {
1.921 raeburn 10654: description => $description,
10655: inst_code => $inst_code,
10656: owner => $course_owner,
10657: type => $crstype,
1.1029 raeburn 10658: creator => $env{'user.name'}.':'.
10659: $env{'user.domain'},
10660: created => $now,
10661: context => $context,
1.918 raeburn 10662: },
10663: };
1.921 raeburn 10664: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10665: # set toplevel url
1.271 www 10666: my $topurl=$url;
10667: unless ($nonstandard) {
10668: # ------------------------------------------ For standard courses, make top url
10669: my $mapurl=&clutter($url);
1.278 www 10670: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10671: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10672: <map>
10673: <resource id="1" type="start"></resource>
10674: <resource id="2" src="$mapurl"></resource>
10675: <resource id="3" type="finish"></resource>
10676: <link index="1" from="1" to="2"></link>
10677: <link index="2" from="2" to="3"></link>
10678: </map>
10679: ENDINITMAP
10680: $topurl=&declutter(
1.638 albertel 10681: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10682: );
10683: }
10684: # ----------------------------------------------------------- Write preferences
1.84 www 10685: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10686: ('description' => $description,
10687: 'url' => $topurl,
10688: 'internal.creator' => $env{'user.name'}.':'.
10689: $env{'user.domain'},
10690: 'internal.created' => $now,
10691: 'internal.creationcontext' => $context)
10692: );
1.84 www 10693: return '/'.$udom.'/'.$uname;
10694: }
10695:
1.1011 raeburn 10696: # ------------------------------------------------------------------- Create ID
10697: sub generate_coursenum {
1.1038 raeburn 10698: my ($udom,$crstype) = @_;
1.1011 raeburn 10699: my $domdesc = &domain($udom);
10700: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10701: my $first;
10702: if ($crstype eq 'Community') {
10703: $first = '0';
10704: } else {
10705: $first = int(1+rand(9));
10706: }
10707: my $uname=$first.
1.1011 raeburn 10708: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10709: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10710: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10711: # ----------------------------------------------- Make sure that does not exist
10712: my $uhome=&homeserver($uname,$udom,'true');
10713: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10714: if ($crstype eq 'Community') {
10715: $first = '0';
10716: } else {
10717: $first = int(1+rand(9));
10718: }
10719: $uname=$first.
1.1011 raeburn 10720: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10721: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10722: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10723: $uhome=&homeserver($uname,$udom,'true');
10724: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10725: return 'error: unable to generate unique course-ID';
10726: }
10727: }
10728: return $uname;
10729: }
10730:
1.813 albertel 10731: sub is_course {
1.1167 droeschl 10732: my ($cdom, $cnum) = scalar(@_) == 1 ?
10733: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10734:
1.1381 raeburn 10735: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10736: my $uhome=&homeserver($cnum,$cdom);
10737: my $iscourse;
10738: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 10739: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 10740: } else {
10741: my $hashid = $cdom.':'.$cnum;
10742: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10743: unless (defined($cached)) {
10744: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10745: $cnum,undef,undef,'.');
10746: $iscourse = 0;
10747: if (exists($courses{$cdom.'_'.$cnum})) {
10748: $iscourse = 1;
10749: }
10750: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10751: }
10752: }
10753: return unless ($iscourse);
1.1167 droeschl 10754: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10755: }
10756:
1.1015 raeburn 10757: sub store_userdata {
10758: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10759: my $result;
1.1016 raeburn 10760: if ($datakey ne '') {
1.1013 raeburn 10761: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10762: if ($udom eq '' || $uname eq '') {
10763: $udom = $env{'user.domain'};
10764: $uname = $env{'user.name'};
10765: }
10766: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10767: if (($uhome eq '') || ($uhome eq 'no_host')) {
10768: $result = 'error: no_host';
10769: } else {
10770: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10771: $storehash->{'host'} = $perlvar{'lonHostID'};
10772:
10773: my $namevalue='';
10774: foreach my $key (keys(%{$storehash})) {
10775: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10776: }
10777: $namevalue=~s/\&$//;
1.1224 raeburn 10778: unless ($namespace eq 'courserequests') {
10779: $datakey = &escape($datakey);
10780: }
1.1105 raeburn 10781: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10782: $namevalue,$uhome);
1.1013 raeburn 10783: }
10784: } else {
10785: $result = 'error: data to store was not a hash reference';
10786: }
10787: } else {
10788: $result= 'error: invalid requestkey';
10789: }
10790: return $result;
10791: }
10792:
1.21 www 10793: # ---------------------------------------------------------- Assign Custom Role
10794:
10795: sub assigncustomrole {
1.957 raeburn 10796: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10797: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10798: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10799: }
10800:
10801: # ----------------------------------------------------------------- Revoke Role
10802:
10803: sub revokerole {
1.957 raeburn 10804: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10805: my $now=time;
1.965 raeburn 10806: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10807: }
10808:
10809: # ---------------------------------------------------------- Revoke Custom Role
10810:
10811: sub revokecustomrole {
1.957 raeburn 10812: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10813: my $now=time;
1.357 www 10814: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10815: $deleteflag,$selfenroll,$context);
1.17 www 10816: }
10817:
1.533 banghart 10818: # ------------------------------------------------------------ Disk usage
1.535 albertel 10819: sub diskusage {
1.955 raeburn 10820: my ($udom,$uname,$directorypath,$getpropath)=@_;
10821: $directorypath =~ s/\/$//;
10822: my $listing=&reply('du2:'.&escape($directorypath).':'
10823: .&escape($getpropath).':'.&escape($uname).':'
10824: .&escape($udom),homeserver($uname,$udom));
10825: if ($listing eq 'unknown_cmd') {
10826: if ($getpropath) {
10827: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10828: }
10829: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10830: }
1.514 albertel 10831: return $listing;
1.512 banghart 10832: }
10833:
1.566 banghart 10834: sub is_locked {
1.1096 raeburn 10835: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10836: my @check;
10837: my $is_locked;
1.1093 raeburn 10838: push (@check,$file_name);
1.613 albertel 10839: my %locked = &get('file_permissions',\@check,
1.620 albertel 10840: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10841: my ($tmp)=keys(%locked);
10842: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10843:
1.566 banghart 10844: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10845: $is_locked = 'false';
10846: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10847: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10848: $is_locked = 'true';
1.1096 raeburn 10849: if (ref($which) eq 'ARRAY') {
10850: push(@{$which},$entry);
10851: } else {
10852: last;
10853: }
1.745 raeburn 10854: }
10855: }
1.566 banghart 10856: } else {
10857: $is_locked = 'false';
10858: }
1.1093 raeburn 10859: return $is_locked;
1.566 banghart 10860: }
10861:
1.759 albertel 10862: sub declutter_portfile {
10863: my ($file) = @_;
1.833 albertel 10864: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10865: return $file;
10866: }
10867:
1.559 banghart 10868: # ------------------------------------------------------------- Mark as Read Only
10869:
10870: sub mark_as_readonly {
10871: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10872: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10873: my ($tmp)=keys(%current_permissions);
10874: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10875: foreach my $file (@{$files}) {
1.759 albertel 10876: $file = &declutter_portfile($file);
1.561 banghart 10877: push(@{$current_permissions{$file}},$what);
1.559 banghart 10878: }
1.613 albertel 10879: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10880: return;
10881: }
10882:
1.572 banghart 10883: # ------------------------------------------------------------Save Selected Files
10884:
10885: sub save_selected_files {
10886: my ($user, $path, @files) = @_;
10887: my $filename = $user."savedfiles";
1.573 banghart 10888: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 10889: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10890: foreach my $file (@files) {
1.620 albertel 10891: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10892: }
10893: foreach my $file (@other_files) {
1.574 banghart 10894: print (OUT $file."\n");
1.572 banghart 10895: }
1.574 banghart 10896: close (OUT);
1.572 banghart 10897: return 'ok';
10898: }
10899:
1.574 banghart 10900: sub clear_selected_files {
10901: my ($user) = @_;
10902: my $filename = $user."savedfiles";
1.1359 raeburn 10903: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10904: print (OUT undef);
10905: close (OUT);
10906: return ("ok");
10907: }
10908:
1.572 banghart 10909: sub files_in_path {
10910: my ($user, $path) = @_;
10911: my $filename = $user."savedfiles";
10912: my %return_files;
1.1359 raeburn 10913: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10914: while (my $line_in = <IN>) {
1.574 banghart 10915: chomp ($line_in);
10916: my @paths_and_file = split (m!/!, $line_in);
10917: my $file_part = pop (@paths_and_file);
10918: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10919: $path_part.='/';
10920: my $path_and_file = $path_part.$file_part;
10921: if ($path_part eq $path) {
10922: $return_files{$file_part}= 'selected';
10923: }
10924: }
1.574 banghart 10925: close (IN);
10926: return (\%return_files);
1.572 banghart 10927: }
10928:
10929: # called in portfolio select mode, to show files selected NOT in current directory
10930: sub files_not_in_path {
10931: my ($user, $path) = @_;
10932: my $filename = $user."savedfiles";
10933: my @return_files;
10934: my $path_part;
1.1359 raeburn 10935: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10936: while (my $line = <IN>) {
1.572 banghart 10937: #ok, I know it's clunky, but I want it to work
1.800 albertel 10938: my @paths_and_file = split(m|/|, $line);
10939: my $file_part = pop(@paths_and_file);
10940: chomp($file_part);
10941: my $path_part = join('/', @paths_and_file);
1.572 banghart 10942: $path_part .= '/';
10943: my $path_and_file = $path_part.$file_part;
10944: if ($path_part ne $path) {
1.800 albertel 10945: push(@return_files, ($path_and_file));
1.572 banghart 10946: }
10947: }
1.800 albertel 10948: close(OUT);
1.574 banghart 10949: return (@return_files);
1.572 banghart 10950: }
10951:
1.1273 raeburn 10952: #------------------------------Submitted/Handedback Portfolio Files Versioning
10953:
10954: sub portfiles_versioning {
10955: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10956: my $portfolio_root = '/userfiles/portfolio';
10957: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10958: foreach my $file (@{$portfiles}) {
10959: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10960: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10961: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10962: my $getpropath = 1;
10963: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10964: $stu_name,$getpropath);
10965: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10966: my $new_answer =
10967: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10968: if ($new_answer ne 'problem getting file') {
10969: push(@{$versioned_portfiles}, $directory.$new_answer);
10970: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10971: [$symb,$env{'request.course.id'},'graded']);
10972: }
10973: }
10974: }
10975:
10976: sub get_next_version {
10977: my ($answer_name, $answer_ext, $dir_list) = @_;
10978: my $version;
10979: if (ref($dir_list) eq 'ARRAY') {
10980: foreach my $row (@{$dir_list}) {
10981: my ($file) = split(/\&/,$row,2);
10982: my ($file_name,$file_version,$file_ext) =
10983: &file_name_version_ext($file);
10984: if (($file_name eq $answer_name) &&
10985: ($file_ext eq $answer_ext)) {
10986: # gets here if filename and extension match,
10987: # regardless of version
10988: if ($file_version ne '') {
10989: # a versioned file is found so save it for later
10990: if ($file_version > $version) {
10991: $version = $file_version;
10992: }
10993: }
10994: }
10995: }
10996: }
10997: $version ++;
10998: return($version);
10999: }
11000:
11001: sub version_selected_portfile {
11002: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11003: my ($answer_name,$answer_ver,$answer_ext) =
11004: &file_name_version_ext($file_name);
11005: my $new_answer;
11006: $env{'form.copy'} =
11007: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11008: if($env{'form.copy'} eq '-1') {
11009: $new_answer = 'problem getting file';
11010: } else {
11011: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11012: my $copy_result =
11013: &finishuserfileupload($stu_name,$domain,'copy',
11014: '/portfolio'.$directory.$new_answer);
11015: }
11016: undef($env{'form.copy'});
11017: return ($new_answer);
11018: }
11019:
11020: sub file_name_version_ext {
11021: my ($file)=@_;
11022: my @file_parts = split(/\./, $file);
11023: my ($name,$version,$ext);
11024: if (@file_parts > 1) {
11025: $ext=pop(@file_parts);
11026: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11027: $version=pop(@file_parts);
11028: }
11029: $name=join('.',@file_parts);
11030: } else {
11031: $name=join('.',@file_parts);
11032: }
11033: return($name,$version,$ext);
11034: }
11035:
1.745 raeburn 11036: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11037:
1.745 raeburn 11038: sub get_portfile_permissions {
11039: my ($domain,$user) = @_;
1.613 albertel 11040: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11041: my ($tmp)=keys(%current_permissions);
11042: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11043: return \%current_permissions;
11044: }
11045:
11046: #---------------------------------------------Get portfolio file access controls
11047:
1.749 raeburn 11048: sub get_access_controls {
1.745 raeburn 11049: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11050: my %access;
11051: my $real_file = $file;
11052: $file =~ s/\.meta$//;
1.745 raeburn 11053: if (defined($file)) {
1.749 raeburn 11054: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11055: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11056: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11057: }
11058: }
1.745 raeburn 11059: } else {
1.749 raeburn 11060: foreach my $key (keys(%{$current_permissions})) {
11061: if ($key =~ /\0accesscontrol$/) {
11062: if (defined($group)) {
11063: if ($key !~ m-^\Q$group\E/-) {
11064: next;
11065: }
11066: }
11067: my ($fullpath) = split(/\0/,$key);
11068: if (ref($$current_permissions{$key}) eq 'HASH') {
11069: foreach my $control (keys(%{$$current_permissions{$key}})) {
11070: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11071: }
11072: }
11073: }
11074: }
11075: }
11076: return %access;
11077: }
11078:
11079: sub modify_access_controls {
11080: my ($file_name,$changes,$domain,$user)=@_;
11081: my ($outcome,$deloutcome);
11082: my %store_permissions;
11083: my %new_values;
11084: my %new_control;
11085: my %translation;
11086: my @deletions = ();
11087: my $now = time;
11088: if (exists($$changes{'activate'})) {
11089: if (ref($$changes{'activate'}) eq 'HASH') {
11090: my @newitems = sort(keys(%{$$changes{'activate'}}));
11091: my $numnew = scalar(@newitems);
11092: for (my $i=0; $i<$numnew; $i++) {
11093: my $newkey = $newitems[$i];
11094: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11095: if ($newkey =~ /^\d+:/) {
11096: $newkey =~ s/^(\d+)/$newid/;
11097: $translation{$1} = $newid;
11098: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11099: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11100: $translation{$1} = $newid;
11101: }
1.749 raeburn 11102: $new_values{$file_name."\0".$newkey} =
11103: $$changes{'activate'}{$newitems[$i]};
11104: $new_control{$newkey} = $now;
11105: }
11106: }
11107: }
11108: my %todelete;
11109: my %changed_items;
11110: foreach my $action ('delete','update') {
11111: if (exists($$changes{$action})) {
11112: if (ref($$changes{$action}) eq 'HASH') {
11113: foreach my $key (keys(%{$$changes{$action}})) {
11114: my ($itemnum) = ($key =~ /^([^:]+):/);
11115: if ($action eq 'delete') {
11116: $todelete{$itemnum} = 1;
11117: } else {
11118: $changed_items{$itemnum} = $key;
11119: }
11120: }
1.745 raeburn 11121: }
11122: }
1.749 raeburn 11123: }
11124: # get lock on access controls for file.
11125: my $lockhash = {
11126: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11127: ':'.$env{'user.domain'},
11128: };
11129: my $tries = 0;
11130: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11131:
1.1288 damieng 11132: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11133: $tries ++;
1.1289 damieng 11134: sleep(0.1);
1.749 raeburn 11135: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11136: }
11137: if ($gotlock eq 'ok') {
11138: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11139: my ($tmp)=keys(%curr_permissions);
11140: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11141: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11142: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11143: if (ref($curr_controls) eq 'HASH') {
11144: foreach my $control_item (keys(%{$curr_controls})) {
11145: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11146: if (defined($todelete{$itemnum})) {
11147: push(@deletions,$file_name."\0".$control_item);
11148: } else {
11149: if (defined($changed_items{$itemnum})) {
11150: $new_control{$changed_items{$itemnum}} = $now;
11151: push(@deletions,$file_name."\0".$control_item);
11152: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11153: } else {
11154: $new_control{$control_item} = $$curr_controls{$control_item};
11155: }
11156: }
1.745 raeburn 11157: }
11158: }
11159: }
1.970 raeburn 11160: my ($group);
11161: if (&is_course($domain,$user)) {
11162: ($group,my $file) = split(/\//,$file_name,2);
11163: }
1.749 raeburn 11164: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11165: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11166: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11167: # remove lock
11168: my @del_lock = ($file_name."\0".'locked_access_records');
11169: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11170: my $sqlresult =
1.970 raeburn 11171: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11172: $group);
1.749 raeburn 11173: } else {
11174: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11175: }
1.749 raeburn 11176: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11177: }
11178:
1.827 raeburn 11179: sub make_public_indefinitely {
1.1271 raeburn 11180: my (@requrl) = @_;
11181: return &automated_portfile_access('public',\@requrl);
11182: }
11183:
11184: sub automated_portfile_access {
11185: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11186: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11187: return 'invalid';
11188: }
1.1271 raeburn 11189: my %urls;
11190: if (ref($addsref) eq 'ARRAY') {
11191: foreach my $requrl (@{$addsref}) {
11192: if (&is_portfolio_url($requrl)) {
11193: unless (exists($urls{$requrl})) {
11194: $urls{$requrl} = 'add';
11195: }
11196: }
11197: }
11198: }
11199: if (ref($delsref) eq 'ARRAY') {
11200: foreach my $requrl (@{$delsref}) {
11201: if (&is_portfolio_url($requrl)) {
11202: unless (exists($urls{$requrl})) {
11203: $urls{$requrl} = 'delete';
11204: }
11205: }
11206: }
11207: }
11208: unless (keys(%urls)) {
11209: return 'invalid';
11210: }
11211: my $ip;
11212: if ($accesstype eq 'ip') {
11213: if (ref($info) eq 'HASH') {
11214: if ($info->{'ip'} ne '') {
11215: $ip = $info->{'ip'};
11216: }
11217: }
11218: if ($ip eq '') {
11219: return 'invalid';
11220: }
11221: }
11222: my $errors;
1.827 raeburn 11223: my $now = time;
1.1271 raeburn 11224: my %current_perms;
11225: foreach my $requrl (sort(keys(%urls))) {
11226: my $action;
11227: if ($urls{$requrl} eq 'add') {
11228: $action = 'activate';
11229: } else {
11230: $action = 'none';
11231: }
11232: my $aclnum = 0;
1.827 raeburn 11233: my (undef,$udom,$unum,$file_name,$group) =
11234: &parse_portfolio_url($requrl);
1.1271 raeburn 11235: unless (exists($current_perms{$unum.':'.$udom})) {
11236: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11237: }
11238: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11239: $group,$file_name);
11240: foreach my $key (keys(%{$access_controls{$file_name}})) {
11241: my ($num,$scope,$end,$start) =
11242: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11243: if ($scope eq $accesstype) {
11244: if (($start <= $now) && ($end == 0)) {
11245: if ($accesstype eq 'ip') {
11246: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11247: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11248: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11249: if ($urls{$requrl} eq 'add') {
11250: $action = 'none';
11251: last;
11252: } else {
11253: $action = 'delete';
11254: $aclnum = $num;
11255: last;
11256: }
11257: }
11258: }
11259: }
11260: } elsif ($accesstype eq 'public') {
11261: if ($urls{$requrl} eq 'add') {
11262: $action = 'none';
11263: last;
11264: } else {
11265: $action = 'delete';
11266: $aclnum = $num;
11267: last;
11268: }
11269: }
11270: } elsif ($accesstype eq 'public') {
1.827 raeburn 11271: $action = 'update';
11272: $aclnum = $num;
1.1271 raeburn 11273: last;
1.827 raeburn 11274: }
11275: }
11276: }
11277: if ($action eq 'none') {
1.1271 raeburn 11278: next;
1.827 raeburn 11279: } else {
11280: my %changes;
11281: my $newend = 0;
11282: my $newstart = $now;
1.1271 raeburn 11283: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11284: $changes{$action}{$newkey} = {
1.1271 raeburn 11285: type => $accesstype,
1.827 raeburn 11286: time => {
11287: start => $newstart,
11288: end => $newend,
11289: },
11290: };
1.1271 raeburn 11291: if ($accesstype eq 'ip') {
11292: $changes{$action}{$newkey}{'ip'} = [$ip];
11293: }
1.827 raeburn 11294: my ($outcome,$deloutcome,$new_values,$translation) =
11295: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11296: unless ($outcome eq 'ok') {
11297: $errors .= $outcome.' ';
11298: }
1.827 raeburn 11299: }
1.1271 raeburn 11300: }
11301: if ($errors) {
11302: $errors =~ s/\s$//;
11303: return $errors;
1.827 raeburn 11304: } else {
1.1271 raeburn 11305: return 'ok';
1.827 raeburn 11306: }
11307: }
11308:
1.745 raeburn 11309: #------------------------------------------------------Get Marked as Read Only
11310:
11311: sub get_marked_as_readonly {
11312: my ($domain,$user,$what,$group) = @_;
11313: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11314: my @readonly_files;
1.629 banghart 11315: my $cmp1=$what;
11316: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11317: while (my ($file_name,$value) = each(%{$current_permissions})) {
11318: if (defined($group)) {
11319: if ($file_name !~ m-^\Q$group\E/-) {
11320: next;
11321: }
11322: }
1.561 banghart 11323: if (ref($value) eq "ARRAY"){
11324: foreach my $stored_what (@{$value}) {
1.629 banghart 11325: my $cmp2=$stored_what;
1.759 albertel 11326: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11327: $cmp2=join('',@{$stored_what});
1.745 raeburn 11328: }
1.629 banghart 11329: if ($cmp1 eq $cmp2) {
1.561 banghart 11330: push(@readonly_files, $file_name);
1.745 raeburn 11331: last;
1.563 banghart 11332: } elsif (!defined($what)) {
11333: push(@readonly_files, $file_name);
1.745 raeburn 11334: last;
1.561 banghart 11335: }
11336: }
1.745 raeburn 11337: }
1.561 banghart 11338: }
11339: return @readonly_files;
11340: }
1.577 banghart 11341: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11342:
1.577 banghart 11343: sub get_marked_as_readonly_hash {
1.745 raeburn 11344: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11345: my %readonly_files;
1.745 raeburn 11346: while (my ($file_name,$value) = each(%{$current_permissions})) {
11347: if (defined($group)) {
11348: if ($file_name !~ m-^\Q$group\E/-) {
11349: next;
11350: }
11351: }
1.577 banghart 11352: if (ref($value) eq "ARRAY"){
11353: foreach my $stored_what (@{$value}) {
1.745 raeburn 11354: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11355: foreach my $lock_descriptor(@{$stored_what}) {
11356: if ($lock_descriptor eq 'graded') {
11357: $readonly_files{$file_name} = 'graded';
11358: } elsif ($lock_descriptor eq 'handback') {
11359: $readonly_files{$file_name} = 'handback';
11360: } else {
11361: if (!exists($readonly_files{$file_name})) {
11362: $readonly_files{$file_name} = 'locked';
11363: }
11364: }
1.745 raeburn 11365: }
1.750 banghart 11366: }
1.577 banghart 11367: }
11368: }
11369: }
11370: return %readonly_files;
11371: }
1.559 banghart 11372: # ------------------------------------------------------------ Unmark as Read Only
11373:
11374: sub unmark_as_readonly {
1.629 banghart 11375: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11376: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11377: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11378: $file_name = &declutter_portfile($file_name);
1.634 albertel 11379: my $symb_crs = $what;
11380: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11381: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11382: my ($tmp)=keys(%current_permissions);
11383: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11384: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11385: foreach my $file (@readonly_files) {
1.759 albertel 11386: my $clean_file = &declutter_portfile($file);
11387: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11388: my $current_locks = $current_permissions{$file};
1.563 banghart 11389: my @new_locks;
11390: my @del_keys;
11391: if (ref($current_locks) eq "ARRAY"){
11392: foreach my $locker (@{$current_locks}) {
1.632 albertel 11393: my $compare=$locker;
1.749 raeburn 11394: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11395: $compare=join('',@{$locker});
1.746 raeburn 11396: if ($compare ne $symb_crs) {
11397: push(@new_locks, $locker);
11398: }
1.563 banghart 11399: }
11400: }
1.650 albertel 11401: if (scalar(@new_locks) > 0) {
1.563 banghart 11402: $current_permissions{$file} = \@new_locks;
11403: } else {
11404: push(@del_keys, $file);
1.613 albertel 11405: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11406: delete($current_permissions{$file});
1.563 banghart 11407: }
11408: }
1.561 banghart 11409: }
1.613 albertel 11410: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11411: return;
11412: }
1.512 banghart 11413:
1.17 www 11414: # ------------------------------------------------------------ Directory lister
11415:
11416: sub dirlist {
1.955 raeburn 11417: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11418: $uri=~s/^\///;
11419: $uri=~s/\/$//;
1.253 stredwic 11420: my ($udom, $uname);
1.955 raeburn 11421: if ($getuserdir) {
1.253 stredwic 11422: $udom = $userdomain;
11423: $uname = $username;
1.955 raeburn 11424: } else {
11425: (undef,$udom,$uname)=split(/\//,$uri);
11426: if(defined($userdomain)) {
11427: $udom = $userdomain;
11428: }
11429: if(defined($username)) {
11430: $uname = $username;
11431: }
1.253 stredwic 11432: }
1.955 raeburn 11433: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11434:
1.955 raeburn 11435: $dirRoot = $perlvar{'lonDocRoot'};
11436: if (defined($getpropath)) {
11437: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11438: $dirRoot =~ s/\/$//;
1.955 raeburn 11439: } elsif (defined($getuserdir)) {
11440: my $subdir=$uname.'__';
11441: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11442: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11443: ."/$udom/$subdir/$uname";
11444: } elsif (defined($alternateRoot)) {
11445: $dirRoot = $alternateRoot;
1.751 banghart 11446: }
1.253 stredwic 11447:
11448: if($udom) {
11449: if($uname) {
1.1135 raeburn 11450: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11451: if ($uhome eq 'no_host') {
11452: return ([],'no_host');
11453: }
1.955 raeburn 11454: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11455: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11456: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11457: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11458: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11459: } else {
11460: @listing_results = map { &unescape($_); } split(/:/,$listing);
11461: }
1.605 matthew 11462: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11463: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11464: @listing_results = split(/:/,$listing);
11465: } else {
11466: @listing_results = map { &unescape($_); } split(/:/,$listing);
11467: }
1.1135 raeburn 11468: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11469: ($listing eq 'rejected') || ($listing eq 'refused') ||
11470: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11471: return ([],$listing);
11472: } else {
11473: return (\@listing_results);
1.1135 raeburn 11474: }
1.955 raeburn 11475: } elsif(!$alternateRoot) {
1.1136 raeburn 11476: my (%allusers,%listerror);
1.841 albertel 11477: my %servers = &get_servers($udom,'library');
1.955 raeburn 11478: foreach my $tryserver (keys(%servers)) {
11479: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11480: &escape($udom),$tryserver);
11481: if ($listing eq 'unknown_cmd') {
11482: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11483: $udom, $tryserver);
11484: } else {
11485: @listing_results = map { &unescape($_); } split(/:/,$listing);
11486: }
1.841 albertel 11487: if ($listing eq 'unknown_cmd') {
11488: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11489: $udom, $tryserver);
11490: @listing_results = split(/:/,$listing);
11491: } else {
11492: @listing_results =
11493: map { &unescape($_); } split(/:/,$listing);
11494: }
1.1136 raeburn 11495: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11496: ($listing eq 'rejected') || ($listing eq 'refused') ||
11497: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11498: $listerror{$tryserver} = $listing;
11499: } else {
1.841 albertel 11500: foreach my $line (@listing_results) {
11501: my ($entry) = split(/&/,$line,2);
11502: $allusers{$entry} = 1;
11503: }
11504: }
1.253 stredwic 11505: }
1.1136 raeburn 11506: my @alluserslist=();
1.800 albertel 11507: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11508: push(@alluserslist,$user.'&user');
1.253 stredwic 11509: }
1.1318 droeschl 11510:
11511: if (!%listerror) {
11512: # no errors
11513: return (\@alluserslist);
11514: } elsif (scalar(keys(%servers)) == 1) {
11515: # one library server, one error
11516: my ($key) = keys(%listerror);
11517: return (\@alluserslist, $listerror{$key});
11518: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11519: # con_lost indicates that we might miss data from at least one
11520: # library server
11521: return (\@alluserslist, 'con_lost');
11522: } else {
11523: # multiple library servers and no con_lost -> data should be
11524: # complete.
11525: return (\@alluserslist);
11526: }
11527:
1.253 stredwic 11528: } else {
1.1136 raeburn 11529: return ([],'missing username');
1.253 stredwic 11530: }
1.955 raeburn 11531: } elsif(!defined($getpropath)) {
1.1136 raeburn 11532: my $path = $perlvar{'lonDocRoot'}.'/res/';
11533: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11534: return (\@all_domains);
1.955 raeburn 11535: } else {
1.1136 raeburn 11536: return ([],'missing domain');
1.275 stredwic 11537: }
11538: }
11539:
11540: # --------------------------------------------- GetFileTimestamp
11541: # This function utilizes dirlist and returns the date stamp for
11542: # when it was last modified. It will also return an error of -1
11543: # if an error occurs
11544:
11545: sub GetFileTimestamp {
1.955 raeburn 11546: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11547: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11548: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11549: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11550: undef,$getuserdir);
11551: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11552: return -1;
11553: }
11554: if (ref($fileref) eq 'ARRAY') {
11555: my @stats = split('&',$fileref->[0]);
1.375 matthew 11556: # @stats contains first the filename, then the stat output
11557: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11558: } else {
11559: return -1;
1.253 stredwic 11560: }
1.26 www 11561: }
11562:
1.712 albertel 11563: sub stat_file {
11564: my ($uri) = @_;
1.787 albertel 11565: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11566:
1.955 raeburn 11567: my ($udom,$uname,$file);
1.712 albertel 11568: if ($uri =~ m-^/(uploaded|editupload)/-) {
11569: ($udom,$uname,$file) =
1.811 albertel 11570: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11571: $file = 'userfiles/'.$file;
11572: }
11573: if ($uri =~ m-^/res/-) {
11574: ($udom,$uname) =
1.807 albertel 11575: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11576: $file = $uri;
11577: }
11578:
11579: if (!$udom || !$uname || !$file) {
11580: # unable to handle the uri
11581: return ();
11582: }
1.956 raeburn 11583: my $getpropath;
11584: if ($file =~ /^userfiles\//) {
11585: $getpropath = 1;
11586: }
1.1136 raeburn 11587: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11588: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11589: return ();
11590: } else {
11591: if (ref($listref) eq 'ARRAY') {
11592: my @stats = split('&',$listref->[0]);
11593: shift(@stats); #filename is first
11594: return @stats;
11595: }
1.712 albertel 11596: }
11597: return ();
11598: }
11599:
1.1313 raeburn 11600: # --------------------------------------------------------- recursedirs
11601: # Recursive function to traverse either a specific user's Authoring Space
11602: # or corresponding Published Resource Space, and populate the hash ref:
11603: # $dirhashref with URLs of all directories, and if $filehashref hash
11604: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11605: # or .rights files in resource space, and .meta, .save, .log, and .bak
11606: # files in Authoring Space.
11607: #
11608: # Inputs:
11609: #
11610: # $is_home - true if current server is home server for user's space
11611: # $context - either: priv, or res respectively for Authoring or Resource Space.
11612: # $docroot - Document root (i.e., /home/httpd/html
11613: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11614: # $relpath - Current path (relative to top level).
11615: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11616: # $filehashref - reference to hash to populate with URLs of files (Optional)
11617: #
11618: # Returns: nothing
11619: #
11620: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11621: #
11622: # Currently used by interface/londocs.pm to create linked select boxes for
11623: # directory and filename to import a Course "Author" resource into a course, and
11624: # also to create linked select boxes for Authoring Space and Directory to choose
11625: # save location for creation of a new "standard" problem from the Course Editor.
11626: #
11627:
11628: sub recursedirs {
11629: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11630: return unless (ref($dirhashref) eq 'HASH');
11631: my $currpath = $docroot.$toppath;
11632: if ($relpath) {
11633: $currpath .= "/$relpath";
11634: }
11635: my $savefile;
11636: if (ref($filehashref)) {
11637: $savefile = 1;
11638: }
11639: if ($is_home) {
11640: if (opendir(my $dirh,$currpath)) {
11641: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11642: next if ($item eq '');
11643: if (-d "$currpath/$item") {
11644: my $newpath;
11645: if ($relpath) {
11646: $newpath = "$relpath/$item";
11647: } else {
11648: $newpath = $item;
11649: }
11650: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11651: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11652: } elsif ($savefile) {
11653: if ($context eq 'priv') {
11654: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11655: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11656: }
11657: } else {
11658: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11659: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11660: }
11661: }
11662: }
11663: }
11664: closedir($dirh);
11665: }
11666: } else {
11667: my ($dirlistref,$listerror) =
11668: &dirlist($toppath.$relpath);
11669: my @dir_lines;
11670: my $dirptr=16384;
11671: if (ref($dirlistref) eq 'ARRAY') {
11672: foreach my $dir_line (sort
11673: {
11674: my ($afile)=split('&',$a,2);
11675: my ($bfile)=split('&',$b,2);
11676: return (lc($afile) cmp lc($bfile));
11677: } (@{$dirlistref})) {
11678: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11679: split(/\&/,$dir_line,16);
11680: $item =~ s/\s+$//;
11681: next if (($item =~ /^\.\.?$/) || ($obs));
11682: if ($dirptr&$testdir) {
11683: my $newpath;
11684: if ($relpath) {
11685: $newpath = "$relpath/$item";
11686: } else {
11687: $relpath = '/';
11688: $newpath = $item;
11689: }
11690: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11691: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11692: } elsif ($savefile) {
11693: if ($context eq 'priv') {
11694: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11695: $filehashref->{$relpath}{$item} = 1;
11696: }
11697: } else {
11698: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11699: $filehashref->{$relpath}{$item} = 1;
11700: }
11701: }
11702: }
11703: }
11704: }
11705: }
11706: return;
11707: }
11708:
1.26 www 11709: # -------------------------------------------------------- Value of a Condition
11710:
1.713 albertel 11711: # gets the value of a specific preevaluated condition
11712: # stored in the string $env{user.state.<cid>}
11713: # or looks up a condition reference in the bighash and if if hasn't
11714: # already been evaluated recurses into docondval to get the value of
11715: # the condition, then memoizing it to
11716: # $env{user.state.<cid>.<condition>}
1.40 www 11717: sub directcondval {
11718: my $number=shift;
1.620 albertel 11719: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11720: &Apache::lonuserstate::evalstate();
11721: }
1.713 albertel 11722: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11723: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11724: } elsif ($number =~ /^_/) {
11725: my $sub_condition;
11726: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11727: &GDBM_READER(),0640)) {
11728: $sub_condition=$bighash{'conditions'.$number};
11729: untie(%bighash);
11730: }
11731: my $value = &docondval($sub_condition);
1.949 raeburn 11732: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11733: return $value;
11734: }
1.620 albertel 11735: if ($env{'user.state.'.$env{'request.course.id'}}) {
11736: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11737: } else {
11738: return 2;
11739: }
11740: }
11741:
1.713 albertel 11742: # get the collection of conditions for this resource
1.26 www 11743: sub condval {
11744: my $condidx=shift;
1.54 www 11745: my $allpathcond='';
1.713 albertel 11746: foreach my $cond (split(/\|/,$condidx)) {
11747: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11748: $allpathcond.=
11749: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11750: }
1.191 harris41 11751: }
1.54 www 11752: $allpathcond=~s/\|$//;
1.713 albertel 11753: return &docondval($allpathcond);
11754: }
11755:
11756: #evaluates an expression of conditions
11757: sub docondval {
11758: my ($allpathcond) = @_;
11759: my $result=0;
11760: if ($env{'request.course.id'}
11761: && defined($allpathcond)) {
11762: my $operand='|';
11763: my @stack;
11764: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11765: if ($chunk eq '(') {
11766: push @stack,($operand,$result);
11767: } elsif ($chunk eq ')') {
11768: my $before=pop @stack;
11769: if (pop @stack eq '&') {
11770: $result=$result>$before?$before:$result;
11771: } else {
11772: $result=$result>$before?$result:$before;
11773: }
11774: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11775: $operand=$chunk;
11776: } else {
11777: my $new=directcondval($chunk);
11778: if ($operand eq '&') {
11779: $result=$result>$new?$new:$result;
11780: } else {
11781: $result=$result>$new?$result:$new;
11782: }
11783: }
11784: }
1.26 www 11785: }
11786: return $result;
1.421 albertel 11787: }
11788:
11789: # ---------------------------------------------------- Devalidate courseresdata
11790:
11791: sub devalidatecourseresdata {
11792: my ($coursenum,$coursedomain)=@_;
11793: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11794: &devalidate_cache_new('courseres',$hashid);
1.28 www 11795: }
11796:
1.763 www 11797:
1.200 www 11798: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11799: #
11800: # Parameters:
11801: # $coursenum - Number of the course.
11802: # $coursedomain - Domain at which the course was created.
11803: # Returns:
11804: # A hash of the course parameters along (I think) with timestamps
11805: # and version info.
1.877 foxr 11806:
1.624 albertel 11807: sub get_courseresdata {
11808: my ($coursenum,$coursedomain)=@_;
1.200 www 11809: my $coursehom=&homeserver($coursenum,$coursedomain);
11810: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11811: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11812: my %dumpreply;
1.417 albertel 11813: unless (defined($cached)) {
1.624 albertel 11814: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11815: $result=\%dumpreply;
1.251 albertel 11816: my ($tmp) = keys(%dumpreply);
11817: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11818: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11819: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11820: return $tmp;
1.416 albertel 11821: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11822: $result=undef;
1.599 albertel 11823: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11824: }
11825: }
1.624 albertel 11826: return $result;
11827: }
11828:
1.633 albertel 11829: sub devalidateuserresdata {
11830: my ($uname,$udom)=@_;
11831: my $hashid="$udom:$uname";
11832: &devalidate_cache_new('userres',$hashid);
11833: }
11834:
1.624 albertel 11835: sub get_userresdata {
11836: my ($uname,$udom)=@_;
11837: #most student don\'t have any data set, check if there is some data
11838: if (&EXT_cache_status($udom,$uname)) { return undef; }
11839:
11840: my $hashid="$udom:$uname";
11841: my ($result,$cached)=&is_cached_new('userres',$hashid);
11842: if (!defined($cached)) {
11843: my %resourcedata=&dump('resourcedata',$udom,$uname);
11844: $result=\%resourcedata;
11845: &do_cache_new('userres',$hashid,$result,600);
11846: }
11847: my ($tmp)=keys(%$result);
11848: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11849: return $result;
11850: }
11851: #error 2 occurs when the .db doesn't exist
11852: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11853: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11854: &logthis("<font color=\"blue\">WARNING:".
11855: " Trying to get resource data for ".
11856: $uname." at ".$udom.": ".
11857: $tmp."</font>");
11858: }
1.624 albertel 11859: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11860: #&EXT_cache_set($udom,$uname);
11861: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11862: undef($tmp); # not really an error so don't send it back
1.624 albertel 11863: }
11864: return $tmp;
11865: }
1.879 foxr 11866: #----------------------------------------------- resdata - return resource data
11867: # Purpose:
11868: # Return resource data for either users or for a course.
11869: # Parameters:
11870: # $name - Course/user name.
11871: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11872: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11873: # $mapp - decluttered URL of enclosing map
11874: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11875: # $recurseup - Ref to array of map URLs, starting with map containing
11876: # $mapp up through hierarchy of nested maps to top level map.
11877: # $courseid - CourseID (first part of param identifier).
11878: # $modifier - Middle part of param identifier.
11879: # $what - Last part of param identifier.
1.879 foxr 11880: # @which - Array of names of resources desired.
11881: # Returns:
11882: # The value of the first reasource in @which that is found in the
11883: # resource hash.
11884: # Exceptional Conditions:
11885: # If the $type passed in is not valid (not the string 'course' or
11886: # 'user', an undefined reference is returned.
11887: # If none of the resources are found, an undef is returned
1.624 albertel 11888: sub resdata {
1.1301 raeburn 11889: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11890: $modifier,$what,@which)=@_;
1.624 albertel 11891: my $result;
11892: if ($type eq 'course') {
11893: $result=&get_courseresdata($name,$domain);
11894: } elsif ($type eq 'user') {
11895: $result=&get_userresdata($name,$domain);
11896: }
11897: if (!ref($result)) { return $result; }
1.251 albertel 11898: foreach my $item (@which) {
1.1301 raeburn 11899: if ($item->[1] eq 'course') {
11900: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11901: unless ($$recursed) {
1.1302 raeburn 11902: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11903: $$recursed = 1;
11904: }
11905: foreach my $item (@${recurseup}) {
11906: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11907: last if (defined($result->{$norecursechk}));
11908: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11909: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11910: }
11911: }
11912: }
11913: if (defined($result->{$item->[0]})) {
1.927 albertel 11914: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11915: }
1.250 albertel 11916: }
1.291 albertel 11917: return undef;
1.200 www 11918: }
11919:
1.1360 raeburn 11920: sub get_domain_lti {
11921: my ($cdom,$context) = @_;
11922: my ($name,%lti);
11923: if ($context eq 'consumer') {
11924: $name = 'ltitools';
11925: } elsif ($context eq 'provider') {
11926: $name = 'lti';
11927: } else {
11928: return %lti;
11929: }
11930: my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298 raeburn 11931: if (defined($cached)) {
11932: if (ref($result) eq 'HASH') {
1.1360 raeburn 11933: %lti = %{$result};
1.1298 raeburn 11934: }
11935: } else {
1.1360 raeburn 11936: my %domconfig = &get_dom('configuration',[$name],$cdom);
11937: if (ref($domconfig{$name}) eq 'HASH') {
11938: %lti = %{$domconfig{$name}};
11939: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11940: if (ref($encdomconfig{$name}) eq 'HASH') {
11941: foreach my $id (keys(%lti)) {
11942: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344 raeburn 11943: foreach my $item ('key','secret') {
1.1360 raeburn 11944: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344 raeburn 11945: }
11946: }
11947: }
11948: }
1.1298 raeburn 11949: }
11950: my $cachetime = 24*60*60;
1.1360 raeburn 11951: &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298 raeburn 11952: }
1.1360 raeburn 11953: return %lti;
1.1298 raeburn 11954: }
11955:
1.1236 raeburn 11956: sub get_numsuppfiles {
11957: my ($cnum,$cdom,$ignorecache)=@_;
11958: my $hashid=$cnum.':'.$cdom;
11959: my ($suppcount,$cached);
11960: unless ($ignorecache) {
11961: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11962: }
11963: unless (defined($cached)) {
11964: my $chome=&homeserver($cnum,$cdom);
11965: unless ($chome eq 'no_host') {
1.1366 raeburn 11966: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 11967: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 11968: ($suppcount,$supptools,$errors) =
11969: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11970: $supptools,$errors);
1.1236 raeburn 11971: }
11972: &do_cache_new('suppcount',$hashid,$suppcount,600);
11973: }
11974: return $suppcount;
11975: }
11976:
1.379 matthew 11977: #
11978: # EXT resource caching routines
11979: #
11980:
1.1302 raeburn 11981: {
11982: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11983: #
11984: # The course for which we cache
11985: my $cachedmapkey='';
11986: # The cached recursive maps for this course
11987: my %cachedmaps=();
11988: # When this was last done
11989: my $cachedmaptime='';
11990:
1.379 matthew 11991: sub clear_EXT_cache_status {
1.383 albertel 11992: &delenv('cache.EXT.');
1.379 matthew 11993: }
11994:
11995: sub EXT_cache_status {
11996: my ($target_domain,$target_user) = @_;
1.383 albertel 11997: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11998: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11999: # We know already the user has no data
12000: return 1;
12001: } else {
12002: return 0;
12003: }
12004: }
12005:
12006: sub EXT_cache_set {
12007: my ($target_domain,$target_user) = @_;
1.383 albertel 12008: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12009: #&appenv({$cachename => time});
1.379 matthew 12010: }
12011:
1.28 www 12012: # --------------------------------------------------------- Value of a Variable
1.58 www 12013: sub EXT {
1.715 albertel 12014:
1.1228 raeburn 12015: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 12016: unless ($varname) { return ''; }
1.218 albertel 12017: #get real user name/domain, courseid and symb
12018: my $courseid;
1.359 albertel 12019: my $publicuser;
1.427 www 12020: if ($symbparm) {
12021: $symbparm=&get_symb_from_alias($symbparm);
12022: }
1.218 albertel 12023: if (!($uname && $udom)) {
1.790 albertel 12024: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12025: if (!$symbparm) { $symbparm=$cursymb; }
12026: } else {
1.620 albertel 12027: $courseid=$env{'request.course.id'};
1.218 albertel 12028: }
1.48 www 12029: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12030: my $rest;
1.320 albertel 12031: if (defined($therest[0])) {
1.48 www 12032: $rest=join('.',@therest);
12033: } else {
12034: $rest='';
12035: }
1.320 albertel 12036:
1.57 www 12037: my $qualifierrest=$qualifier;
12038: if ($rest) { $qualifierrest.='.'.$rest; }
12039: my $spacequalifierrest=$space;
12040: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12041: if ($realm eq 'user') {
1.48 www 12042: # --------------------------------------------------------------- user.resource
12043: if ($space eq 'resource') {
1.651 albertel 12044: if ( (defined($Apache::lonhomework::parsing_a_problem)
12045: || defined($Apache::lonhomework::parsing_a_task))
12046: &&
1.744 albertel 12047: ($symbparm eq &symbread()) ) {
12048: # if we are in the middle of processing the resource the
12049: # get the value we are planning on committing
12050: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12051: return $Apache::lonhomework::results{$qualifierrest};
12052: } else {
12053: return $Apache::lonhomework::history{$qualifierrest};
12054: }
1.335 albertel 12055: } else {
1.359 albertel 12056: my %restored;
1.620 albertel 12057: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12058: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12059: } else {
12060: %restored=&restore($symbparm,$courseid,$udom,$uname);
12061: }
1.335 albertel 12062: return $restored{$qualifierrest};
12063: }
1.48 www 12064: # ----------------------------------------------------------------- user.access
12065: } elsif ($space eq 'access') {
1.218 albertel 12066: # FIXME - not supporting calls for a specific user
1.48 www 12067: return &allowed($qualifier,$rest);
12068: # ------------------------------------------ user.preferences, user.environment
12069: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12070: if (($uname eq $env{'user.name'}) &&
12071: ($udom eq $env{'user.domain'})) {
12072: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12073: } else {
1.359 albertel 12074: my %returnhash;
12075: if (!$publicuser) {
12076: %returnhash=&userenvironment($udom,$uname,
12077: $qualifierrest);
12078: }
1.218 albertel 12079: return $returnhash{$qualifierrest};
12080: }
1.48 www 12081: # ----------------------------------------------------------------- user.course
12082: } elsif ($space eq 'course') {
1.218 albertel 12083: # FIXME - not supporting calls for a specific user
1.620 albertel 12084: return $env{join('.',('request.course',$qualifier))};
1.48 www 12085: # ------------------------------------------------------------------- user.role
12086: } elsif ($space eq 'role') {
1.218 albertel 12087: # FIXME - not supporting calls for a specific user
1.620 albertel 12088: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12089: if ($qualifier eq 'value') {
12090: return $role;
12091: } elsif ($qualifier eq 'extent') {
12092: return $where;
12093: }
12094: # ----------------------------------------------------------------- user.domain
12095: } elsif ($space eq 'domain') {
1.218 albertel 12096: return $udom;
1.48 www 12097: # ------------------------------------------------------------------- user.name
12098: } elsif ($space eq 'name') {
1.218 albertel 12099: return $uname;
1.48 www 12100: # ---------------------------------------------------- Any other user namespace
1.29 www 12101: } else {
1.359 albertel 12102: my %reply;
12103: if (!$publicuser) {
12104: %reply=&get($space,[$qualifierrest],$udom,$uname);
12105: }
12106: return $reply{$qualifierrest};
1.48 www 12107: }
1.236 www 12108: } elsif ($realm eq 'query') {
12109: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12110: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12111: [$spacequalifierrest]);
1.620 albertel 12112: return $env{'form.'.$spacequalifierrest};
1.236 www 12113: } elsif ($realm eq 'request') {
1.48 www 12114: # ------------------------------------------------------------- request.browser
12115: if ($space eq 'browser') {
1.1145 bisitz 12116: return $env{'browser.'.$qualifier};
1.57 www 12117: # ------------------------------------------------------------ request.filename
12118: } else {
1.620 albertel 12119: return $env{'request.'.$spacequalifierrest};
1.29 www 12120: }
1.28 www 12121: } elsif ($realm eq 'course') {
1.48 www 12122: # ---------------------------------------------------------- course.description
1.620 albertel 12123: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12124: } elsif ($realm eq 'resource') {
1.165 www 12125:
1.620 albertel 12126: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12127: if (!$symbparm) { $symbparm=&symbread(); }
12128: }
1.693 albertel 12129:
1.1232 raeburn 12130: if ($qualifier eq '') {
12131: if ($space eq 'title') {
12132: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12133: return &gettitle($symbparm);
12134: }
1.693 albertel 12135:
1.1232 raeburn 12136: if ($space eq 'map') {
12137: my ($map) = &decode_symb($symbparm);
12138: return &symbread($map);
12139: }
12140: if ($space eq 'maptitle') {
12141: my ($map) = &decode_symb($symbparm);
12142: return &gettitle($map);
12143: }
12144: if ($space eq 'filename') {
12145: if ($symbparm) {
12146: return &clutter((&decode_symb($symbparm))[2]);
12147: }
12148: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12149: }
1.1232 raeburn 12150:
1.1233 raeburn 12151: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12152: if ($space eq 'visibleparts') {
12153: my $navmap = Apache::lonnavmaps::navmap->new();
12154: my $item;
12155: if (ref($navmap)) {
12156: my $res = $navmap->getBySymb($symbparm);
12157: my $parts = $res->parts();
12158: if (ref($parts) eq 'ARRAY') {
12159: $item = join(',',@{$parts});
12160: }
12161: undef($navmap);
1.1232 raeburn 12162: }
1.1233 raeburn 12163: return $item;
1.1232 raeburn 12164: }
12165: }
12166: }
1.693 albertel 12167:
1.1301 raeburn 12168: my ($section, $group, @groups, @recurseup, $recursed);
12169: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12170: if (($courseid eq '') && ($cid)) {
12171: $courseid = $cid;
12172: }
12173: if (($symbparm && $courseid) &&
12174: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12175:
1.218 albertel 12176: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12177:
1.60 www 12178: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12179: my $symbp=$symbparm;
1.1301 raeburn 12180: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12181: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12182: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12183: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12184: if (($env{'user.name'} eq $uname) &&
12185: ($env{'user.domain'} eq $udom)) {
12186: $section=$env{'request.course.sec'};
1.733 raeburn 12187: @groups = split(/:/,$env{'request.course.groups'});
12188: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12189: } else {
1.539 albertel 12190: if (! defined($usection)) {
1.551 albertel 12191: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12192: } else {
12193: $section = $usection;
12194: }
1.733 raeburn 12195: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12196: }
12197:
12198: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12199: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12200: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12201: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12202:
1.593 albertel 12203: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12204: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12205: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12206: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12207:
1.60 www 12208: # ----------------------------------------------------------- first, check user
1.624 albertel 12209:
1.1301 raeburn 12210: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12211: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12212: ([$courselevelr,'resource'],
12213: [$courselevelm,'map' ],
1.1301 raeburn 12214: [$courseleveli,'map' ],
1.927 albertel 12215: [$courselevel, 'course' ]));
1.931 albertel 12216: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12217:
1.594 albertel 12218: # ------------------------------------------------ second, check some of course
1.684 raeburn 12219: my $coursereply;
1.691 raeburn 12220: if (@groups > 0) {
12221: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12222: $recurseparm,$mapparm,$spacequalifierrest,
12223: $mapp,\$recursed,\@recurseup);
12224: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12225: }
1.96 www 12226:
1.684 raeburn 12227: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12228: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12229: 'course',$mapp,\$recursed,\@recurseup,
12230: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12231: ([$seclevelr, 'resource'],
12232: [$seclevelm, 'map' ],
1.1301 raeburn 12233: [$secleveli, 'map' ],
1.927 albertel 12234: [$seclevel, 'course' ],
12235: [$courselevelr,'resource']));
12236: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12237:
1.60 www 12238: # ------------------------------------------------------ third, check map parms
1.218 albertel 12239: my %parmhash=();
12240: my $thisparm='';
12241: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12242: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12243: &GDBM_READER(),0640)) {
1.218 albertel 12244: $thisparm=$parmhash{$symbparm};
12245: untie(%parmhash);
12246: }
1.927 albertel 12247: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12248: }
1.594 albertel 12249: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12250:
12251: my $what = $spacequalifierrest;
12252: $what=~s/\./\_/;
1.282 albertel 12253: my $filename;
12254: if (!$symbparm) { $symbparm=&symbread(); }
12255: if ($symbparm) {
1.409 www 12256: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12257: } else {
1.620 albertel 12258: $filename=$env{'request.filename'};
1.282 albertel 12259: }
1.1362 raeburn 12260: my $toolsymb;
12261: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12262: $toolsymb = $symbparm;
12263: }
12264: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12265: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12266: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12267: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12268:
1.1301 raeburn 12269: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12270: if ($symbparm && defined($courseid) &&
1.620 albertel 12271: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12272: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12273: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12274: 'course',$mapp,\$recursed,\@recurseup,
12275: $courseid,'.',$spacequalifierrest,
1.927 albertel 12276: ([$courselevelm,'map' ],
1.1301 raeburn 12277: [$courseleveli,'map' ],
1.927 albertel 12278: [$courselevel, 'course']));
12279: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12280: }
1.145 www 12281: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12282: unless ($space eq '0') {
1.336 albertel 12283: my @parts=split(/_/,$space);
12284: my $id=pop(@parts);
12285: my $part=join('_',@parts);
12286: if ($part eq '') { $part='0'; }
1.927 albertel 12287: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12288: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12289: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12290: }
1.395 albertel 12291: if ($recurse) { return undef; }
1.1362 raeburn 12292: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12293: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12294: # ---------------------------------------------------- Any other user namespace
12295: } elsif ($realm eq 'environment') {
12296: # ----------------------------------------------------------------- environment
1.620 albertel 12297: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12298: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12299: } else {
1.770 albertel 12300: if ($uname eq 'anonymous' && $udom eq '') {
12301: return '';
12302: }
1.219 albertel 12303: my %returnhash=&userenvironment($udom,$uname,
12304: $spacequalifierrest);
12305: return $returnhash{$spacequalifierrest};
12306: }
1.28 www 12307: } elsif ($realm eq 'system') {
1.48 www 12308: # ----------------------------------------------------------------- system.time
12309: if ($space eq 'time') {
12310: return time;
12311: }
1.696 albertel 12312: } elsif ($realm eq 'server') {
12313: # ----------------------------------------------------------------- system.time
12314: if ($space eq 'name') {
12315: return $ENV{'SERVER_NAME'};
12316: }
1.1415 raeburn 12317: } elsif ($realm eq 'client') {
12318: if ($space eq 'remote_addr') {
12319: return $ENV{'REMOTE_ADDR'};
12320: }
1.28 www 12321: }
1.48 www 12322: return '';
1.61 www 12323: }
12324:
1.927 albertel 12325: sub get_reply {
12326: my ($reply_value) = @_;
1.940 raeburn 12327: if (ref($reply_value) eq 'ARRAY') {
12328: if (wantarray) {
12329: return @$reply_value;
12330: }
12331: return $reply_value->[0];
12332: } else {
12333: return $reply_value;
1.927 albertel 12334: }
12335: }
12336:
1.691 raeburn 12337: sub check_group_parms {
1.1301 raeburn 12338: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12339: $recursed,$recurseupref) = @_;
12340: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12341: [$what,'course']);
12342: my $coursereply;
1.691 raeburn 12343: foreach my $group (@{$groups}) {
1.1301 raeburn 12344: my @groupitems = ();
1.691 raeburn 12345: foreach my $level (@levels) {
1.927 albertel 12346: my $item = $courseid.'.['.$group.'].'.$level->[0];
12347: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12348: }
1.1301 raeburn 12349: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12350: $env{'course.'.$courseid.'.domain'},
12351: 'course',$mapp,$recursed,$recurseupref,
12352: $courseid,'.['.$group.'].',$what,
12353: @groupitems);
12354: last if (defined($coursereply));
1.691 raeburn 12355: }
12356: return $coursereply;
12357: }
12358:
1.1301 raeburn 12359: sub get_map_hierarchy {
1.1302 raeburn 12360: my ($mapname,$courseid) = @_;
12361: my @recurseup = ();
1.1301 raeburn 12362: if ($mapname) {
1.1302 raeburn 12363: if (($cachedmapkey eq $courseid) &&
12364: (abs($cachedmaptime-time)<5)) {
12365: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12366: return @{$cachedmaps{$mapname}};
12367: }
12368: }
1.1301 raeburn 12369: my $navmap = Apache::lonnavmaps::navmap->new();
12370: if (ref($navmap)) {
12371: @recurseup = $navmap->recurseup_maps($mapname);
12372: undef($navmap);
1.1302 raeburn 12373: $cachedmaps{$mapname} = \@recurseup;
12374: $cachedmaptime=time;
12375: $cachedmapkey=$courseid;
1.1301 raeburn 12376: }
12377: }
12378: return @recurseup;
12379: }
12380:
1.1302 raeburn 12381: }
12382:
1.691 raeburn 12383: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12384: my ($courseid,@groups) = @_;
12385: @groups = sort(@groups);
1.691 raeburn 12386: return @groups;
12387: }
12388:
1.395 albertel 12389: sub packages_tab_default {
1.1362 raeburn 12390: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12391: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12392:
12393: my (@extension,@specifics,$do_default);
1.1362 raeburn 12394: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12395: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12396: if ($pack_type eq 'default') {
12397: $do_default=1;
12398: } elsif ($pack_type eq 'extension') {
12399: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12400: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12401: # only look at packages defaults for packages that this id is
1.738 albertel 12402: push(@specifics,[$package,$pack_type,$pack_part]);
12403: }
12404: }
12405: # first look for a package that matches the requested part id
12406: foreach my $package (@specifics) {
12407: my (undef,$pack_type,$pack_part)=@{$package};
12408: next if ($pack_part ne $part);
12409: if (defined($packagetab{"$pack_type&$name&default"})) {
12410: return $packagetab{"$pack_type&$name&default"};
12411: }
12412: }
12413: # look for any possible matching non extension_ package
12414: foreach my $package (@specifics) {
12415: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12416: if (defined($packagetab{"$pack_type&$name&default"})) {
12417: return $packagetab{"$pack_type&$name&default"};
12418: }
1.585 albertel 12419: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12420: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12421: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12422: }
12423: }
1.738 albertel 12424: # look for any posible extension_ match
12425: foreach my $package (@extension) {
12426: my ($package,$pack_type)=@{$package};
12427: if (defined($packagetab{"$pack_type&$name&default"})) {
12428: return $packagetab{"$pack_type&$name&default"};
12429: }
12430: if (defined($packagetab{$package."&$name&default"})) {
12431: return $packagetab{$package."&$name&default"};
12432: }
12433: }
12434: # look for a global default setting
12435: if ($do_default && defined($packagetab{"default&$name&default"})) {
12436: return $packagetab{"default&$name&default"};
12437: }
1.395 albertel 12438: return undef;
12439: }
12440:
1.334 albertel 12441: sub add_prefix_and_part {
12442: my ($prefix,$part)=@_;
12443: my $keyroot;
12444: if (defined($prefix) && $prefix !~ /^__/) {
12445: # prefix that has a part already
12446: $keyroot=$prefix;
12447: } elsif (defined($prefix)) {
12448: # prefix that is missing a part
12449: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12450: } else {
12451: # no prefix at all
12452: if (defined($part)) { $keyroot='_'.$part; }
12453: }
12454: return $keyroot;
12455: }
12456:
1.71 www 12457: # ---------------------------------------------------------------- Get metadata
12458:
1.599 albertel 12459: my %metaentry;
1.1070 www 12460: my %importedpartids;
1.1369 raeburn 12461: my %importedrespids;
1.71 www 12462: sub metadata {
1.1362 raeburn 12463: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12464: $uri=&declutter($uri);
1.288 albertel 12465: # if it is a non metadata possible uri return quickly
1.529 albertel 12466: if (($uri eq '') ||
12467: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12468: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12469: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12470: return undef;
12471: }
1.1261 raeburn 12472: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12473: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12474: return undef;
1.288 albertel 12475: }
1.73 www 12476: my $filename=$uri;
12477: $uri=~s/\.meta$//;
1.172 www 12478: #
12479: # Is the metadata already cached?
1.177 www 12480: # Look at timestamp of caching
1.172 www 12481: # Everything is cached by the main uri, libraries are never directly cached
12482: #
1.428 albertel 12483: if (!defined($liburi)) {
1.599 albertel 12484: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12485: if (defined($cached)) { return $result->{':'.$what}; }
12486: }
1.1362 raeburn 12487:
12488: #
12489: # If the uri is for an external tool the file from
12490: # which metadata should be retrieved depends on whether
12491: # the tool had been configured to be gradable (set in the Course
12492: # Editor or Resource Editor).
12493: #
12494: # If a valid symb has been included as the third arg in the call
12495: # to &metadata() that can be used to retrieve the value of
12496: # parameter_0_gradable set for the resource, and included in the
12497: # uploaded map containing the tool. The value is retrieved via
12498: # &EXT(), if a valid symb is available. Otherwise the value of
12499: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12500: # is retrieved via &get().
12501: #
12502: # When lonuserstate::traceroute() calls lonnet::EXT() for
12503: # hiddenresource and encrypturl (during course initialization)
12504: # the map-level parameter for resource.0.gradable included in the
12505: # uploaded map containing the tool will not yet have been stored
12506: # in the user_course_parms.db file for the user's session, so in
12507: # this case fall back to retrieving gradable status from the
12508: # exttool_$marker.db file.
1.1362 raeburn 12509: #
12510: # In order to avoid an infinite loop, &metadata() will return
12511: # before a call to &EXT(), if the uri is for an external tool
12512: # and the $what for which metadata is being requested is
12513: # parameter_0_gradable or 0_gradable.
12514: #
12515:
12516: if ($uri =~ /ext\.tool$/) {
12517: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12518: return;
12519: } else {
12520: my ($checked,$use_passback);
12521: if ($toolsymb ne '') {
12522: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12523: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12524: $checked = 1;
12525: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12526: $use_passback = 1;
12527: }
12528: }
12529: }
12530: unless ($checked) {
12531: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12532: $marker=~s/\D//g;
1.1363 raeburn 12533: if ($marker) {
1.1362 raeburn 12534: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12535: $use_passback = $toolsettings{'gradable'};
12536: }
12537: }
12538: if ($use_passback) {
12539: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12540: } else {
12541: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12542: }
12543: }
12544: }
12545:
1.428 albertel 12546: {
1.1069 www 12547: # Imported parts would go here
1.1369 raeburn 12548: my @origfiletagids=();
1.1069 www 12549: my $importedparts=0;
1.1369 raeburn 12550:
12551: # Imported responseids would go here
12552: my $importedresponses=0;
1.172 www 12553: #
12554: # Is this a recursive call for a library?
12555: #
1.599 albertel 12556: # if (! exists($metacache{$uri})) {
12557: # $metacache{$uri}={};
12558: # }
1.924 albertel 12559: my $cachetime = 60*60;
1.171 www 12560: if ($liburi) {
12561: $liburi=&declutter($liburi);
12562: $filename=$liburi;
1.401 bowersj2 12563: } else {
1.599 albertel 12564: &devalidate_cache_new('meta',$uri);
12565: undef(%metaentry);
1.401 bowersj2 12566: }
1.140 www 12567: my %metathesekeys=();
1.73 www 12568: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12569: my $metastring;
1.1140 www 12570: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12571: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12572: $metastring =
1.929 albertel 12573: &Apache::lonnet::ssi_body($which,
1.924 albertel 12574: ('grade_target' => 'meta'));
12575: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12576: } elsif (($uri !~ m -^(editupload)/-) &&
12577: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12578: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12579: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12580: $metastring=&getfile($file);
1.489 albertel 12581: }
1.208 albertel 12582: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12583: my $token;
1.140 www 12584: undef %metathesekeys;
1.71 www 12585: while ($token=$parser->get_token) {
1.339 albertel 12586: if ($token->[0] eq 'S') {
12587: if (defined($token->[2]->{'package'})) {
1.172 www 12588: #
12589: # This is a package - get package info
12590: #
1.339 albertel 12591: my $package=$token->[2]->{'package'};
12592: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12593: if (defined($token->[2]->{'id'})) {
12594: $keyroot.='_'.$token->[2]->{'id'};
12595: }
1.599 albertel 12596: if ($metaentry{':packages'}) {
12597: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12598: } else {
1.599 albertel 12599: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12600: }
1.736 albertel 12601: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12602: my $part=$keyroot;
12603: $part=~s/^\_//;
1.736 albertel 12604: if ($pack_entry=~/^\Q$package\E\&/ ||
12605: $pack_entry=~/^\Q$package\E_0\&/) {
12606: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12607: # ignore package.tab specified default values
12608: # here &package_tab_default() will fetch those
12609: if ($subp eq 'default') { next; }
1.736 albertel 12610: my $value=$packagetab{$pack_entry};
1.432 albertel 12611: my $unikey;
12612: if ($pack =~ /_0$/) {
12613: $unikey='parameter_0_'.$name;
12614: $part=0;
12615: } else {
12616: $unikey='parameter'.$keyroot.'_'.$name;
12617: }
1.339 albertel 12618: if ($subp eq 'display') {
12619: $value.=' [Part: '.$part.']';
12620: }
1.599 albertel 12621: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12622: $metathesekeys{$unikey}=1;
1.599 albertel 12623: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12624: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12625: }
1.599 albertel 12626: if (defined($metaentry{':'.$unikey.'.default'})) {
12627: $metaentry{':'.$unikey}=
12628: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12629: }
1.339 albertel 12630: }
12631: }
12632: } else {
1.172 www 12633: #
12634: # This is not a package - some other kind of start tag
1.339 albertel 12635: #
12636: my $entry=$token->[1];
1.1068 www 12637: my $unikey='';
1.175 www 12638:
1.339 albertel 12639: if ($entry eq 'import') {
1.175 www 12640: #
12641: # Importing a library here
1.339 albertel 12642: #
1.1067 www 12643: my $location=$parser->get_text('/import');
12644: my $dir=$filename;
12645: $dir=~s|[^/]*$||;
12646: $location=&filelocation($dir,$location);
1.1369 raeburn 12647:
12648: my $importid=$token->[2]->{'id'};
1.1068 www 12649: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 12650: #
12651: # Check metadata for imported file to
12652: # see if it contained response items
12653: #
1.1372 raeburn 12654: my ($origfile,@libfilekeys);
1.1370 raeburn 12655: my %currmetaentry = %metaentry;
1.1372 raeburn 12656: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12657: $depthcount+1));
12658: if (grep(/^responseorder$/,@libfilekeys)) {
12659: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12660: undef,$depthcount+1);
12661: if ($libresponseorder ne '') {
12662: if ($#origfiletagids<0) {
12663: undef(%importedrespids);
12664: undef(%importedpartids);
12665: }
1.1373 raeburn 12666: my @respids = split(/\s*,\s*/,$libresponseorder);
12667: if (@respids) {
12668: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12669: }
12670: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 12671: $importedresponses = 1;
1.1369 raeburn 12672: # We need to get the original file and the imported file to get the response order correct
12673: # Load and inspect original file
1.1372 raeburn 12674: if ($#origfiletagids<0) {
12675: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12676: $origfile=&getfile($origfilelocation);
12677: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12678: }
1.1369 raeburn 12679: }
12680: }
12681: }
1.1370 raeburn 12682: # Do not overwrite contents of %metaentry hash for resource itself with
12683: # hash populated for imported library file
12684: %metaentry = %currmetaentry;
12685: undef(%currmetaentry);
1.1374 raeburn 12686: if ($importmode eq 'part') {
1.1068 www 12687: # Import as part(s)
1.1069 www 12688: $importedparts=1;
12689: # We need to get the original file and the imported file to get the part order correct
12690: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 12691: # Load and inspect original file if we didn't do that already
12692: if ($#origfiletagids<0) {
12693: undef(%importedrespids);
12694: undef(%importedpartids);
12695: if ($origfile eq '') {
12696: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12697: $origfile=&getfile($origfilelocation);
12698: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12699: }
1.1070 www 12700: }
1.1372 raeburn 12701: my @impfilepartids;
12702: # If <partorder> tag is included in metadata for the imported file
12703: # get the parts in the imported file from that.
12704: if (grep(/^partorder$/,@libfilekeys)) {
12705: %currmetaentry = %metaentry;
12706: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12707: $depthcount+1);
12708: %metaentry = %currmetaentry;
12709: undef(%currmetaentry);
12710: if ($libpartorder ne '') {
12711: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12712: }
12713: } else {
12714: # If no <partorder> tag available, load and inspect imported file
12715: my $impfile=&getfile($location);
12716: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12717: }
1.1069 www 12718: if ($#impfilepartids>=0) {
12719: # This problem had parts
1.1070 www 12720: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12721: } else {
12722: # Importing by turning a single problem into a problem part
12723: # It gets the import-tags ID as part-ID
12724: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12725: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12726: }
1.1068 www 12727: } else {
1.1374 raeburn 12728: # Import as problem or as normal import
12729: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12730: unless ($importmode eq 'problem') {
1.1068 www 12731: # Normal import
1.1374 raeburn 12732: if (defined($token->[2]->{'id'})) {
12733: $unikey.='_'.$token->[2]->{'id'};
12734: }
12735: }
12736: # Check metadata for imported file to
12737: # see if it contained parts
12738: if (grep(/^partorder$/,@libfilekeys)) {
12739: %currmetaentry = %metaentry;
12740: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12741: $depthcount+1);
12742: %metaentry = %currmetaentry;
12743: undef(%currmetaentry);
12744: if ($libpartorder ne '') {
12745: $importedparts = 1;
12746: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12747: }
12748: }
1.1067 www 12749: }
1.339 albertel 12750: if ($depthcount<20) {
1.736 albertel 12751: my $metadata =
1.1362 raeburn 12752: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 12753: $depthcount+1);
12754: foreach my $meta (split(',',$metadata)) {
12755: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12756: $metathesekeys{$meta}=1;
1.339 albertel 12757: }
1.1068 www 12758: }
1.1067 www 12759: } else {
12760: #
12761: # Not importing, some other kind of non-package, non-library start tag
12762: #
12763: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12764: if (defined($token->[2]->{'id'})) {
12765: $unikey.='_'.$token->[2]->{'id'};
12766: }
1.339 albertel 12767: if (defined($token->[2]->{'name'})) {
12768: $unikey.='_'.$token->[2]->{'name'};
12769: }
12770: $metathesekeys{$unikey}=1;
1.736 albertel 12771: foreach my $param (@{$token->[3]}) {
12772: $metaentry{':'.$unikey.'.'.$param} =
12773: $token->[2]->{$param};
1.339 albertel 12774: }
12775: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12776: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12777: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12778: # only ws inside the tag, and not in default, so use default
12779: # as value
1.599 albertel 12780: $metaentry{':'.$unikey}=$default;
1.908 albertel 12781: } elsif ( $internaltext =~ /\S/ ) {
12782: # something interesting inside the tag
12783: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12784: } else {
1.908 albertel 12785: # no interesting values, don't set a default
1.339 albertel 12786: }
1.172 www 12787: # end of not-a-package not-a-library import
1.339 albertel 12788: }
1.172 www 12789: # end of not-a-package start tag
1.339 albertel 12790: }
1.172 www 12791: # the next is the end of "start tag"
1.339 albertel 12792: }
12793: }
1.483 albertel 12794: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12795: $extension = lc($extension);
12796: if ($extension eq 'htm') { $extension='html'; }
12797:
1.737 albertel 12798: foreach my $key (keys(%packagetab)) {
1.483 albertel 12799: #no specific packages #how's our extension
12800: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12801: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12802: \%metathesekeys);
12803: }
1.883 albertel 12804:
12805: if (!exists($metaentry{':packages'})
12806: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12807: foreach my $key (keys(%packagetab)) {
1.483 albertel 12808: #no specific packages well let's get default then
12809: if ($key!~/^default&/) { next; }
1.488 albertel 12810: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12811: \%metathesekeys);
12812: }
12813: }
1.338 www 12814: # are there custom rights to evaluate
1.599 albertel 12815: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12816:
1.338 www 12817: #
12818: # Importing a rights file here
1.339 albertel 12819: #
12820: unless ($depthcount) {
1.599 albertel 12821: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12822: my $dir=$filename;
12823: $dir=~s|[^/]*$||;
12824: $location=&filelocation($dir,$location);
1.736 albertel 12825: my $rights_metadata =
1.1362 raeburn 12826: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 12827: $depthcount+1);
12828: foreach my $rights (split(',',$rights_metadata)) {
12829: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12830: $metathesekeys{$rights}=1;
1.339 albertel 12831: }
12832: }
12833: }
1.737 albertel 12834: # uniqifiy package listing
12835: my %seen;
12836: my @uniq_packages =
12837: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12838: $metaentry{':packages'} = join(',',@uniq_packages);
12839:
1.1369 raeburn 12840: if (($importedresponses) || ($importedparts)) {
12841: if ($importedparts) {
1.1070 www 12842: # We had imported parts and need to rebuild partorder
1.1369 raeburn 12843: $metaentry{':partorder'}='';
12844: $metathesekeys{'partorder'}=1;
12845: }
12846: if ($importedresponses) {
12847: # We had imported responses and need to rebuil responseorder
12848: $metaentry{':responseorder'}='';
12849: $metathesekeys{'responseorder'}=1;
12850: }
12851: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12852: my $origid = $origfiletagids[$index+1];
12853: if ($origfiletagids[$index] eq 'part') {
12854: # Original part, part of the problem
12855: if ($importedparts) {
12856: $metaentry{':partorder'}.=','.$origid;
12857: }
12858: } elsif ($origfiletagids[$index] eq 'import') {
12859: if ($importedparts) {
12860: # We have imported parts at this position
1.1373 raeburn 12861: if ($importedpartids{$origid} ne '') {
12862: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12863: }
1.1369 raeburn 12864: }
12865: if ($importedresponses) {
12866: # We have imported responses at this position
1.1373 raeburn 12867: if ($importedrespids{$origid} ne '') {
12868: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 12869: }
12870: }
12871: } else {
12872: # Original response item, part of the problem
12873: if ($importedresponses) {
12874: $metaentry{':responseorder'}.=','.$origid;
12875: }
12876: }
12877: }
12878: if ($importedparts) {
12879: $metaentry{':partorder'}=~s/^\,//;
12880: }
12881: if ($importedresponses) {
12882: $metaentry{':responseorder'}=~s/^\,//;
12883: }
1.1070 www 12884: }
1.737 albertel 12885: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12886: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 12887: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 12888: unless ($liburi) {
12889: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12890: }
1.177 www 12891: # this is the end of "was not already recently cached
1.71 www 12892: }
1.599 albertel 12893: return $metaentry{':'.$what};
1.261 albertel 12894: }
12895:
1.488 albertel 12896: sub metadata_create_package_def {
1.483 albertel 12897: my ($uri,$key,$package,$metathesekeys)=@_;
12898: my ($pack,$name,$subp)=split(/\&/,$key);
12899: if ($subp eq 'default') { next; }
12900:
1.599 albertel 12901: if (defined($metaentry{':packages'})) {
12902: $metaentry{':packages'}.=','.$package;
1.483 albertel 12903: } else {
1.599 albertel 12904: $metaentry{':packages'}=$package;
1.483 albertel 12905: }
12906: my $value=$packagetab{$key};
12907: my $unikey;
12908: $unikey='parameter_0_'.$name;
1.599 albertel 12909: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12910: $$metathesekeys{$unikey}=1;
1.599 albertel 12911: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12912: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12913: }
1.599 albertel 12914: if (defined($metaentry{':'.$unikey.'.default'})) {
12915: $metaentry{':'.$unikey}=
12916: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12917: }
12918: }
12919:
1.261 albertel 12920: sub metadata_generate_part0 {
12921: my ($metadata,$metacache,$uri) = @_;
12922: my %allnames;
1.737 albertel 12923: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12924: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12925: my $part=$$metacache{':'.$metakey.'.part'};
12926: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12927: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12928: $allnames{$name}=$part;
12929: }
12930: }
12931: }
12932: foreach my $name (keys(%allnames)) {
12933: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12934: my $key=":parameter_0_$name";
1.261 albertel 12935: $$metacache{"$key.part"}='0';
12936: $$metacache{"$key.name"}=$name;
1.428 albertel 12937: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12938: $allnames{$name}.'_'.$name.
12939: '.type'};
1.428 albertel 12940: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12941: '.display'};
1.644 www 12942: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12943: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12944: $$metacache{"$key.display"}=$olddis;
12945: }
1.71 www 12946: }
12947:
1.764 albertel 12948: # ------------------------------------------------------ Devalidate title cache
12949:
12950: sub devalidate_title_cache {
12951: my ($url)=@_;
12952: if (!$env{'request.course.id'}) { return; }
12953: my $symb=&symbread($url);
12954: if (!$symb) { return; }
12955: my $key=$env{'request.course.id'}."\0".$symb;
12956: &devalidate_cache_new('title',$key);
12957: }
12958:
1.1014 droeschl 12959: # ------------------------------------------------- Get the title of a course
12960:
12961: sub current_course_title {
12962: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12963: }
1.301 www 12964: # ------------------------------------------------- Get the title of a resource
12965:
12966: sub gettitle {
12967: my $urlsymb=shift;
12968: my $symb=&symbread($urlsymb);
1.534 albertel 12969: if ($symb) {
1.620 albertel 12970: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12971: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12972: if (defined($cached)) {
12973: return $result;
12974: }
1.534 albertel 12975: my ($map,$resid,$url)=&decode_symb($symb);
12976: my $title='';
1.907 albertel 12977: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12978: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12979: } else {
12980: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12981: &GDBM_READER(),0640)) {
12982: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12983: $title=$bighash{'title_'.$mapid.'.'.$resid};
12984: untie(%bighash);
12985: }
1.534 albertel 12986: }
12987: $title=~s/\&colon\;/\:/gs;
12988: if ($title) {
1.1159 www 12989: # Remember both $symb and $title for dynamic metadata
12990: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12991: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12992: # Cache this title and then return it
1.599 albertel 12993: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12994: }
12995: $urlsymb=$url;
12996: }
12997: my $title=&metadata($urlsymb,'title');
12998: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12999: return $title;
1.301 www 13000: }
1.613 albertel 13001:
1.614 albertel 13002: sub get_slot {
13003: my ($which,$cnum,$cdom)=@_;
13004: if (!$cnum || !$cdom) {
1.790 albertel 13005: (undef,my $courseid)=&whichuser();
1.620 albertel 13006: $cdom=$env{'course.'.$courseid.'.domain'};
13007: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13008: }
1.703 albertel 13009: my $key=join("\0",'slots',$cdom,$cnum,$which);
13010: my %slotinfo;
13011: if (exists($remembered{$key})) {
13012: $slotinfo{$which} = $remembered{$key};
13013: } else {
13014: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13015: &Apache::lonhomework::showhash(%slotinfo);
13016: my ($tmp)=keys(%slotinfo);
13017: if ($tmp=~/^error:/) { return (); }
13018: $remembered{$key} = $slotinfo{$which};
13019: }
1.616 albertel 13020: if (ref($slotinfo{$which}) eq 'HASH') {
13021: return %{$slotinfo{$which}};
13022: }
13023: return $slotinfo{$which};
1.614 albertel 13024: }
1.1150 raeburn 13025:
13026: sub get_reservable_slots {
13027: my ($cnum,$cdom,$uname,$udom) = @_;
13028: my $now = time;
13029: my $reservable_info;
13030: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13031: if (exists($remembered{$key})) {
13032: $reservable_info = $remembered{$key};
13033: } else {
13034: my %resv;
13035: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13036: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13037: $reservable_info = \%resv;
13038: $remembered{$key} = $reservable_info;
13039: }
13040: return $reservable_info;
13041: }
13042:
13043: sub get_course_slots {
13044: my ($cnum,$cdom) = @_;
13045: my $hashid=$cnum.':'.$cdom;
13046: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13047: if (defined($cached)) {
13048: if (ref($result) eq 'HASH') {
13049: return %{$result};
13050: }
13051: } else {
13052: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13053: my ($tmp) = keys(%slots);
13054: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13055: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13056: return %slots;
13057: }
13058: }
13059: return;
13060: }
13061:
13062: sub devalidate_slots_cache {
13063: my ($cnum,$cdom)=@_;
13064: my $hashid=$cnum.':'.$cdom;
13065: &devalidate_cache_new('allslots',$hashid);
13066: }
13067:
1.1181 raeburn 13068: sub get_coursechange {
13069: my ($cdom,$cnum) = @_;
13070: if ($cdom eq '' || $cnum eq '') {
13071: return unless ($env{'request.course.id'});
13072: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13073: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13074: }
13075: my $hashid=$cdom.'_'.$cnum;
13076: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13077: if ((defined($cached)) && ($change ne '')) {
13078: return $change;
13079: } else {
13080: my %crshash;
13081: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13082: if ($crshash{'internal.contentchange'} eq '') {
13083: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13084: if ($change eq '') {
13085: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13086: $change = $crshash{'internal.created'};
13087: }
13088: } else {
13089: $change = $crshash{'internal.contentchange'};
13090: }
13091: my $cachetime = 600;
13092: &do_cache_new('crschange',$hashid,$change,$cachetime);
13093: }
13094: return $change;
13095: }
13096:
13097: sub devalidate_coursechange_cache {
13098: my ($cnum,$cdom)=@_;
13099: my $hashid=$cnum.':'.$cdom;
13100: &devalidate_cache_new('crschange',$hashid);
13101: }
13102:
1.31 www 13103: # ------------------------------------------------- Update symbolic store links
13104:
13105: sub symblist {
13106: my ($mapname,%newhash)=@_;
1.438 www 13107: $mapname=&deversion(&declutter($mapname));
1.31 www 13108: my %hash;
1.620 albertel 13109: if (($env{'request.course.fn'}) && (%newhash)) {
13110: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13111: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13112: foreach my $url (keys(%newhash)) {
1.711 albertel 13113: next if ($url eq 'last_known'
13114: && $env{'form.no_update_last_known'});
13115: $hash{declutter($url)}=&encode_symb($mapname,
13116: $newhash{$url}->[1],
13117: $newhash{$url}->[0]);
1.191 harris41 13118: }
1.31 www 13119: if (untie(%hash)) {
13120: return 'ok';
13121: }
13122: }
13123: }
13124: return 'error';
1.212 www 13125: }
13126:
13127: # --------------------------------------------------------------- Verify a symb
13128:
13129: sub symbverify {
1.1190 raeburn 13130: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13131: my $thisfn=$thisurl;
1.439 www 13132: $thisfn=&declutter($thisfn);
1.215 www 13133: # direct jump to resource in page or to a sequence - will construct own symbs
13134: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13135: # check URL part
1.409 www 13136: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13137:
1.431 www 13138: unless ($url eq $thisfn) { return 0; }
1.213 www 13139:
1.216 www 13140: $symb=&symbclean($symb);
1.510 www 13141: $thisurl=&deversion($thisurl);
1.439 www 13142: $thisfn=&deversion($thisfn);
1.213 www 13143:
13144: my %bighash;
13145: my $okay=0;
1.431 www 13146:
1.620 albertel 13147: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13148: &GDBM_READER(),0640)) {
1.1032 raeburn 13149: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13150: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13151: if ($map =~ m{^uploaded/.+\.page$}) {
13152: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13153: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13154: }
13155: }
13156: my $ids;
1.1419 raeburn 13157: if ($map =~ m{^uploaded/.+\.page$}) {
13158: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13159: } else {
13160: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13161: }
1.1102 raeburn 13162: unless ($ids) {
13163: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13164: $ids=$bighash{$idkey};
1.216 www 13165: }
13166: if ($ids) {
13167: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13168: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13169: $symb =~ s/\?.+$//;
1.1202 raeburn 13170: }
1.800 albertel 13171: foreach my $id (split(/\,/,$ids)) {
13172: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13173: if (
13174: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13175: eq $symb) {
13176: if (ref($encstate)) {
13177: $$encstate = $bighash{'encrypted_'.$id};
13178: }
1.620 albertel 13179: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13180: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13181: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13182: $okay=1;
1.1202 raeburn 13183: last;
1.582 albertel 13184: }
13185: }
1.216 www 13186: }
13187: }
1.213 www 13188: untie(%bighash);
13189: }
13190: return $okay;
1.31 www 13191: }
13192:
1.210 www 13193: # --------------------------------------------------------------- Clean-up symb
13194:
13195: sub symbclean {
13196: my $symb=shift;
1.568 albertel 13197: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13198: # remove version from map
13199: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13200:
1.210 www 13201: # remove version from URL
13202: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13203:
1.507 www 13204: # remove wrapper
13205:
1.510 www 13206: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13207: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13208: return $symb;
1.409 www 13209: }
13210:
13211: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13212:
13213: sub encode_symb {
13214: my ($map,$resid,$url)=@_;
13215: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13216: }
1.409 www 13217:
13218: sub decode_symb {
1.568 albertel 13219: my $symb=shift;
13220: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13221: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13222: return (&fixversion($map),$resid,&fixversion($url));
13223: }
13224:
13225: sub fixversion {
13226: my $fn=shift;
1.609 banghart 13227: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13228: my %bighash;
13229: my $uri=&clutter($fn);
1.620 albertel 13230: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13231: # is this cached?
1.599 albertel 13232: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13233: if (defined($cached)) { return $result; }
13234: # unfortunately not cached, or expired
1.620 albertel 13235: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13236: &GDBM_READER(),0640)) {
13237: if ($bighash{'version_'.$uri}) {
13238: my $version=$bighash{'version_'.$uri};
1.444 www 13239: unless (($version eq 'mostrecent') ||
13240: ($version==&getversion($uri))) {
1.440 www 13241: $uri=~s/\.(\w+)$/\.$version\.$1/;
13242: }
13243: }
13244: untie %bighash;
1.413 www 13245: }
1.599 albertel 13246: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13247: }
13248:
13249: sub deversion {
13250: my $url=shift;
13251: $url=~s/\.\d+\.(\w+)$/\.$1/;
13252: return $url;
1.210 www 13253: }
13254:
1.31 www 13255: # ------------------------------------------------------ Return symb list entry
13256:
13257: sub symbread {
1.1282 raeburn 13258: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 13259: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 13260: if (defined($env{$cache_str})) {
13261: if ($ignorecachednull) {
13262: return $env{$cache_str} unless ($env{$cache_str} eq '');
13263: } else {
13264: return $env{$cache_str};
13265: }
13266: }
1.242 www 13267: # no filename provided? try from environment
1.1265 raeburn 13268: unless ($thisfn) {
1.620 albertel 13269: if ($env{'request.symb'}) {
13270: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13271: }
1.620 albertel 13272: $thisfn=$env{'request.filename'};
1.44 www 13273: }
1.569 albertel 13274: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13275: # is that filename actually a symb? Verify, clean, and return
13276: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13277: if (&symbverify($thisfn,$1)) {
1.620 albertel 13278: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13279: }
1.242 www 13280: }
1.44 www 13281: $thisfn=declutter($thisfn);
1.31 www 13282: my %hash;
1.37 www 13283: my %bighash;
13284: my $syval='';
1.620 albertel 13285: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13286: my $targetfn = $thisfn;
1.609 banghart 13287: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13288: $targetfn = 'adm/wrapper/'.$thisfn;
13289: }
1.687 albertel 13290: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13291: $targetfn=$1;
13292: }
1.620 albertel 13293: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13294: &GDBM_READER(),0640)) {
1.481 raeburn 13295: $syval=$hash{$targetfn};
1.37 www 13296: untie(%hash);
13297: }
13298: # ---------------------------------------------------------- There was an entry
13299: if ($syval) {
1.601 albertel 13300: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13301: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13302: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13303: #return $env{$cache_str}='';
1.601 albertel 13304: #}
13305: #$syval.=$1;
13306: #}
1.37 www 13307: } else {
13308: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13309: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13310: &GDBM_READER(),0640)) {
1.37 www 13311: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13312: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13313: unless ($ids) {
13314: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13315: }
13316: unless ($ids) {
13317: # alias?
13318: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13319: }
1.37 www 13320: if ($ids) {
13321: # ------------------------------------------------------------------- Has ID(s)
13322: my @possibilities=split(/\,/,$ids);
1.39 www 13323: if ($#possibilities==0) {
13324: # ----------------------------------------------- There is only one possibility
1.37 www 13325: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13326: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13327: $resid,$thisfn);
1.1282 raeburn 13328: if (ref($possibles) eq 'HASH') {
13329: $possibles->{$syval} = 1;
13330: }
13331: if ($checkforblock) {
13332: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13333: if (@blockers) {
13334: $syval = '';
13335: return;
13336: }
13337: }
13338: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13339: # ------------------------------------------ There is more than one possibility
13340: my $realpossible=0;
1.800 albertel 13341: foreach my $id (@possibilities) {
13342: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13343: my $canaccess;
13344: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13345: $canaccess = 1;
13346: } else {
13347: $canaccess = &allowed('bre',$file);
13348: }
13349: if ($canaccess) {
13350: my ($mapid,$resid)=split(/\./,$id);
13351: if ($bighash{'map_type_'.$mapid} ne 'page') {
13352: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13353: $resid,$thisfn);
13354: if (ref($possibles) eq 'HASH') {
13355: $possibles->{$syval} = 1;
13356: }
13357: if ($checkforblock) {
13358: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13359: unless (@blockers > 0) {
13360: $syval = $poss_syval;
13361: $realpossible++;
13362: }
13363: } else {
13364: $syval = $poss_syval;
13365: $realpossible++;
13366: }
13367: }
1.39 www 13368: }
1.191 harris41 13369: }
1.39 www 13370: if ($realpossible!=1) { $syval=''; }
1.249 www 13371: } else {
13372: $syval='';
1.37 www 13373: }
13374: }
1.1282 raeburn 13375: untie(%bighash);
1.481 raeburn 13376: }
1.31 www 13377: }
1.62 www 13378: if ($syval) {
1.620 albertel 13379: return $env{$cache_str}=$syval;
1.62 www 13380: }
1.31 www 13381: }
1.949 raeburn 13382: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13383: return $env{$cache_str}='';
1.31 www 13384: }
13385:
13386: # ---------------------------------------------------------- Return random seed
13387:
1.32 www 13388: sub numval {
13389: my $txt=shift;
13390: $txt=~tr/A-J/0-9/;
13391: $txt=~tr/a-j/0-9/;
13392: $txt=~tr/K-T/0-9/;
13393: $txt=~tr/k-t/0-9/;
13394: $txt=~tr/U-Z/0-5/;
13395: $txt=~tr/u-z/0-5/;
13396: $txt=~s/\D//g;
1.564 albertel 13397: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13398: return int($txt);
1.368 albertel 13399: }
13400:
1.484 albertel 13401: sub numval2 {
13402: my $txt=shift;
13403: $txt=~tr/A-J/0-9/;
13404: $txt=~tr/a-j/0-9/;
13405: $txt=~tr/K-T/0-9/;
13406: $txt=~tr/k-t/0-9/;
13407: $txt=~tr/U-Z/0-5/;
13408: $txt=~tr/u-z/0-5/;
13409: $txt=~s/\D//g;
13410: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13411: my $total;
13412: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13413: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13414: return int($total);
13415: }
13416:
1.575 albertel 13417: sub numval3 {
13418: use integer;
13419: my $txt=shift;
13420: $txt=~tr/A-J/0-9/;
13421: $txt=~tr/a-j/0-9/;
13422: $txt=~tr/K-T/0-9/;
13423: $txt=~tr/k-t/0-9/;
13424: $txt=~tr/U-Z/0-5/;
13425: $txt=~tr/u-z/0-5/;
13426: $txt=~s/\D//g;
13427: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13428: my $total;
13429: foreach my $val (@txts) { $total+=$val; }
13430: if ($_64bit) { $total=(($total<<32)>>32); }
13431: return $total;
13432: }
13433:
1.675 albertel 13434: sub digest {
13435: my ($data)=@_;
13436: my $digest=&Digest::MD5::md5($data);
13437: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13438: my ($e,$f);
13439: {
13440: use integer;
13441: $e=($a+$b);
13442: $f=($c+$d);
13443: if ($_64bit) {
13444: $e=(($e<<32)>>32);
13445: $f=(($f<<32)>>32);
13446: }
13447: }
13448: if (wantarray) {
13449: return ($e,$f);
13450: } else {
13451: my $g;
13452: {
13453: use integer;
13454: $g=($e+$f);
13455: if ($_64bit) {
13456: $g=(($g<<32)>>32);
13457: }
13458: }
13459: return $g;
13460: }
13461: }
13462:
1.368 albertel 13463: sub latest_rnd_algorithm_id {
1.675 albertel 13464: return '64bit5';
1.366 albertel 13465: }
1.32 www 13466:
1.503 albertel 13467: sub get_rand_alg {
13468: my ($courseid)=@_;
1.790 albertel 13469: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13470: if ($courseid) {
1.620 albertel 13471: return $env{"course.$courseid.rndseed"};
1.503 albertel 13472: }
13473: return &latest_rnd_algorithm_id();
13474: }
13475:
1.562 albertel 13476: sub validCODE {
13477: my ($CODE)=@_;
13478: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13479: return 0;
13480: }
13481:
1.491 albertel 13482: sub getCODE {
1.620 albertel 13483: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13484: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13485: defined($Apache::lonhomework::parsing_a_task) ) &&
13486: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13487: return $Apache::lonhomework::history{'resource.CODE'};
13488: }
13489: return undef;
13490: }
1.1133 foxr 13491: #
13492: # Determines the random seed for a specific context:
13493: #
13494: # parameters:
13495: # symb - in course context the symb for the seed.
13496: # course_id - The course id of the form domain_coursenum.
13497: # domain - Domain for the user.
13498: # course - Course for the user.
13499: # cenv - environment of the course.
13500: #
13501: # NOTE:
13502: # All parameters are picked out of the environment if missing
13503: # or not defined.
13504: # If a symb cannot be determined the current time is used instead.
13505: #
13506: # For a given well defined symb, courside, domain, username,
13507: # and course environment, the seed is reproducible.
13508: #
1.31 www 13509: sub rndseed {
1.1133 foxr 13510: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13511: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13512: if (!defined($symb)) {
1.366 albertel 13513: unless ($symb=$wsymb) { return time; }
13514: }
1.1146 foxr 13515: if (!defined $courseid) {
13516: $courseid=$wcourseid;
13517: }
13518: if (!defined $domain) { $domain=$wdomain; }
13519: if (!defined $username) { $username=$wusername }
1.1133 foxr 13520:
13521: my $which;
13522: if (defined($cenv->{'rndseed'})) {
13523: $which = $cenv->{'rndseed'};
13524: } else {
13525: $which =&get_rand_alg($courseid);
13526: }
1.491 albertel 13527: if (defined(&getCODE())) {
1.1133 foxr 13528:
1.675 albertel 13529: if ($which eq '64bit5') {
13530: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13531: } elsif ($which eq '64bit4') {
1.575 albertel 13532: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13533: } else {
13534: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13535: }
1.675 albertel 13536: } elsif ($which eq '64bit5') {
13537: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13538: } elsif ($which eq '64bit4') {
13539: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13540: } elsif ($which eq '64bit3') {
13541: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13542: } elsif ($which eq '64bit2') {
13543: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13544: } elsif ($which eq '64bit') {
13545: return &rndseed_64bit($symb,$courseid,$domain,$username);
13546: }
13547: return &rndseed_32bit($symb,$courseid,$domain,$username);
13548: }
13549:
13550: sub rndseed_32bit {
13551: my ($symb,$courseid,$domain,$username)=@_;
13552: {
13553: use integer;
13554: my $symbchck=unpack("%32C*",$symb) << 27;
13555: my $symbseed=numval($symb) << 22;
13556: my $namechck=unpack("%32C*",$username) << 17;
13557: my $nameseed=numval($username) << 12;
13558: my $domainseed=unpack("%32C*",$domain) << 7;
13559: my $courseseed=unpack("%32C*",$courseid);
13560: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13561: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13562: #&logthis("rndseed :$num:$symb");
1.564 albertel 13563: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13564: return $num;
13565: }
13566: }
13567:
13568: sub rndseed_64bit {
13569: my ($symb,$courseid,$domain,$username)=@_;
13570: {
13571: use integer;
13572: my $symbchck=unpack("%32S*",$symb) << 21;
13573: my $symbseed=numval($symb) << 10;
13574: my $namechck=unpack("%32S*",$username);
13575:
13576: my $nameseed=numval($username) << 21;
13577: my $domainseed=unpack("%32S*",$domain) << 10;
13578: my $courseseed=unpack("%32S*",$courseid);
13579:
13580: my $num1=$symbchck+$symbseed+$namechck;
13581: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13582: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13583: #&logthis("rndseed :$num:$symb");
1.564 albertel 13584: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13585: return "$num1,$num2";
1.155 albertel 13586: }
1.366 albertel 13587: }
13588:
1.443 albertel 13589: sub rndseed_64bit2 {
13590: my ($symb,$courseid,$domain,$username)=@_;
13591: {
13592: use integer;
13593: # strings need to be an even # of cahracters long, it it is odd the
13594: # last characters gets thrown away
13595: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13596: my $symbseed=numval($symb) << 10;
13597: my $namechck=unpack("%32S*",$username.' ');
13598:
13599: my $nameseed=numval($username) << 21;
1.501 albertel 13600: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13601: my $courseseed=unpack("%32S*",$courseid.' ');
13602:
13603: my $num1=$symbchck+$symbseed+$namechck;
13604: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13605: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13606: #&logthis("rndseed :$num:$symb");
1.803 albertel 13607: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13608: return "$num1,$num2";
13609: }
13610: }
13611:
13612: sub rndseed_64bit3 {
13613: my ($symb,$courseid,$domain,$username)=@_;
13614: {
13615: use integer;
13616: # strings need to be an even # of cahracters long, it it is odd the
13617: # last characters gets thrown away
13618: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13619: my $symbseed=numval2($symb) << 10;
13620: my $namechck=unpack("%32S*",$username.' ');
13621:
13622: my $nameseed=numval2($username) << 21;
1.443 albertel 13623: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13624: my $courseseed=unpack("%32S*",$courseid.' ');
13625:
13626: my $num1=$symbchck+$symbseed+$namechck;
13627: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13628: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13629: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13630: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13631:
1.503 albertel 13632: return "$num1:$num2";
1.443 albertel 13633: }
13634: }
13635:
1.575 albertel 13636: sub rndseed_64bit4 {
13637: my ($symb,$courseid,$domain,$username)=@_;
13638: {
13639: use integer;
13640: # strings need to be an even # of cahracters long, it it is odd the
13641: # last characters gets thrown away
13642: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13643: my $symbseed=numval3($symb) << 10;
13644: my $namechck=unpack("%32S*",$username.' ');
13645:
13646: my $nameseed=numval3($username) << 21;
13647: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13648: my $courseseed=unpack("%32S*",$courseid.' ');
13649:
13650: my $num1=$symbchck+$symbseed+$namechck;
13651: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13652: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13653: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13654: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13655:
1.575 albertel 13656: return "$num1:$num2";
13657: }
13658: }
13659:
1.675 albertel 13660: sub rndseed_64bit5 {
13661: my ($symb,$courseid,$domain,$username)=@_;
13662: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13663: return "$num1:$num2";
13664: }
13665:
1.366 albertel 13666: sub rndseed_CODE_64bit {
13667: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13668: {
1.366 albertel 13669: use integer;
1.443 albertel 13670: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13671: my $symbseed=numval2($symb);
1.491 albertel 13672: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13673: my $CODEseed=numval(&getCODE());
1.443 albertel 13674: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13675: my $num1=$symbseed+$CODEchck;
13676: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13677: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13678: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13679: if ($_64bit) { $num1=(($num1<<32)>>32); }
13680: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13681: return "$num1:$num2";
1.366 albertel 13682: }
13683: }
13684:
1.575 albertel 13685: sub rndseed_CODE_64bit4 {
13686: my ($symb,$courseid,$domain,$username)=@_;
13687: {
13688: use integer;
13689: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13690: my $symbseed=numval3($symb);
13691: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13692: my $CODEseed=numval3(&getCODE());
13693: my $courseseed=unpack("%32S*",$courseid.' ');
13694: my $num1=$symbseed+$CODEchck;
13695: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13696: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13697: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13698: if ($_64bit) { $num1=(($num1<<32)>>32); }
13699: if ($_64bit) { $num2=(($num2<<32)>>32); }
13700: return "$num1:$num2";
13701: }
13702: }
13703:
1.675 albertel 13704: sub rndseed_CODE_64bit5 {
13705: my ($symb,$courseid,$domain,$username)=@_;
13706: my $code = &getCODE();
13707: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13708: return "$num1:$num2";
13709: }
13710:
1.366 albertel 13711: sub setup_random_from_rndseed {
13712: my ($rndseed)=@_;
1.503 albertel 13713: if ($rndseed =~/([,:])/) {
1.1262 raeburn 13714: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13715: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13716: &Math::Random::random_set_seed_from_phrase($rndseed);
13717: } else {
13718: &Math::Random::random_set_seed($num1,$num2);
13719: }
1.366 albertel 13720: } else {
13721: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13722: }
1.36 albertel 13723: }
13724:
1.474 albertel 13725: sub latest_receipt_algorithm_id {
1.835 albertel 13726: return 'receipt3';
1.474 albertel 13727: }
13728:
1.480 www 13729: sub recunique {
13730: my $fucourseid=shift;
13731: my $unique;
1.835 albertel 13732: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13733: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13734: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13735: } else {
13736: $unique=$perlvar{'lonReceipt'};
13737: }
13738: return unpack("%32C*",$unique);
13739: }
13740:
13741: sub recprefix {
13742: my $fucourseid=shift;
13743: my $prefix;
1.835 albertel 13744: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13745: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13746: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13747: } else {
13748: $prefix=$perlvar{'lonHostID'};
13749: }
13750: return unpack("%32C*",$prefix);
13751: }
13752:
1.76 www 13753: sub ireceipt {
1.474 albertel 13754: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13755:
13756: my $return =&recprefix($fucourseid).'-';
13757:
13758: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13759: $env{'request.state'} eq 'construct') {
13760: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13761: return $return;
13762: }
13763:
1.76 www 13764: my $cuname=unpack("%32C*",$funame);
13765: my $cudom=unpack("%32C*",$fudom);
13766: my $cucourseid=unpack("%32C*",$fucourseid);
13767: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13768: my $cunique=&recunique($fucourseid);
1.474 albertel 13769: my $cpart=unpack("%32S*",$part);
1.835 albertel 13770: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13771:
1.790 albertel 13772: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13773:
13774: $return.= ($cunique%$cuname+
13775: $cunique%$cudom+
13776: $cusymb%$cuname+
13777: $cusymb%$cudom+
13778: $cucourseid%$cuname+
13779: $cucourseid%$cudom+
13780: $cpart%$cuname+
13781: $cpart%$cudom);
13782: } else {
13783: $return.= ($cunique%$cuname+
13784: $cunique%$cudom+
13785: $cusymb%$cuname+
13786: $cusymb%$cudom+
13787: $cucourseid%$cuname+
13788: $cucourseid%$cudom);
13789: }
13790: return $return;
1.76 www 13791: }
13792:
13793: sub receipt {
1.474 albertel 13794: my ($part)=@_;
1.790 albertel 13795: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13796: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13797: }
1.260 ng 13798:
1.790 albertel 13799: sub whichuser {
13800: my ($passedsymb)=@_;
13801: my ($symb,$courseid,$domain,$name,$publicuser);
13802: if (defined($env{'form.grade_symb'})) {
13803: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13804: my $allowed=&allowed('vgr',$tmp_courseid);
13805: if (!$allowed &&
13806: exists($env{'request.course.sec'}) &&
13807: $env{'request.course.sec'} !~ /^\s*$/) {
13808: $allowed=&allowed('vgr',$tmp_courseid.
13809: '/'.$env{'request.course.sec'});
13810: }
13811: if ($allowed) {
13812: ($symb)=&get_env_multiple('form.grade_symb');
13813: $courseid=$tmp_courseid;
13814: ($domain)=&get_env_multiple('form.grade_domain');
13815: ($name)=&get_env_multiple('form.grade_username');
13816: return ($symb,$courseid,$domain,$name,$publicuser);
13817: }
13818: }
13819: if (!$passedsymb) {
13820: $symb=&symbread();
13821: } else {
13822: $symb=$passedsymb;
13823: }
13824: $courseid=$env{'request.course.id'};
13825: $domain=$env{'user.domain'};
13826: $name=$env{'user.name'};
13827: if ($name eq 'public' && $domain eq 'public') {
13828: if (!defined($env{'form.username'})) {
13829: $env{'form.username'}.=time.rand(10000000);
13830: }
13831: $name.=$env{'form.username'};
13832: }
13833: return ($symb,$courseid,$domain,$name,$publicuser);
13834:
13835: }
13836:
1.36 albertel 13837: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13838: # returns either the contents of the file or
13839: # -1 if the file doesn't exist
1.481 raeburn 13840: #
13841: # if the target is a file that was uploaded via DOCS,
13842: # a check will be made to see if a current copy exists on the local server,
13843: # if it does this will be served, otherwise a copy will be retrieved from
13844: # the home server for the course and stored in /home/httpd/html/userfiles on
13845: # the local server.
1.472 albertel 13846:
1.36 albertel 13847: sub getfile {
1.538 albertel 13848: my ($file) = @_;
1.609 banghart 13849: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13850: &repcopy($file);
13851: return &readfile($file);
13852: }
13853:
13854: sub repcopy_userfile {
13855: my ($file)=@_;
1.1142 raeburn 13856: my $londocroot = $perlvar{'lonDocRoot'};
13857: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13858: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13859: my ($cdom,$cnum,$filename) =
1.811 albertel 13860: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13861: my $uri="/uploaded/$cdom/$cnum/$filename";
13862: if (-e "$file") {
1.828 www 13863: # we already have a local copy, check it out
1.538 albertel 13864: my @fileinfo = stat($file);
1.828 www 13865: my $rtncode;
13866: my $info;
1.538 albertel 13867: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13868: if ($lwpresp ne 'ok') {
1.828 www 13869: # there is no such file anymore, even though we had a local copy
1.482 albertel 13870: if ($rtncode eq '404') {
1.538 albertel 13871: unlink($file);
1.482 albertel 13872: }
13873: return -1;
13874: }
13875: if ($info < $fileinfo[9]) {
1.828 www 13876: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13877: return 'ok';
1.828 www 13878: } else {
13879: # the file is outdated, get rid of it
13880: unlink($file);
1.482 albertel 13881: }
1.828 www 13882: }
13883: # one way or the other, at this point, we don't have the file
13884: # construct the correct path for the file
13885: my @parts = ($cdom,$cnum);
13886: if ($filename =~ m|^(.+)/[^/]+$|) {
13887: push @parts, split(/\//,$1);
13888: }
13889: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13890: foreach my $part (@parts) {
13891: $path .= '/'.$part;
13892: if (!-e $path) {
13893: mkdir($path,0770);
1.482 albertel 13894: }
13895: }
1.828 www 13896: # now the path exists for sure
13897: # get a user agent
13898: my $transferfile=$file.'.in.transfer';
13899: # FIXME: this should flock
13900: if (-e $transferfile) { return 'ok'; }
13901: my $request;
13902: $uri=~s/^\///;
1.980 raeburn 13903: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 13904: my $hostname = &hostname($homeserver);
1.980 raeburn 13905: my $protocol = $protocol{$homeserver};
13906: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13907: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 13908: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 13909: # did it work?
13910: if ($response->is_error()) {
13911: unlink($transferfile);
13912: &logthis("Userfile repcopy failed for $uri");
13913: return -1;
13914: }
13915: # worked, rename the transfer file
13916: rename($transferfile,$file);
1.607 raeburn 13917: return 'ok';
1.481 raeburn 13918: }
13919:
1.517 albertel 13920: sub tokenwrapper {
13921: my $uri=shift;
1.980 raeburn 13922: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13923: $uri=~s|^/||;
1.620 albertel 13924: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13925: my $token=$1;
1.552 albertel 13926: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13927: if ($udom && $uname && $file) {
13928: $file=~s|(\?\.*)*$||;
1.949 raeburn 13929: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13930: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 13931: my $hostname = &hostname($homeserver);
1.980 raeburn 13932: my $protocol = $protocol{$homeserver};
13933: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13934: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13935: (($uri=~/\?/)?'&':'?').'token='.$token.
13936: '&tokenissued='.$perlvar{'lonHostID'};
13937: } else {
13938: return '/adm/notfound.html';
13939: }
13940: }
13941:
1.828 www 13942: # call with reqtype HEAD: get last modification time
13943: # call with reqtype GET: get the file contents
13944: # Do not call this with reqtype GET for large files! It loads everything into memory
13945: #
1.481 raeburn 13946: sub getuploaded {
13947: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13948: $uri=~s/^\///;
1.980 raeburn 13949: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 13950: my $hostname = &hostname($homeserver);
1.980 raeburn 13951: my $protocol = $protocol{$homeserver};
13952: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13953: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13954: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 13955: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 13956: $$rtncode = $response->code;
1.482 albertel 13957: if (! $response->is_success()) {
13958: return 'failed';
13959: }
13960: if ($reqtype eq 'HEAD') {
1.486 www 13961: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13962: } elsif ($reqtype eq 'GET') {
13963: $$info = $response->content;
1.472 albertel 13964: }
1.482 albertel 13965: return 'ok';
1.36 albertel 13966: }
13967:
1.481 raeburn 13968: sub readfile {
13969: my $file = shift;
13970: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13971: my $fh;
1.1359 raeburn 13972: open($fh,"<",$file);
1.481 raeburn 13973: my $a='';
1.800 albertel 13974: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13975: return $a;
13976: }
13977:
1.36 albertel 13978: sub filelocation {
1.590 banghart 13979: my ($dir,$file) = @_;
13980: my $location;
13981: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13982:
13983: if ($file =~ m-^/adm/-) {
13984: $file=~s-^/adm/wrapper/-/-;
13985: $file=~s-^/adm/coursedocs/showdoc/-/-;
13986: }
1.882 albertel 13987:
1.1139 www 13988: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13989: $location = $file;
1.609 banghart 13990: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13991: my ($udom,$uname,$filename)=
1.811 albertel 13992: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13993: my $home=&homeserver($uname,$udom);
13994: my $is_me=0;
13995: my @ids=¤t_machine_ids();
13996: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13997: if ($is_me) {
1.1117 foxr 13998: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13999: } else {
14000: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14001: $udom.'/'.$uname.'/'.$filename;
14002: }
1.882 albertel 14003: } elsif ($file =~ m-^/adm/-) {
14004: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14005: } else {
14006: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14007: $file=~s:^/(res|priv)/:/:;
14008: my $space=$1;
1.590 banghart 14009: if ( !( $file =~ m:^/:) ) {
14010: $location = $dir. '/'.$file;
14011: } else {
1.1142 raeburn 14012: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14013: }
1.59 albertel 14014: }
1.590 banghart 14015: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14016: while ($location=~m{/\.\./}) {
14017: if ($location =~ m{/[^/]+/\.\./}) {
14018: $location=~ s{/[^/]+/\.\./}{/}g;
14019: } else {
14020: $location=~ s{/\.\./}{/}g;
14021: }
14022: } #remove dir/..
1.590 banghart 14023: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14024: return $location;
1.46 www 14025: }
1.36 albertel 14026:
1.46 www 14027: sub hreflocation {
14028: my ($dir,$file)=@_;
1.980 raeburn 14029: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14030: $file=filelocation($dir,$file);
1.700 albertel 14031: } elsif ($file=~m-^/adm/-) {
14032: $file=~s-^/adm/wrapper/-/-;
14033: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14034: }
14035: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14036: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14037: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14038: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14039: {/uploaded/$1/$2/}x;
1.46 www 14040: }
1.913 albertel 14041: if ($file=~ m{^/userfiles/}) {
14042: $file =~ s{^/userfiles/}{/uploaded/};
14043: }
1.462 albertel 14044: return $file;
1.465 albertel 14045: }
14046:
1.1139 www 14047:
14048:
14049:
14050:
1.465 albertel 14051: sub current_machine_domains {
1.853 albertel 14052: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14053: }
14054:
14055: sub machine_domains {
14056: my ($hostname) = @_;
1.465 albertel 14057: my @domains;
1.838 albertel 14058: my %hostname = &all_hostnames();
1.465 albertel 14059: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14060: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14061: if ($hostname eq $name) {
1.844 albertel 14062: push(@domains,&host_domain($id));
1.465 albertel 14063: }
14064: }
14065: return @domains;
14066: }
14067:
14068: sub current_machine_ids {
1.853 albertel 14069: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14070: }
14071:
14072: sub machine_ids {
14073: my ($hostname) = @_;
14074: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14075: my @ids;
1.888 albertel 14076: my %name_to_host = &all_names();
1.889 albertel 14077: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14078: return @{ $name_to_host{$hostname} };
14079: }
14080: return;
1.31 www 14081: }
14082:
1.824 raeburn 14083: sub additional_machine_domains {
14084: my @domains;
1.1359 raeburn 14085: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 14086: while( my $line = <$fh>) {
14087: $line =~ s/\s//g;
14088: push(@domains,$line);
14089: }
14090: return @domains;
14091: }
14092:
14093: sub default_login_domain {
14094: my $domain = $perlvar{'lonDefDomain'};
14095: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14096: foreach my $posdom (¤t_machine_domains(),
14097: &additional_machine_domains()) {
14098: if (lc($posdom) eq lc($testdomain)) {
14099: $domain=$posdom;
14100: last;
14101: }
14102: }
14103: return $domain;
14104: }
14105:
1.1414 raeburn 14106: sub shared_institution {
14107: my ($dom) = @_;
14108: my $same_intdom;
14109: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14110: if ($hostintdom ne '') {
14111: my %iphost = &get_iphost();
14112: my $primary_id = &domain($dom,'primary');
14113: my $primary_ip = &get_host_ip($primary_id);
14114: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14115: foreach my $id (@{$iphost{$primary_ip}}) {
14116: my $intdom = &internet_dom($id);
14117: if ($intdom eq $hostintdom) {
14118: $same_intdom = 1;
14119: last;
14120: }
14121: }
14122: }
14123: }
14124: return $same_intdom;
14125: }
14126:
1.1398 raeburn 14127: sub uses_sts {
14128: my ($ignore_cache) = @_;
14129: my $lonhost = $perlvar{'lonHostID'};
14130: my $hostname = &hostname($lonhost);
14131: my $sts_on;
14132: if ($protocol{$lonhost} eq 'https') {
14133: my $cachetime = 12*3600;
14134: if (!$ignore_cache) {
14135: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14136: if (defined($cached)) {
14137: return $sts_on;
14138: }
14139: }
14140: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14141: my $request=new HTTP::Request('HEAD',$url);
14142: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14143: if ($response->is_success) {
14144: my $has_sts = $response->header('Strict-Transport-Security');
14145: if ($has_sts eq '') {
14146: $sts_on = 0;
14147: } else {
14148: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14149: my $maxage = $1;
14150: if ($maxage) {
14151: $sts_on = 1;
14152: } else {
14153: $sts_on = 0;
14154: }
14155: } else {
14156: $sts_on = 0;
14157: }
14158: }
14159: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14160: }
14161: }
14162: return;
14163: }
14164:
1.31 www 14165: # ------------------------------------------------------------- Declutters URLs
14166:
14167: sub declutter {
14168: my $thisfn=shift;
1.569 albertel 14169: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 14170: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14171: $thisfn=~s{^/home/httpd/html}{};
14172: }
1.31 www 14173: $thisfn=~s/^\///;
1.697 albertel 14174: $thisfn=~s|^adm/wrapper/||;
14175: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14176: $thisfn=~s/^res\///;
1.1172 bisitz 14177: $thisfn=~s/^priv\///;
1.1032 raeburn 14178: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14179: $thisfn=~s/\?.+$//;
14180: }
1.268 www 14181: return $thisfn;
14182: }
14183:
14184: # ------------------------------------------------------------- Clutter up URLs
14185:
14186: sub clutter {
14187: my $thisfn='/'.&declutter(shift);
1.887 albertel 14188: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14189: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14190: $thisfn='/res'.$thisfn;
14191: }
1.1031 raeburn 14192: if ($thisfn !~m|^/adm|) {
14193: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14194: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14195: } else {
14196: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14197: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14198: if ($embstyle eq 'ssi'
14199: || ($embstyle eq 'hdn')
14200: || ($embstyle eq 'rat')
14201: || ($embstyle eq 'prv')
14202: || ($embstyle eq 'ign')) {
14203: #do nothing with these
14204: } elsif (($embstyle eq 'img')
1.695 albertel 14205: || ($embstyle eq 'emb')
14206: || ($embstyle eq 'wrp')) {
14207: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14208: } elsif ($embstyle eq 'unk'
14209: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14210: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14211: } else {
1.718 www 14212: # &logthis("Got a blank emb style");
1.695 albertel 14213: }
1.694 albertel 14214: }
1.1343 raeburn 14215: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14216: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14217: }
1.31 www 14218: return $thisfn;
1.12 www 14219: }
14220:
1.787 albertel 14221: sub clutter_with_no_wrapper {
14222: my $uri = &clutter(shift);
14223: if ($uri =~ m-^/adm/-) {
14224: $uri =~ s-^/adm/wrapper/-/-;
14225: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14226: }
14227: return $uri;
14228: }
14229:
1.557 albertel 14230: sub freeze_escape {
14231: my ($value)=@_;
14232: if (ref($value)) {
14233: $value=&nfreeze($value);
14234: return '__FROZEN__'.&escape($value);
14235: }
14236: return &escape($value);
14237: }
14238:
1.11 www 14239:
1.557 albertel 14240: sub thaw_unescape {
14241: my ($value)=@_;
14242: if ($value =~ /^__FROZEN__/) {
14243: substr($value,0,10,undef);
14244: $value=&unescape($value);
14245: return &thaw($value);
14246: }
14247: return &unescape($value);
14248: }
14249:
1.436 albertel 14250: sub correct_line_ends {
14251: my ($result)=@_;
14252: $$result =~s/\r\n/\n/mg;
14253: $$result =~s/\r/\n/mg;
1.415 albertel 14254: }
1.1 albertel 14255: # ================================================================ Main Program
14256:
1.184 www 14257: sub goodbye {
1.204 albertel 14258: &logthis("Starting Shut down");
1.443 albertel 14259: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14260: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14261: #converted
1.599 albertel 14262: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14263: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14264: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14265: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14266: #1.1 only
1.870 albertel 14267: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14268: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14269: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14270: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14271: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14272: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14273: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14274: &flushcourselogs();
14275: &logthis("Shutting down");
14276: }
14277:
1.852 albertel 14278: sub get_dns {
1.1210 raeburn 14279: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14280: if (!$ignore_cache) {
14281: my ($content,$cached)=
14282: &Apache::lonnet::is_cached_new('dns',$url);
14283: if ($cached) {
1.1210 raeburn 14284: &$func($content,$hashref);
1.869 albertel 14285: return;
14286: }
14287: }
14288:
14289: my %alldns;
1.1379 raeburn 14290: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14291: foreach my $dns (<$config>) {
14292: next if ($dns !~ /^\^(\S*)/x);
14293: my $line = $1;
14294: my ($host,$protocol) = split(/:/,$line);
14295: if ($protocol ne 'https') {
14296: $protocol = 'http';
14297: }
14298: $alldns{$host} = $protocol;
1.979 raeburn 14299: }
1.1379 raeburn 14300: close($config);
1.869 albertel 14301: }
14302: while (%alldns) {
1.1263 raeburn 14303: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 14304: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 14305: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 14306: delete($alldns{$dns});
1.852 albertel 14307: next if ($response->is_error());
1.1379 raeburn 14308: if ($url eq '/adm/dns/loncapaCRL') {
14309: return &$func($response);
14310: } else {
14311: my @content = split("\n",$response->content);
14312: unless ($nocache) {
14313: &do_cache_new('dns',$url,\@content,30*24*60*60);
14314: }
14315: &$func(\@content,$hashref);
14316: return;
14317: }
14318: }
14319: my $which = (split('/',$url,4))[3];
14320: if ($which eq 'loncapaCRL') {
14321: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14322: if (-e $diskfile) {
14323: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14324: } else {
14325: &logthis("unable to contact DNS, no on disk file $diskfile available");
14326: }
14327: } else {
14328: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14329: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14330: my @content = <$config>;
14331: close($config);
14332: &$func(\@content,$hashref);
14333: }
1.852 albertel 14334: }
1.1210 raeburn 14335: return;
14336: }
14337:
14338: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 14339: sub parse_dns_checksums_tab {
1.1210 raeburn 14340: my ($lines,$hashref) = @_;
1.1264 raeburn 14341: my $lonhost = $perlvar{'lonHostID'};
14342: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 14343: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 14344: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14345: my $webconfdir = '/etc/httpd/conf';
14346: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14347: $webconfdir = '/etc/apache2';
14348: } elsif ($distro =~ /^sles(\d+)$/) {
14349: if ($1 >= 10) {
14350: $webconfdir = '/etc/apache2';
14351: }
14352: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14353: if ($1 >= 10.0) {
14354: $webconfdir = '/etc/apache2';
14355: }
14356: }
1.1210 raeburn 14357: my ($release,$timestamp) = split(/\-/,$loncaparev);
14358: my (%chksum,%revnum);
14359: if (ref($lines) eq 'ARRAY') {
14360: chomp(@{$lines});
1.1238 raeburn 14361: my $version = shift(@{$lines});
14362: if ($version eq $release) {
1.1210 raeburn 14363: foreach my $line (@{$lines}) {
1.1238 raeburn 14364: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 14365: if ($file =~ m{^/etc/httpd/conf}) {
14366: if ($webconfdir eq '/etc/apache2') {
14367: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14368: }
14369: }
1.1238 raeburn 14370: $chksum{$file} = $shasum;
14371: $revnum{$file} = $version;
1.1210 raeburn 14372: }
14373: if (ref($hashref) eq 'HASH') {
14374: %{$hashref} = (
14375: sums => \%chksum,
14376: versions => \%revnum,
14377: );
14378: }
14379: }
14380: }
1.869 albertel 14381: return;
1.852 albertel 14382: }
1.1210 raeburn 14383:
14384: sub fetch_dns_checksums {
1.1238 raeburn 14385: my %checksums;
14386: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 14387: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 14388: my ($release,$timestamp) = split(/\-/,$loncaparev);
14389: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 14390: \%checksums);
1.1210 raeburn 14391: return \%checksums;
14392: }
14393:
1.1379 raeburn 14394: sub fetch_crl_pemfile {
14395: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14396: }
14397:
14398: sub save_crl_pem {
14399: my ($response) = @_;
1.1380 raeburn 14400: my ($msg,$hadchanges);
1.1379 raeburn 14401: if (ref($response)) {
14402: my $now = time;
14403: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14404: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14405: if (open(my $fh,'>',"$tmpcrl")) {
14406: print $fh $response->content;
14407: close($fh);
14408: if (-e $lonca) {
14409: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14410: my $check = <PIPE>;
14411: close(PIPE);
14412: chomp($check);
14413: if ($check eq 'verify OK') {
14414: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 14415: my $backup;
1.1379 raeburn 14416: if (-e $dest) {
1.1380 raeburn 14417: if (&File::Copy::move($dest,"$dest.bak")) {
14418: $backup = 'ok';
14419: }
1.1379 raeburn 14420: }
14421: if (&File::Copy::move($tmpcrl,$dest)) {
14422: $msg = 'ok';
1.1380 raeburn 14423: if ($backup) {
14424: my (%oldnums,%newnums);
14425: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14426: while (<PIPE>) {
14427: $oldnums{(split(/:/))[1]} = 1;
14428: }
14429: close(PIPE);
14430: }
14431: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14432: while(<PIPE>) {
14433: $newnums{(split(/:/))[1]} = 1;
14434: }
14435: close(PIPE);
14436: }
14437: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14438: unless (exists($oldnums{$key})) {
14439: $hadchanges = 1;
14440: last;
14441: }
14442: }
14443: unless ($hadchanges) {
14444: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14445: unless (exists($newnums{$key})) {
14446: $hadchanges = 1;
14447: last;
14448: }
14449: }
14450: }
14451: }
1.1379 raeburn 14452: }
14453: } else {
14454: unlink($tmpcrl);
14455: }
14456: } else {
14457: unlink($tmpcrl);
14458: }
14459: } else {
14460: unlink($tmpcrl);
14461: }
14462: }
14463: }
1.1380 raeburn 14464: return ($msg,$hadchanges);
1.1379 raeburn 14465: }
14466:
1.327 albertel 14467: # ------------------------------------------------------------ Read domain file
14468: {
1.852 albertel 14469: my $loaded;
1.846 albertel 14470: my %domain;
14471:
1.852 albertel 14472: sub parse_domain_tab {
14473: my ($lines) = @_;
14474: foreach my $line (@$lines) {
14475: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14476:
1.846 albertel 14477: chomp($line);
1.852 albertel 14478: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14479: my %this_domain;
14480: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14481: 'lang_def', 'city', 'longi', 'lati',
14482: 'primary') {
14483: $this_domain{$field} = shift(@elements);
14484: }
14485: $domain{$name} = \%this_domain;
1.852 albertel 14486: }
14487: }
1.864 albertel 14488:
14489: sub reset_domain_info {
14490: undef($loaded);
14491: undef(%domain);
14492: }
14493:
1.852 albertel 14494: sub load_domain_tab {
1.1293 raeburn 14495: my ($ignore_cache,$nocache) = @_;
14496: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14497: my $fh;
1.1359 raeburn 14498: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14499: my @lines = <$fh>;
14500: &parse_domain_tab(\@lines);
1.448 albertel 14501: }
1.852 albertel 14502: close($fh);
14503: $loaded = 1;
1.327 albertel 14504: }
1.846 albertel 14505:
14506: sub domain {
1.852 albertel 14507: &load_domain_tab() if (!$loaded);
14508:
1.846 albertel 14509: my ($name,$what) = @_;
14510: return if ( !exists($domain{$name}) );
14511:
14512: if (!$what) {
14513: return $domain{$name}{'description'};
14514: }
14515: return $domain{$name}{$what};
14516: }
1.974 raeburn 14517:
14518: sub domain_info {
14519: &load_domain_tab() if (!$loaded);
14520: return %domain;
14521: }
14522:
1.327 albertel 14523: }
14524:
14525:
1.1 albertel 14526: # ------------------------------------------------------------- Read hosts file
14527: {
1.838 albertel 14528: my %hostname;
1.844 albertel 14529: my %hostdom;
1.845 albertel 14530: my %libserv;
1.852 albertel 14531: my $loaded;
1.888 albertel 14532: my %name_to_host;
1.1074 raeburn 14533: my %internetdom;
1.1107 raeburn 14534: my %LC_dns_serv;
1.852 albertel 14535:
14536: sub parse_hosts_tab {
14537: my ($file) = @_;
14538: foreach my $configline (@$file) {
14539: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14540: chomp($configline);
14541: if ($configline =~ /^\^/) {
14542: if ($configline =~ /^\^([\w.\-]+)/) {
14543: $LC_dns_serv{$1} = 1;
14544: }
14545: next;
14546: }
1.1074 raeburn 14547: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14548: $name=~s/\s//g;
14549: if ($id && $domain && $role && $name) {
1.1351 raeburn 14550: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14551: my $curr = $hostname{$id};
14552: my $skip;
14553: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14554: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14555: $skip = 1;
14556: } else {
14557: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14558: }
14559: }
14560: unless ($skip) {
14561: push(@{$name_to_host{$name}},$id);
14562: }
14563: } else {
14564: push(@{$name_to_host{$name}},$id);
14565: }
1.852 albertel 14566: $hostname{$id}=$name;
14567: $hostdom{$id}=$domain;
14568: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14569: if (defined($protocol)) {
14570: if ($protocol eq 'https') {
14571: $protocol{$id} = $protocol;
14572: } else {
14573: $protocol{$id} = 'http';
14574: }
1.968 raeburn 14575: } else {
1.969 raeburn 14576: $protocol{$id} = 'http';
1.968 raeburn 14577: }
1.1074 raeburn 14578: if (defined($intdom)) {
14579: $internetdom{$id} = $intdom;
14580: }
1.852 albertel 14581: }
14582: }
14583: }
1.864 albertel 14584:
14585: sub reset_hosts_info {
1.897 albertel 14586: &purge_remembered();
1.864 albertel 14587: &reset_domain_info();
14588: &reset_hosts_ip_info();
1.1339 raeburn 14589: undef(%internetdom);
1.892 albertel 14590: undef(%name_to_host);
1.864 albertel 14591: undef(%hostname);
14592: undef(%hostdom);
14593: undef(%libserv);
14594: undef($loaded);
14595: }
1.1 albertel 14596:
1.852 albertel 14597: sub load_hosts_tab {
1.1293 raeburn 14598: my ($ignore_cache,$nocache) = @_;
14599: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 14600: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14601: my @config = <$config>;
14602: &parse_hosts_tab(\@config);
14603: close($config);
14604: $loaded=1;
1.1 albertel 14605: }
1.852 albertel 14606:
1.838 albertel 14607: sub hostname {
1.852 albertel 14608: &load_hosts_tab() if (!$loaded);
14609:
1.838 albertel 14610: my ($lonid) = @_;
14611: return $hostname{$lonid};
14612: }
1.845 albertel 14613:
1.838 albertel 14614: sub all_hostnames {
1.852 albertel 14615: &load_hosts_tab() if (!$loaded);
14616:
1.838 albertel 14617: return %hostname;
14618: }
1.845 albertel 14619:
1.888 albertel 14620: sub all_names {
1.1293 raeburn 14621: my ($ignore_cache,$nocache) = @_;
14622: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14623:
14624: return %name_to_host;
14625: }
14626:
1.974 raeburn 14627: sub all_host_domain {
14628: &load_hosts_tab() if (!$loaded);
14629: return %hostdom;
14630: }
14631:
1.1339 raeburn 14632: sub all_host_intdom {
14633: &load_hosts_tab() if (!$loaded);
14634: return %internetdom;
14635: }
14636:
1.845 albertel 14637: sub is_library {
1.852 albertel 14638: &load_hosts_tab() if (!$loaded);
14639:
1.845 albertel 14640: return exists($libserv{$_[0]});
14641: }
14642:
14643: sub all_library {
1.852 albertel 14644: &load_hosts_tab() if (!$loaded);
14645:
1.845 albertel 14646: return %libserv;
14647: }
14648:
1.1062 droeschl 14649: sub unique_library {
14650: #2x reverse removes all hostnames that appear more than once
14651: my %unique = reverse &all_library();
14652: return reverse %unique;
14653: }
14654:
1.841 albertel 14655: sub get_servers {
1.852 albertel 14656: &load_hosts_tab() if (!$loaded);
14657:
1.841 albertel 14658: my ($domain,$type) = @_;
14659: my %possible_hosts = ($type eq 'library') ? %libserv
14660: : %hostname;
14661: my %result;
1.842 albertel 14662: if (ref($domain) eq 'ARRAY') {
14663: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14664: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14665: $result{$host} = $hostname;
14666: }
14667: }
14668: } else {
14669: while ( my ($host,$hostname) = each(%possible_hosts)) {
14670: if ($hostdom{$host} eq $domain) {
14671: $result{$host} = $hostname;
14672: }
1.841 albertel 14673: }
14674: }
14675: return %result;
14676: }
1.845 albertel 14677:
1.1062 droeschl 14678: sub get_unique_servers {
14679: my %unique = reverse &get_servers(@_);
14680: return reverse %unique;
14681: }
14682:
1.844 albertel 14683: sub host_domain {
1.852 albertel 14684: &load_hosts_tab() if (!$loaded);
14685:
1.844 albertel 14686: my ($lonid) = @_;
14687: return $hostdom{$lonid};
14688: }
14689:
1.841 albertel 14690: sub all_domains {
1.852 albertel 14691: &load_hosts_tab() if (!$loaded);
14692:
1.841 albertel 14693: my %seen;
14694: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14695: return @uniq;
14696: }
1.1074 raeburn 14697:
14698: sub internet_dom {
14699: &load_hosts_tab() if (!$loaded);
14700:
14701: my ($lonid) = @_;
14702: return $internetdom{$lonid};
14703: }
1.1107 raeburn 14704:
14705: sub is_LC_dns {
14706: &load_hosts_tab() if (!$loaded);
14707:
14708: my ($hostname) = @_;
14709: return exists($LC_dns_serv{$hostname});
14710: }
14711:
1.1 albertel 14712: }
14713:
1.847 albertel 14714: {
14715: my %iphost;
1.856 albertel 14716: my %name_to_ip;
14717: my %lonid_to_ip;
1.869 albertel 14718:
1.847 albertel 14719: sub get_hosts_from_ip {
14720: my ($ip) = @_;
14721: my %iphosts = &get_iphost();
14722: if (ref($iphosts{$ip})) {
14723: return @{$iphosts{$ip}};
14724: }
14725: return;
1.839 albertel 14726: }
1.864 albertel 14727:
14728: sub reset_hosts_ip_info {
14729: undef(%iphost);
14730: undef(%name_to_ip);
14731: undef(%lonid_to_ip);
14732: }
1.856 albertel 14733:
14734: sub get_host_ip {
14735: my ($lonid) = @_;
14736: if (exists($lonid_to_ip{$lonid})) {
14737: return $lonid_to_ip{$lonid};
14738: }
14739: my $name=&hostname($lonid);
14740: my $ip = gethostbyname($name);
14741: return if (!$ip || length($ip) ne 4);
14742: $ip=inet_ntoa($ip);
14743: $name_to_ip{$name} = $ip;
14744: $lonid_to_ip{$lonid} = $ip;
14745: return $ip;
14746: }
1.847 albertel 14747:
14748: sub get_iphost {
1.1293 raeburn 14749: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14750:
1.869 albertel 14751: if (!$ignore_cache) {
14752: if (%iphost) {
14753: return %iphost;
14754: }
14755: my ($ip_info,$cached)=
14756: &Apache::lonnet::is_cached_new('iphost','iphost');
14757: if ($cached) {
14758: %iphost = %{$ip_info->[0]};
14759: %name_to_ip = %{$ip_info->[1]};
14760: %lonid_to_ip = %{$ip_info->[2]};
14761: return %iphost;
14762: }
14763: }
1.894 albertel 14764:
14765: # get yesterday's info for fallback
14766: my %old_name_to_ip;
14767: my ($ip_info,$cached)=
14768: &Apache::lonnet::is_cached_new('iphost','iphost');
14769: if ($cached) {
14770: %old_name_to_ip = %{$ip_info->[1]};
14771: }
14772:
1.1293 raeburn 14773: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14774: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14775: my $ip;
14776: if (!exists($name_to_ip{$name})) {
14777: $ip = gethostbyname($name);
14778: if (!$ip || length($ip) ne 4) {
1.894 albertel 14779: if (defined($old_name_to_ip{$name})) {
14780: $ip = $old_name_to_ip{$name};
14781: &logthis("Can't find $name defaulting to old $ip");
14782: } else {
14783: &logthis("Name $name no IP found");
14784: next;
14785: }
14786: } else {
14787: $ip=inet_ntoa($ip);
1.847 albertel 14788: }
14789: $name_to_ip{$name} = $ip;
14790: } else {
14791: $ip = $name_to_ip{$name};
1.653 albertel 14792: }
1.888 albertel 14793: foreach my $id (@{ $name_to_host{$name} }) {
14794: $lonid_to_ip{$id} = $ip;
14795: }
14796: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14797: }
1.1293 raeburn 14798: unless ($nocache) {
14799: &do_cache_new('iphost','iphost',
14800: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14801: 48*60*60);
14802: }
1.869 albertel 14803:
1.847 albertel 14804: return %iphost;
1.598 albertel 14805: }
14806:
1.992 raeburn 14807: #
14808: # Given a DNS returns the loncapa host name for that DNS
14809: #
14810: sub host_from_dns {
14811: my ($dns) = @_;
14812: my @hosts;
14813: my $ip;
14814:
1.993 raeburn 14815: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14816: $ip = $name_to_ip{$dns};
14817: }
14818: if (!$ip) {
14819: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14820: if (length($ip) == 4) {
14821: $ip = &IO::Socket::inet_ntoa($ip);
14822: }
14823: }
14824: if ($ip) {
14825: @hosts = get_hosts_from_ip($ip);
14826: return $hosts[0];
14827: }
14828: return undef;
1.986 foxr 14829: }
1.992 raeburn 14830:
1.1074 raeburn 14831: sub get_internet_names {
14832: my ($lonid) = @_;
14833: return if ($lonid eq '');
14834: my ($idnref,$cached)=
14835: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14836: if ($cached) {
14837: return $idnref;
14838: }
14839: my $ip = &get_host_ip($lonid);
14840: my @hosts = &get_hosts_from_ip($ip);
14841: my %iphost = &get_iphost();
14842: my (@idns,%seen);
14843: foreach my $id (@hosts) {
14844: my $dom = &host_domain($id);
14845: my $prim_id = &domain($dom,'primary');
14846: my $prim_ip = &get_host_ip($prim_id);
14847: next if ($seen{$prim_ip});
14848: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14849: foreach my $id (@{$iphost{$prim_ip}}) {
14850: my $intdom = &internet_dom($id);
14851: unless (grep(/^\Q$intdom\E$/,@idns)) {
14852: push(@idns,$intdom);
14853: }
14854: }
14855: }
14856: $seen{$prim_ip} = 1;
14857: }
1.1219 raeburn 14858: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14859: }
14860:
1.986 foxr 14861: }
14862:
1.1079 raeburn 14863: sub all_loncaparevs {
1.1249 raeburn 14864: 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 14865: }
14866:
1.1227 raeburn 14867: # ---------------------------------------------------------- Read loncaparev table
14868: {
14869: sub load_loncaparevs {
14870: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 14871: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 14872: while (my $configline=<$config>) {
14873: chomp($configline);
14874: my ($hostid,$loncaparev)=split(/:/,$configline);
14875: $loncaparevs{$hostid}=$loncaparev;
14876: }
14877: close($config);
14878: }
14879: }
14880: }
14881: }
14882:
14883: # ---------------------------------------------------------- Read serverhostID table
14884: {
14885: sub load_serverhomeIDs {
14886: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 14887: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 14888: while (my $configline=<$config>) {
14889: chomp($configline);
14890: my ($name,$id)=split(/:/,$configline);
14891: $serverhomeIDs{$name}=$id;
14892: }
14893: close($config);
14894: }
14895: }
14896: }
14897: }
14898:
14899:
1.862 albertel 14900: BEGIN {
14901:
14902: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14903: unless ($readit) {
14904: {
14905: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14906: %perlvar = (%perlvar,%{$configvars});
14907: }
14908:
14909:
1.1 albertel 14910: # ------------------------------------------------------ Read spare server file
14911: {
1.1359 raeburn 14912: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14913:
14914: while (my $configline=<$config>) {
14915: chomp($configline);
1.284 matthew 14916: if ($configline) {
1.784 albertel 14917: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14918: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14919: push(@{ $spareid{$type} }, $host);
1.1 albertel 14920: }
14921: }
1.448 albertel 14922: close($config);
1.1 albertel 14923: }
1.11 www 14924: # ------------------------------------------------------------ Read permissions
14925: {
1.1359 raeburn 14926: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14927:
14928: while (my $configline=<$config>) {
1.448 albertel 14929: chomp($configline);
14930: if ($configline) {
14931: my ($role,$perm)=split(/ /,$configline);
14932: if ($perm ne '') { $pr{$role}=$perm; }
14933: }
1.11 www 14934: }
1.448 albertel 14935: close($config);
1.11 www 14936: }
14937:
14938: # -------------------------------------------- Read plain texts for permissions
14939: {
1.1359 raeburn 14940: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14941:
14942: while (my $configline=<$config>) {
1.448 albertel 14943: chomp($configline);
14944: if ($configline) {
1.742 raeburn 14945: my ($short,@plain)=split(/:/,$configline);
14946: %{$prp{$short}} = ();
14947: if (@plain > 0) {
14948: $prp{$short}{'std'} = $plain[0];
14949: for (my $i=1; $i<@plain; $i++) {
14950: $prp{$short}{'alt'.$i} = $plain[$i];
14951: }
14952: }
1.448 albertel 14953: }
1.135 www 14954: }
1.448 albertel 14955: close($config);
1.135 www 14956: }
14957:
14958: # ---------------------------------------------------------- Read package table
14959: {
1.1359 raeburn 14960: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14961:
14962: while (my $configline=<$config>) {
1.483 albertel 14963: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14964: chomp($configline);
14965: my ($short,$plain)=split(/:/,$configline);
14966: my ($pack,$name)=split(/\&/,$short);
14967: if ($plain ne '') {
14968: $packagetab{$pack.'&'.$name.'&name'}=$name;
14969: $packagetab{$short}=$plain;
14970: }
1.11 www 14971: }
1.448 albertel 14972: close($config);
1.329 matthew 14973: }
14974:
1.1073 raeburn 14975: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 14976:
14977: &load_loncaparevs();
1.1073 raeburn 14978:
1.1074 raeburn 14979: # ---------------------------------------------------------- Read serverhostID table
14980:
1.1227 raeburn 14981: &load_serverhomeIDs();
14982:
14983: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14984: {
14985: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14986: if (-e $file) {
14987: my $parser = HTML::LCParser->new($file);
14988: while (my $token = $parser->get_token()) {
14989: if ($token->[0] eq 'S') {
14990: my $item = $token->[1];
14991: my $name = $token->[2]{'name'};
14992: my $value = $token->[2]{'value'};
1.1285 raeburn 14993: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 14994: my $namematch = $token->[2]{'namematch'};
14995: if ($item eq 'parameter') {
14996: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14997: my $release = $parser->get_text();
14998: $release =~ s/(^\s*|\s*$ )//gx;
14999: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15000: }
15001: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15002: my $release = $parser->get_text();
15003: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15004: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15005: }
15006: }
15007: }
15008: }
1.1073 raeburn 15009: }
15010:
1.1138 raeburn 15011: # ---------------------------------------------------------- Read managers table
15012: {
15013: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15014: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15015: while (my $configline=<$config>) {
15016: chomp($configline);
15017: next if ($configline =~ /^\#/);
15018: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15019: $managerstab{$configline} = 1;
15020: }
15021: }
15022: close($config);
15023: }
15024: }
15025: }
15026:
1.329 matthew 15027: # ------------- set up temporary directory
15028: {
1.1117 foxr 15029: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15030:
1.11 www 15031: }
15032:
1.1405 raeburn 15033: # ------------- set default texengine (domain default overrides this)
15034: {
15035: $deftex = LONCAPA::texengine();
15036: }
15037:
1.1416 raeburn 15038: # ------------- set default minimum length for passwords for internal auth users
15039: {
15040: $passwdmin = LONCAPA::passwd_min();
15041: }
15042:
1.794 albertel 15043: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15044: 'compress_threshold'=> 20_000,
15045: });
1.185 www 15046:
1.281 www 15047: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15048: $dumpcount=0;
1.958 www 15049: $locknum=0;
1.22 www 15050:
1.163 harris41 15051: &logtouch();
1.672 albertel 15052: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15053: $readit=1;
1.564 albertel 15054: {
15055: use integer;
15056: my $test=(2**32)+1;
1.568 albertel 15057: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15058: &logthis(" Detected 64bit platform ($_64bit)");
15059: }
1.195 www 15060: }
1.1 albertel 15061: }
1.179 www 15062:
1.1 albertel 15063: 1;
1.191 harris41 15064: __END__
15065:
1.243 albertel 15066: =pod
15067:
1.191 harris41 15068: =head1 NAME
15069:
1.243 albertel 15070: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15071:
15072: =head1 SYNOPSIS
15073:
1.243 albertel 15074: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15075:
15076: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15077:
1.243 albertel 15078: Common parameters:
15079:
15080: =over 4
15081:
15082: =item *
15083:
15084: $uname : an internal username (if $cname expecting a course Id specifically)
15085:
15086: =item *
15087:
15088: $udom : a domain (if $cdom expecting a course's domain specifically)
15089:
15090: =item *
15091:
15092: $symb : a resource instance identifier
15093:
15094: =item *
15095:
15096: $namespace : the name of a .db file that contains the data needed or
15097: being set.
15098:
15099: =back
15100:
1.394 bowersj2 15101: =head1 OVERVIEW
1.191 harris41 15102:
1.394 bowersj2 15103: lonnet provides subroutines which interact with the
15104: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15105: about classes, users, and resources.
1.243 albertel 15106:
15107: For many of these objects you can also use this to store data about
15108: them or modify them in various ways.
1.191 harris41 15109:
1.394 bowersj2 15110: =head2 Symbs
1.191 harris41 15111:
1.394 bowersj2 15112: To identify a specific instance of a resource, LON-CAPA uses symbols
15113: or "symbs"X<symb>. These identifiers are built from the URL of the
15114: map, the resource number of the resource in the map, and the URL of
15115: the resource itself. The latter is somewhat redundant, but might help
15116: if maps change.
15117:
15118: An example is
15119:
15120: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15121:
15122: The respective map entry is
15123:
15124: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15125: title="Problem 2">
15126: </resource>
15127:
15128: Symbs are used by the random number generator, as well as to store and
15129: restore data specific to a certain instance of for example a problem.
15130:
15131: =head2 Storing And Retrieving Data
15132:
15133: X<store()>X<cstore()>X<restore()>Three of the most important functions
15134: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15135: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15136: is is the non-critical message twin of cstore. These functions are for
15137: handlers to store a perl hash to a user's permanent data space in an
15138: easy manner, and to retrieve it again on another call. It is expected
15139: that a handler would use this once at the beginning to retrieve data,
15140: and then again once at the end to send only the new data back.
15141:
15142: The data is stored in the user's data directory on the user's
15143: homeserver under the ID of the course.
15144:
15145: The hash that is returned by restore will have all of the previous
15146: value for all of the elements of the hash.
15147:
15148: Example:
15149:
15150: #creating a hash
15151: my %hash;
15152: $hash{'foo'}='bar';
15153:
15154: #storing it
15155: &Apache::lonnet::cstore(\%hash);
15156:
15157: #changing a value
15158: $hash{'foo'}='notbar';
15159:
15160: #adding a new value
15161: $hash{'bar'}='foo';
15162: &Apache::lonnet::cstore(\%hash);
15163:
15164: #retrieving the hash
15165: my %history=&Apache::lonnet::restore();
15166:
15167: #print the hash
15168: foreach my $key (sort(keys(%history))) {
15169: print("\%history{$key} = $history{$key}");
15170: }
15171:
15172: Will print out:
1.191 harris41 15173:
1.394 bowersj2 15174: %history{1:foo} = bar
15175: %history{1:keys} = foo:timestamp
15176: %history{1:timestamp} = 990455579
15177: %history{2:bar} = foo
15178: %history{2:foo} = notbar
15179: %history{2:keys} = foo:bar:timestamp
15180: %history{2:timestamp} = 990455580
15181: %history{bar} = foo
15182: %history{foo} = notbar
15183: %history{timestamp} = 990455580
15184: %history{version} = 2
15185:
15186: Note that the special hash entries C<keys>, C<version> and
15187: C<timestamp> were added to the hash. C<version> will be equal to the
15188: total number of versions of the data that have been stored. The
15189: C<timestamp> attribute will be the UNIX time the hash was
15190: stored. C<keys> is available in every historical section to list which
15191: keys were added or changed at a specific historical revision of a
15192: hash.
15193:
15194: B<Warning>: do not store the hash that restore returns directly. This
15195: will cause a mess since it will restore the historical keys as if the
15196: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15197:
1.394 bowersj2 15198: Calling convention:
1.191 harris41 15199:
1.1225 raeburn 15200: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15201: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15202:
1.394 bowersj2 15203: For more detailed information, see lonnet specific documentation.
1.191 harris41 15204:
1.394 bowersj2 15205: =head1 RETURN MESSAGES
1.191 harris41 15206:
1.394 bowersj2 15207: =over 4
1.191 harris41 15208:
1.394 bowersj2 15209: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15210:
1.394 bowersj2 15211: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15212: when the connection is brought back up
1.191 harris41 15213:
1.394 bowersj2 15214: =item * B<con_failed>: unable to contact remote host and unable to save message
15215: for later delivery
1.191 harris41 15216:
1.967 bisitz 15217: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15218:
1.394 bowersj2 15219: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15220: that was requested
1.191 harris41 15221:
1.243 albertel 15222: =back
1.191 harris41 15223:
1.243 albertel 15224: =head1 PUBLIC SUBROUTINES
1.191 harris41 15225:
1.243 albertel 15226: =head2 Session Environment Functions
1.191 harris41 15227:
1.243 albertel 15228: =over 4
1.191 harris41 15229:
1.394 bowersj2 15230: =item *
15231: X<appenv()>
1.949 raeburn 15232: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15233: the user envirnoment file, and will be restored for each access this
1.620 albertel 15234: user makes during this session, also modifies the %env for the current
1.949 raeburn 15235: process. Optional rolesarrayref - if defined contains a reference to an array
15236: of roles which are exempt from the restriction on modifying user.role entries
15237: in the user's environment.db and in %env.
1.191 harris41 15238:
15239: =item *
1.394 bowersj2 15240: X<delenv()>
1.987 raeburn 15241: B<delenv($delthis,$regexp)>: removes all items from the session
15242: environment file that begin with $delthis. If the
15243: optional second arg - $regexp - is true, $delthis is treated as a
15244: regular expression, otherwise \Q$delthis\E is used.
15245: The values are also deleted from the current processes %env.
1.191 harris41 15246:
1.795 albertel 15247: =item * get_env_multiple($name)
15248:
15249: gets $name from the %env hash, it seemlessly handles the cases where multiple
15250: values may be defined and end up as an array ref.
15251:
15252: returns an array of values
15253:
1.243 albertel 15254: =back
15255:
15256: =head2 User Information
1.191 harris41 15257:
1.243 albertel 15258: =over 4
1.191 harris41 15259:
15260: =item *
1.394 bowersj2 15261: X<queryauthenticate()>
15262: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15263: authentication scheme
15264:
15265: =item *
1.394 bowersj2 15266: X<authenticate()>
1.1073 raeburn 15267: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15268: authenticate user from domain's lib servers (first use the current
15269: one). C<$upass> should be the users password.
1.1073 raeburn 15270: $checkdefauth is optional (value is 1 if a check should be made to
15271: authenticate user using default authentication method, and allow
15272: account creation if username does not have account in the domain).
15273: $clientcancheckhost is optional (value is 1 if checking whether the
15274: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15275:
15276: =item *
1.394 bowersj2 15277: X<homeserver()>
15278: B<homeserver($uname,$udom)>: find the server which has
15279: the user's directory and files (there must be only one), this caches
15280: the answer, and also caches if there is a borken connection.
1.191 harris41 15281:
15282: =item *
1.394 bowersj2 15283: X<idget()>
1.1300 raeburn 15284: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15285: a list of student/employee IDs or clicker IDs
15286: (student/employee IDs are a unique resource in a domain, there must be
15287: only 1 ID per username, and only 1 username per ID in a specific domain).
15288: clickerIDs are not necessarily unique, as students might share clickers.
15289: (returns hash: id=>name,id=>name)
1.191 harris41 15290:
15291: =item *
1.394 bowersj2 15292: X<idrget()>
15293: B<idrget($udom,@unames)>: find the IDs behind a list of
15294: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15295:
15296: =item *
1.394 bowersj2 15297: X<idput()>
1.1300 raeburn 15298: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15299: names and associated student/employee IDs or clicker IDs.
15300:
15301: =item *
15302: X<iddel()>
15303: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15304: student/employee ID or clicker ID username look-ups from domain.
15305: The homeserver ($uhome) and namespace ($namespace) are optional.
15306: If no $uhome is provided, it will be determined usig &homeserver()
15307: for each user. If no $namespace is provided, the default is ids.
15308:
15309: =item *
15310: X<updateclickers()>
15311: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15312: clicker ID-to-username look-ups in clickers.db on library server.
15313: Permitted actions are add or del (i.e., add or delete). The
15314: clickers.db contains clickerID as keys (escaped), and each corresponding
15315: value is an escaped comma-separated list of usernames (for whom the
15316: library server is the homeserver), who registered that particular ID.
15317: If $critical is true, the update will be sent via &critical, otherwise
15318: &reply() will be used.
1.191 harris41 15319:
15320: =item *
1.394 bowersj2 15321: X<rolesinit()>
1.1169 droeschl 15322: B<rolesinit($udom,$username)>: get user privileges.
15323: returns user role, first access and timer interval hashes
1.243 albertel 15324:
15325: =item *
1.1171 droeschl 15326: X<privileged()>
15327: B<privileged($username,$domain)>: returns a true if user has a
15328: privileged and active role (i.e. su or dc), false otherwise.
15329:
15330: =item *
1.551 albertel 15331: X<getsection()>
15332: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15333: course $cname, return section name/number or '' for "not in course"
15334: and '-1' for "no section"
15335:
15336: =item *
1.394 bowersj2 15337: X<userenvironment()>
15338: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15339: passed in @what from the requested user's environment, returns a hash
15340:
1.858 raeburn 15341: =item *
15342: X<userlog_query()>
1.859 albertel 15343: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15344: activity.log file. %filters defines filters applied when parsing the
15345: log file. These can be start or end timestamps, or the type of action
15346: - log to look for Login or Logout events, check for Checkin or
15347: Checkout, role for role selection. The response is in the form
15348: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15349: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15350:
1.243 albertel 15351: =back
15352:
15353: =head2 User Roles
15354:
15355: =over 4
15356:
15357: =item *
15358:
1.1284 raeburn 15359: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15360: returns codes for allowed actions.
15361:
15362: The first argument is required, all others are optional.
15363:
15364: $priv is the privilege being checked.
15365: $uri contains additional information about what is being checked for access (e.g.,
15366: URL, course ID etc.).
15367: $symb is the unique resource instance identifier in a course; if needed,
15368: but not provided, it will be retrieved via a call to &symbread().
15369: $role is the role for which a priv is being checked (only used if priv is evb).
15370: $clientip is the user's IP address (only used when checking for access to portfolio
15371: files).
15372: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15373: prevents recursive calls to &allowed.
15374:
1.243 albertel 15375: F: full access
15376: U,I,K: authentication modes (cxx only)
15377: '': forbidden
15378: 1: user needs to choose course
15379: 2: browse allowed
1.766 albertel 15380: A: passphrase authentication needed
1.1284 raeburn 15381: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 15382: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15383:
15384: =item *
15385:
1.1192 raeburn 15386: constructaccess($url,$setpriv) : check for access to construction space URL
15387:
15388: See if the owner domain and name in the URL match those in the
15389: expected environment. If so, return three element list
15390: ($ownername,$ownerdomain,$ownerhome).
15391:
15392: Otherwise return the null string.
15393:
15394: If second argument 'setpriv' is true, it assigns the privileges,
15395: and returns the same three element list, unless the owner has
15396: blocked "ad hoc" Domain Coordinator access to the Author Space,
15397: in which case the null string is returned.
15398:
15399: =item *
15400:
1.1326 raeburn 15401: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15402: define a custom role rolename set privileges in format of lonTabs/roles.tab
15403: for system, domain, and course level. $uname and $udom are optional (current
15404: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15405:
15406: =item *
15407:
1.988 raeburn 15408: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15409: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15410: $type is Course (default) or Community.
1.988 raeburn 15411: If $forcedefault evaluates to true, text returned will be default
15412: text for $type. Otherwise, if this is a course, the text returned
15413: will be a custom name for the role (if defined in the course's
15414: environment). If no custom name is defined the default is returned.
15415:
1.832 raeburn 15416: =item *
15417:
1.1219 raeburn 15418: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15419: All arguments are optional. Returns a hash of a roles, either for
15420: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15421: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15422: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15423: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15424: For each key, value is set to colon-separated start and end times for
15425: the role. If no username and domain are specified, will default to
1.934 raeburn 15426: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15427: of role statuses (active, future or previous), roles
15428: (e.g., cc,in, st etc.) and domains of the roles which can be used
15429: to restrict the list of roles reported. If no array ref is
15430: provided for types, will default to return only active roles.
1.834 albertel 15431:
1.1195 raeburn 15432: =item *
15433:
15434: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 15435: user: $uname:$udom has a role in the course: $cdom_$cnum.
15436:
15437: Additional optional arguments are: $type (if role checking is to be restricted
15438: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 15439: available roles) or future (roles available in the future), and
15440: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 15441: have active Domain Coordinator role in course's domain or in additional
15442: domains (specified in 'Domains to check for privileged users' in course
15443: environment -- set via: Course Settings -> Classlists and staff listing).
15444:
15445: =item *
15446:
15447: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15448: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15449: $possdomains and $possroles are optional array refs -- to domains to check and
15450: roles to check. If $possdomains is not specified, a dump will be done of the
15451: users' roles.db to check for a dc or su role in any domain. This can be
15452: time consuming if &privileged is called repeatedly (e.g., when displaying a
15453: classlist), so in such cases, supplying a $possdomains array is preferred, as
15454: this then allows &privileged_by_domain() to be used, which caches the identity
15455: of privileged users, eliminating the need for repeated calls to &dump().
15456:
15457: =item *
15458:
15459: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15460: where the outer hash keys are domains specified in the $possdomains array ref,
15461: next inner hash keys are privileged roles specified in the $roles array ref,
15462: and the innermost hash contains key = value pairs for username:domain = end:start
15463: for active or future "privileged" users with that role in that domain. To avoid
15464: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15465: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 15466:
1.243 albertel 15467: =back
15468:
15469: =head2 User Modification
15470:
15471: =over 4
15472:
15473: =item *
15474:
1.957 raeburn 15475: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15476: user for the level given by URL. Optional start and end dates (leave empty
15477: string or zero for "no date")
1.191 harris41 15478:
15479: =item *
15480:
1.243 albertel 15481: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15482: change a users, password, possible return values are: ok,
15483: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15484: refused
1.191 harris41 15485:
15486: =item *
15487:
1.243 albertel 15488: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15489:
15490: =item *
15491:
1.1058 raeburn 15492: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15493: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15494:
15495: will update user information (firstname,middlename,lastname,generation,
15496: permanentemail), and if forceid is true, student/employee ID also.
15497: A user's institutional affiliation(s) can also be updated.
15498: User information fields will not be overwritten with empty entries
15499: unless the field is included in the $candelete array reference.
15500: This array is included when a single user is modified via "Manage Users",
15501: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15502:
15503: =item *
15504:
1.286 matthew 15505: modifystudent
15506:
1.957 raeburn 15507: modify a student's enrollment and identification information.
1.1235 raeburn 15508: The course id is resolved based on the current user's environment.
15509: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15510: associated with a course.
15511:
1.297 matthew 15512: This call is essentially a wrapper for lonnet::modifyuser and
15513: lonnet::modify_student_enrollment
1.286 matthew 15514:
15515: Inputs:
15516:
15517: =over 4
15518:
1.957 raeburn 15519: =item B<$udom> Student's loncapa domain
1.286 matthew 15520:
1.957 raeburn 15521: =item B<$uname> Student's loncapa login name
1.286 matthew 15522:
1.964 bisitz 15523: =item B<$uid> Student/Employee ID
1.286 matthew 15524:
1.957 raeburn 15525: =item B<$umode> Student's authentication mode
1.286 matthew 15526:
1.957 raeburn 15527: =item B<$upass> Student's password
1.286 matthew 15528:
1.957 raeburn 15529: =item B<$first> Student's first name
1.286 matthew 15530:
1.957 raeburn 15531: =item B<$middle> Student's middle name
1.286 matthew 15532:
1.957 raeburn 15533: =item B<$last> Student's last name
1.286 matthew 15534:
1.957 raeburn 15535: =item B<$gene> Student's generation
1.286 matthew 15536:
1.957 raeburn 15537: =item B<$usec> Student's section in course
1.286 matthew 15538:
15539: =item B<$end> Unix time of the roles expiration
15540:
15541: =item B<$start> Unix time of the roles start date
15542:
15543: =item B<$forceid> If defined, allow $uid to be changed
15544:
15545: =item B<$desiredhome> server to use as home server for student
15546:
1.957 raeburn 15547: =item B<$email> Student's permanent e-mail address
15548:
15549: =item B<$type> Type of enrollment (auto or manual)
15550:
1.963 raeburn 15551: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15552:
15553: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15554:
1.963 raeburn 15555: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15556:
1.963 raeburn 15557: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15558:
1.1216 raeburn 15559: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15560:
15561: =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 15562:
1.286 matthew 15563: =back
1.297 matthew 15564:
15565: =item *
15566:
15567: modify_student_enrollment
15568:
1.1235 raeburn 15569: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15570: 'role.request.course' must be defined for this function to proceed.
15571:
15572: Inputs:
15573:
15574: =over 4
15575:
1.1235 raeburn 15576: =item $udom, student's domain
1.297 matthew 15577:
1.1235 raeburn 15578: =item $uname, student's name
1.297 matthew 15579:
1.1235 raeburn 15580: =item $uid, student's user id
1.297 matthew 15581:
1.1235 raeburn 15582: =item $first, student's first name
1.297 matthew 15583:
15584: =item $middle
15585:
15586: =item $last
15587:
15588: =item $gene
15589:
15590: =item $usec
15591:
15592: =item $end
15593:
15594: =item $start
15595:
1.957 raeburn 15596: =item $type
15597:
15598: =item $locktype
15599:
15600: =item $cid
15601:
15602: =item $selfenroll
15603:
15604: =item $context
15605:
1.1216 raeburn 15606: =item $credits, number of credits student will earn from this class
15607:
1.1314 raeburn 15608: =item $instsec, institutional course section code for student
15609:
1.297 matthew 15610: =back
15611:
1.191 harris41 15612:
15613: =item *
15614:
1.243 albertel 15615: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15616: custom role; give a custom role to a user for the level given by URL. Specify
15617: name and domain of role author, and role name
1.191 harris41 15618:
15619: =item *
15620:
1.243 albertel 15621: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15622:
15623: =item *
15624:
1.243 albertel 15625: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15626:
15627: =back
15628:
15629: =head2 Course Infomation
15630:
15631: =over 4
1.191 harris41 15632:
15633: =item *
15634:
1.1118 foxr 15635: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15636: specified course id, including all environment settings for the
15637: course, the description of the course will be in the hash under the
15638: key 'description'
1.191 harris41 15639:
1.1118 foxr 15640: $options is an optional parameter that if supplied is a hash reference that controls
15641: what how this function works. It has the following key/values:
15642:
15643: =over 4
15644:
15645: =item freshen_cache
15646:
15647: If defined, and the environment cache for the course is valid, it is
15648: returned in the returned hash.
15649:
15650: =item one_time
15651:
15652: If defined, the last cache time is set to _now_
15653:
15654: =item user
15655:
15656: If defined, the supplied username is used instead of the current user.
15657:
15658:
15659: =back
15660:
1.191 harris41 15661: =item *
15662:
1.624 albertel 15663: resdata($name,$domain,$type,@which) : request for current parameter
15664: setting for a specific $type, where $type is either 'course' or 'user',
15665: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 15666: answers for 10 minutes.
1.243 albertel 15667:
1.877 foxr 15668: =item *
15669:
15670: get_courseresdata($courseid, $domain) : dump the entire course resource
15671: data base, returning a hash that is keyed by the resource name and has
15672: values that are the resource value. I believe that the timestamps and
15673: versions are also returned.
15674:
1.1236 raeburn 15675: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15676: supplemental content area. This routine caches the number of files for
15677: 10 minutes.
15678:
1.243 albertel 15679: =back
15680:
15681: =head2 Course Modification
15682:
15683: =over 4
1.191 harris41 15684:
15685: =item *
15686:
1.243 albertel 15687: writecoursepref($courseid,%prefs) : write preferences (environment
15688: database) for a course
1.191 harris41 15689:
15690: =item *
15691:
1.1011 raeburn 15692: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15693:
15694: =item *
15695:
1.1038 raeburn 15696: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15697:
1.1167 droeschl 15698: =item *
15699:
15700: is_course($courseid), is_course($cdom, $cnum)
15701:
15702: Accepts either a combined $courseid (in the form of domain_courseid) or the
15703: two component version $cdom, $cnum. It checks if the specified course exists.
15704:
15705: Returns:
15706: undef if the course doesn't exist, otherwise
15707: in scalar context the combined courseid.
15708: in list context the two components of the course identifier, domain and
15709: courseid.
15710:
1.243 albertel 15711: =back
15712:
1.1401 raeburn 15713: =head2 Bubblesheet Configuration
15714:
15715: =over 4
15716:
15717: =item *
15718:
15719: get_scantron_config($which)
15720:
15721: $which - the name of the configuration to parse from the file.
15722:
15723: Parses and returns the bubblesheet configuration line selected as a
15724: hash of configuration file fields.
15725:
15726:
15727: Returns:
15728: If the named configuration is not in the file, an empty
15729: hash is returned.
15730:
15731: a hash with the fields
15732: name - internal name for the this configuration setup
15733: description - text to display to operator that describes this config
15734: CODElocation - if 0 or the string 'none'
15735: - no CODE exists for this config
15736: if -1 || the string 'letter'
15737: - a CODE exists for this config and is
15738: a string of letters
15739: Unsupported value (but planned for future support)
15740: if a positive integer
15741: - The CODE exists as the first n items from
15742: the question section of the form
15743: if the string 'number'
15744: - The CODE exists for this config and is
15745: a string of numbers
15746: CODEstart - (only matter if a CODE exists) column in the line where
15747: the CODE starts
15748: CODElength - length of the CODE
15749: IDstart - column where the student/employee ID starts
15750: IDlength - length of the student/employee ID info
15751: Qstart - column where the information from the bubbled
15752: 'questions' start
15753: Qlength - number of columns comprising a single bubble line from
15754: the sheet. (usually either 1 or 10)
15755: Qon - either a single character representing the character used
15756: to signal a bubble was chosen in the positional setup, or
15757: the string 'letter' if the letter of the chosen bubble is
15758: in the final, or 'number' if a number representing the
15759: chosen bubble is in the file (1->A 0->J)
15760: Qoff - the character used to represent that a bubble was
15761: left blank
15762: PaperID - if the scanning process generates a unique number for each
15763: sheet scanned the column that this ID number starts in
15764: PaperIDlength - number of columns that comprise the unique ID number
15765: for the sheet of paper
15766: FirstName - column that the first name starts in
15767: FirstNameLength - number of columns that the first name spans
15768: LastName - column that the last name starts in
15769: LastNameLength - number of columns that the last name spans
15770: BubblesPerRow - number of bubbles available in each row used to
15771: bubble an answer. (If not specified, 10 assumed).
15772:
15773:
15774: =item *
15775:
15776: get_scantronformat_file($cdom)
15777:
15778: $cdom - the course's domain (optional); if not supplied, uses
15779: domain for current $env{'request.course.id'}.
15780:
15781: Returns an array containing lines from the scantron format file for
15782: the domain of the course.
15783:
15784: If a url for a custom.tab file is listed in domain's configuration.db,
15785: lines are from this file.
15786:
15787: Otherwise, if a default.tab has been published in RES space by the
15788: domainconfig user, lines are from this file.
15789:
15790: Otherwise, fall back to getting lines from the legacy file on the
15791: local server: /home/httpd/lonTabs/default_scantronformat.tab
15792:
15793: =back
15794:
1.243 albertel 15795: =head2 Resource Subroutines
15796:
15797: =over 4
1.191 harris41 15798:
15799: =item *
15800:
1.243 albertel 15801: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15802:
15803: =item *
15804:
1.243 albertel 15805: repcopy($filename) : subscribes to the requested file, and attempts to
15806: replicate from the owning library server, Might return
1.607 raeburn 15807: 'unavailable', 'not_found', 'forbidden', 'ok', or
15808: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15809: resource. Expects the local filesystem pathname
15810: (/home/httpd/html/res/....)
15811:
15812: =back
15813:
15814: =head2 Resource Information
15815:
15816: =over 4
1.191 harris41 15817:
15818: =item *
15819:
1.1228 raeburn 15820: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15821: and returns the value of a variety of different possible values,
15822: $varname should be a request string, and the other parameters can be
15823: used to specify who and what one is asking about. Ordinarily, $cid
15824: does not need to be specified, as it is retrived from
15825: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15826: within lonuserstate::loadmap() when initializing a course, before
15827: $env{'request.course.id'} has been set, so it needs to be provided
15828: in that one case.
1.243 albertel 15829:
15830: Possible values for $varname are environment.lastname (or other item
15831: from the envirnment hash), user.name (or someother aspect about the
15832: user), resource.0.maxtries (or some other part and parameter of a
15833: resource)
1.204 albertel 15834:
15835: =item *
15836:
1.243 albertel 15837: directcondval($number) : get current value of a condition; reads from a state
15838: string
1.204 albertel 15839:
15840: =item *
15841:
1.243 albertel 15842: condval($condidx) : value of condition index based on state
1.204 albertel 15843:
15844: =item *
15845:
1.1362 raeburn 15846: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 15847: resource's metadata, $what should be either a specific key, or either
15848: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 15849: packages that this resource currently uses, the last 3 arguments are
15850: only used internally for recursive metadata.
15851:
15852: the toolsymb is only used where the uri is for an external tool (for which
15853: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 15854:
1.1371 raeburn 15855: this function automatically caches all requests except any made recursively
15856: to retrieve a list of metadata keys for an imported library file ($liburi is
15857: defined).
1.191 harris41 15858:
15859: =item *
15860:
1.243 albertel 15861: metadata_query($query,$custom,$customshow) : make a metadata query against the
15862: network of library servers; returns file handle of where SQL and regex results
15863: will be stored for query
1.191 harris41 15864:
15865: =item *
15866:
1.1282 raeburn 15867: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15868: return symbolic list entry (all arguments optional).
15869:
15870: Args: filename is the filename (including path) for the file for which a symb
15871: is required; donotrecurse, if true will prevent calls to allowed() being made
15872: to check access status if more than one resource was found in the bighash
15873: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15874: a randompick); ignorecachednull, if true will prevent a symb of '' being
15875: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15876: cause possible symbs to be checked to determine if they are subject to content
15877: blocking, if so they will not be included as possible symbs; possibles is a
15878: ref to a hash, which, as a side effect, will be populated with all possible
15879: symbs (content blocking not tested).
15880:
1.243 albertel 15881: returns the data handle
1.191 harris41 15882:
15883: =item *
15884:
1.1190 raeburn 15885: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15886: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15887: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 15888: on failure, user must be in a course, as it assumes the existence of
15889: the course initial hash, and uses $env('request.course.id'}. The third
15890: arg is an optional reference to a scalar. If this arg is passed in the
15891: call to symbverify, it will be set to 1 if the symb has been set to be
15892: encrypted; otherwise it will be null.
1.191 harris41 15893:
15894: =item *
15895:
1.243 albertel 15896: symbclean($symb) : removes versions numbers from a symb, returns the
15897: cleaned symb
1.191 harris41 15898:
15899: =item *
15900:
1.243 albertel 15901: is_on_map($uri) : checks if the $uri is somewhere on the current
15902: course map, user must be in a course for it to work.
1.191 harris41 15903:
15904: =item *
15905:
1.243 albertel 15906: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15907:
15908: =item *
15909:
1.243 albertel 15910: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15911: a random seed, all arguments are optional, if they aren't sent it uses the
15912: environment to derive them. Note: if symb isn't sent and it can't get one
15913: from &symbread it will use the current time as its return value
1.191 harris41 15914:
15915: =item *
15916:
1.243 albertel 15917: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15918: unfakeable, receipt
1.191 harris41 15919:
15920: =item *
15921:
1.620 albertel 15922: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15923:
15924: =item *
15925:
1.243 albertel 15926: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15927:
15928: =item *
15929:
1.243 albertel 15930: 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 15931:
15932: =item *
15933:
1.243 albertel 15934: 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 15935:
15936: =item *
15937:
1.243 albertel 15938: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15939:
15940: =item *
15941:
1.243 albertel 15942: devalidate($symb) : devalidate temporary spreadsheet calculations,
15943: forcing spreadsheet to reevaluate the resource scores next time.
15944:
1.1195 raeburn 15945: =item *
15946:
1.1196 raeburn 15947: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15948: when viewing in course context.
1.1195 raeburn 15949:
1.1196 raeburn 15950: input: six args -- filename (decluttered), course number, course domain,
15951: url, symb (if registered) and group (if this is a
15952: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 15953:
1.1196 raeburn 15954: output: array of five scalars --
1.1195 raeburn 15955: $cfile -- url for file editing if editable on current server
15956: $home -- homeserver of resource (i.e., for author if published,
15957: or course if uploaded.).
15958: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 15959: $forceedit -- 1 if icon/link should be to go to edit mode
15960: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 15961:
15962: =item *
15963:
15964: is_course_upload($file,$cnum,$cdom)
15965:
15966: Used in course context to determine if current file was uploaded to
15967: the course (i.e., would be found in /userfiles/docs on the course's
15968: homeserver.
15969:
15970: input: 3 args -- filename (decluttered), course number and course domain.
15971: output: boolean -- 1 if file was uploaded.
15972:
1.243 albertel 15973: =back
15974:
15975: =head2 Storing/Retreiving Data
15976:
15977: =over 4
1.191 harris41 15978:
15979: =item *
15980:
1.1269 raeburn 15981: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15982: permanently for this url; hashref needs to be given and should be a \%hashname;
15983: the remaining args aren't required and if they aren't passed or are '' they will
15984: be derived from the env (with the exception of $laststore, which is an
15985: optional arg used when a user's submission is stored in grading).
15986: $laststore is $version=$timestamp, where $version is the most recent version
15987: number retrieved for the corresponding $symb in the $namespace db file, and
15988: $timestamp is the timestamp for that transaction (UNIX time).
15989: $laststore is currently only passed when cstore() is called by
15990: structuretags::finalize_storage().
1.191 harris41 15991:
15992: =item *
15993:
1.1269 raeburn 15994: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15995: but uses critical subroutine
1.191 harris41 15996:
15997: =item *
15998:
1.243 albertel 15999: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16000: all args are optional
1.191 harris41 16001:
16002: =item *
16003:
1.717 albertel 16004: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16005: dumps the complete (or key matching regexp) namespace into a hash
16006: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16007: normally &store()ed into
16008:
16009: $range should be either an integer '100' (give me the first 100
16010: matching records)
16011: or be two integers sperated by a - with no spaces
16012: '30-50' (give me the 30th through the 50th matching
16013: records)
16014:
16015:
16016: =item *
16017:
1.1269 raeburn 16018: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16019: replaces a &store() version of data with a replacement set of data
16020: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16021: reference. If $tolog is true, the transaction is logged in the courselog
16022: with an action=PUTSTORE.
1.717 albertel 16023:
16024: =item *
16025:
1.243 albertel 16026: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16027: works very similar to store/cstore, but all data is stored in a
16028: temporary location and can be reset using tmpreset, $storehash should
16029: be a hash reference, returns nothing on success
1.191 harris41 16030:
16031: =item *
16032:
1.243 albertel 16033: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16034: similar to restore, but all data is stored in a temporary location and
16035: can be reset using tmpreset. Returns a hash of values on success,
16036: error string otherwise.
1.191 harris41 16037:
16038: =item *
16039:
1.243 albertel 16040: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16041: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16042:
16043: =item *
16044:
1.243 albertel 16045: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16046: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16047:
16048: =item *
16049:
1.243 albertel 16050: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16051: namesp ($udom and $uname are optional)
1.191 harris41 16052:
16053: =item *
16054:
1.702 albertel 16055: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16056: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16057: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16058:
1.702 albertel 16059: $range should be either an integer '100' (give me the first 100
16060: matching records)
16061: or be two integers sperated by a - with no spaces
16062: '30-50' (give me the 30th through the 50th matching
16063: records)
1.449 matthew 16064: =item *
16065:
16066: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16067: $store can be a scalar, an array reference, or if the amount to be
16068: incremented is > 1, a hash reference.
16069:
16070: ($udom and $uname are optional)
1.191 harris41 16071:
16072: =item *
16073:
1.243 albertel 16074: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16075: ($udom and $uname are optional)
1.191 harris41 16076:
16077: =item *
16078:
1.243 albertel 16079: cput($namespace,$storehash,$udom,$uname) : critical put
16080: ($udom and $uname are optional)
1.191 harris41 16081:
16082: =item *
16083:
1.748 albertel 16084: newput($namespace,$storehash,$udom,$uname) :
16085:
16086: Attempts to store the items in the $storehash, but only if they don't
16087: currently exist, if this succeeds you can be certain that you have
16088: successfully created a new key value pair in the $namespace db.
16089:
16090:
16091: Args:
16092: $namespace: name of database to store values to
16093: $storehash: hashref to store to the db
16094: $udom: (optional) domain of user containing the db
16095: $uname: (optional) name of user caontaining the db
16096:
16097: Returns:
16098: 'ok' -> succeeded in storing all keys of $storehash
16099: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16100: least <key> already existed in the db (other
16101: requested keys may also already exist)
1.967 bisitz 16102: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16103: 'con_lost' -> unable to contact request server
16104: 'refused' -> action was not allowed by remote machine
16105:
16106:
16107: =item *
16108:
1.243 albertel 16109: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16110: reference filled in from namesp (encrypts the return communication)
16111: ($udom and $uname are optional)
1.191 harris41 16112:
16113: =item *
16114:
1.243 albertel 16115: log($udom,$name,$home,$message) : write to permanent log for user; use
16116: critical subroutine
16117:
1.806 raeburn 16118: =item *
16119:
1.860 raeburn 16120: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16121: array reference filled in from namespace found in domain level on either
16122: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16123:
16124: =item *
16125:
1.860 raeburn 16126: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16127: domain level either on specified domain server ($uhome) or primary domain
16128: server ($udom and $uhome are optional)
1.806 raeburn 16129:
1.943 raeburn 16130: =item *
16131:
1.1240 raeburn 16132: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16133: for: authentication, language, quotas, timezone, date locale, and portal URL in
16134: the target domain.
16135:
16136: May also include additional key => value pairs for the following groups:
16137:
16138: =over
16139:
16140: =item
16141: disk quotas (MB allocated by default to portfolios and authoring spaces).
16142:
16143: =over
16144:
16145: =item defaultquota, authorquota
16146:
16147: =back
16148:
16149: =item
16150: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16151: portfolio for users).
16152:
16153: =over
16154:
16155: =item
16156: aboutme, blog, webdav, portfolio
16157:
16158: =back
16159:
16160: =item
16161: requestcourses: ability to request courses, and how requests are processed.
16162:
16163: =over
16164:
16165: =item
1.1305 raeburn 16166: official, unofficial, community, textbook, placement
1.1240 raeburn 16167:
16168: =back
16169:
16170: =item
16171: inststatus: types of institutional affiliation, and order in which they are displayed.
16172:
16173: =over
16174:
16175: =item
1.1256 raeburn 16176: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 16177:
16178: =back
16179:
16180: =item
16181: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16182: for course's uploaded content.
16183:
16184: =over
16185:
16186: =item
1.1246 raeburn 16187: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16188: communityquota, textbookquota, placementquota
1.1240 raeburn 16189:
16190: =back
16191:
16192: =item
16193: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16194: on your servers.
16195:
16196: =over
16197:
16198: =item
16199: remotesessions, hostedsessions
16200:
16201: =back
16202:
16203: =back
16204:
16205: In cases where a domain coordinator has never used the "Set Domain Configuration"
16206: utility to create a configuration.db file on a domain's primary library server
16207: only the following domain defaults: auth_def, auth_arg_def, lang_def
16208: -- corresponding values are authentication type (internal, krb4, krb5,
16209: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16210: will be available. Values are retrieved from cache (if current), unless the
16211: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16212: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16213:
16214: Typical usage:
1.943 raeburn 16215:
1.1240 raeburn 16216: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16217:
1.243 albertel 16218: =back
16219:
16220: =head2 Network Status Functions
16221:
16222: =over 4
1.191 harris41 16223:
16224: =item *
16225:
1.1137 raeburn 16226: dirlist() : return directory list based on URI (first arg).
16227:
16228: Inputs: 1 required, 5 optional.
16229:
16230: =over
16231:
16232: =item
16233: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16234:
16235: =item
16236: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16237:
16238: =item
16239: $username - username of user/course to be listed. Extracted from $uri if absent.
16240:
16241: =item
16242: $getpropath - boolean: 1 if prepend path using &propath().
16243:
16244: =item
16245: $getuserdir - boolean: 1 if prepend path for "userfiles".
16246:
16247: =item
16248: $alternateRoot - path to prepend in place of path from $uri.
16249:
16250: =back
16251:
16252: Returns: Array of up to two items.
16253:
16254: =over
16255:
16256: a reference to an array of files/subdirectories
16257:
16258: =over
16259:
16260: Each element in the array of files/subdirectories is a & separated list of
16261: item name and the result of running stat on the item. If dirlist was requested
16262: for a file instead of a directory, the item name will be ''. For a directory
16263: listing, if the item is a metadata file, the element will end &N&M
16264: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16265: default copyright set (1).
16266:
16267: =back
16268:
16269: a scalar containing error condition (if encountered).
16270:
16271: =over
16272:
16273: =item
16274: no_host (no homeserver identified for $username:$domain).
16275:
16276: =item
16277: no_such_host (server contacted for listing not identified as valid host).
16278:
16279: =item
16280: con_lost (connection to remote server failed).
16281:
16282: =item
16283: refused (invalid $username:$domain received on lond side).
16284:
16285: =item
16286: no_such_dir (directory at specified path on lond side does not exist).
16287:
16288: =item
16289: empty (directory at specified path on lond side is empty).
16290:
16291: =over
16292:
16293: This is currently not encountered because the &ls3, &ls2,
16294: &ls (_handler) routines on the lond side do not filter out
16295: . and .. from a directory listing.
16296:
16297: =back
16298:
16299: =back
16300:
16301: =back
1.191 harris41 16302:
16303: =item *
16304:
1.243 albertel 16305: spareserver() : find server with least workload from spare.tab
16306:
1.986 foxr 16307:
16308: =item *
16309:
16310: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16311: if there is no corresponding loncapa host.
16312:
1.243 albertel 16313: =back
16314:
1.986 foxr 16315:
1.243 albertel 16316: =head2 Apache Request
16317:
16318: =over 4
1.191 harris41 16319:
16320: =item *
16321:
1.243 albertel 16322: ssi($url,%hash) : server side include, does a complete request cycle on url to
16323: localhost, posts hash
16324:
16325: =back
16326:
16327: =head2 Data to String to Data
16328:
16329: =over 4
1.191 harris41 16330:
16331: =item *
16332:
1.243 albertel 16333: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16334: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16335:
16336: =item *
16337:
1.243 albertel 16338: hashref2str($hashref) : convert a hashref into a string complete with
16339: escaping and '=' and '&' separators, supports elements that are
16340: arrayrefs and hashrefs
1.191 harris41 16341:
16342: =item *
16343:
1.243 albertel 16344: arrayref2str($arrayref) : convert an arrayref into a string complete
16345: with escaping and '&' separators, supports elements that are arrayrefs
16346: and hashrefs
1.191 harris41 16347:
16348: =item *
16349:
1.243 albertel 16350: str2hash($string) : convert string to hash using unescaping and
16351: splitting on '=' and '&', supports elements that are arrayrefs and
16352: hashrefs
1.191 harris41 16353:
16354: =item *
16355:
1.243 albertel 16356: str2array($string) : convert string to hash using unescaping and
16357: splitting on '&', supports elements that are arrayrefs and hashrefs
16358:
16359: =back
16360:
16361: =head2 Logging Routines
16362:
16363:
16364: These routines allow one to make log messages in the lonnet.log and
16365: lonnet.perm logfiles.
1.191 harris41 16366:
1.1119 foxr 16367: =over 4
16368:
1.191 harris41 16369: =item *
16370:
1.243 albertel 16371: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16372:
16373: =item *
16374:
1.243 albertel 16375: logthis() : append message to the normal lonnet.log file, it gets
16376: preiodically rolled over and deleted.
1.191 harris41 16377:
16378: =item *
16379:
1.243 albertel 16380: logperm() : append a permanent message to lonnet.perm.log, this log
16381: file never gets deleted by any automated portion of the system, only
16382: messages of critical importance should go in here.
16383:
1.1119 foxr 16384:
1.243 albertel 16385: =back
16386:
16387: =head2 General File Helper Routines
16388:
16389: =over 4
1.191 harris41 16390:
16391: =item *
16392:
1.481 raeburn 16393: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16394: (a) files in /uploaded
16395: (i) If a local copy of the file exists -
16396: compares modification date of local copy with last-modified date for
16397: definitive version stored on home server for course. If local copy is
16398: stale, requests a new version from the home server and stores it.
16399: If the original has been removed from the home server, then local copy
16400: is unlinked.
16401: (ii) If local copy does not exist -
16402: requests the file from the home server and stores it.
16403:
16404: If $caller is 'uploadrep':
16405: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16406: for request for files originally uploaded via DOCS.
16407: - returns 'ok' if fresh local copy now available, -1 otherwise.
16408:
16409: Otherwise:
16410: This indicates a call from the content generation phase of the request.
16411: - returns the entire contents of the file or -1.
16412:
16413: (b) files in /res
16414: - returns the entire contents of a file or -1;
16415: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16416:
1.712 albertel 16417:
16418: =item *
16419:
16420: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16421: reference
16422:
16423: returns either a stat() list of data about the file or an empty list
16424: if the file doesn't exist or couldn't find out about it (connection
16425: problems or user unknown)
16426:
1.191 harris41 16427: =item *
16428:
1.243 albertel 16429: filelocation($dir,$file) : returns file system location of a file
16430: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16431: directory that relative $file lookups are to looked in ($dir of /a/dir
16432: and a file of ../bob will become /a/bob)
1.191 harris41 16433:
16434: =item *
16435:
16436: hreflocation($dir,$file) : returns file system location or a URL; same as
16437: filelocation except for hrefs
16438:
16439: =item *
16440:
1.1261 raeburn 16441: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16442: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16443:
1.243 albertel 16444: =back
16445:
1.608 albertel 16446: =head2 Usererfile file routines (/uploaded*)
16447:
16448: =over 4
16449:
16450: =item *
16451:
16452: userfileupload(): main rotine for putting a file in a user or course's
16453: filespace, arguments are,
16454:
1.620 albertel 16455: formname - required - this is the name of the element in $env where the
1.608 albertel 16456: filename, and the contents of the file to create/modifed exist
1.620 albertel 16457: the filename is in $env{'form.'.$formname.'.filename'} and the
16458: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16459: context - if coursedoc, store the file in the course of the active role
16460: of the current user;
16461: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16462: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16463: subdir - required - subdirectory to put the file in under ../userfiles/
16464: if undefined, it will be placed in "unknown"
16465:
16466: (This routine calls clean_filename() to remove any dangerous
16467: characters from the filename, and then calls finuserfileupload() to
16468: complete the transaction)
16469:
16470: returns either the url of the uploaded file (/uploaded/....) if successful
16471: and /adm/notfound.html if unsuccessful
16472:
16473: =item *
16474:
16475: clean_filename(): routine for cleaing a filename up for storage in
16476: userfile space, argument is:
16477:
16478: filename - proposed filename
16479:
16480: returns: the new clean filename
16481:
16482: =item *
16483:
1.1090 raeburn 16484: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16485: userspace, probably shouldn't be called directly
16486:
16487: docuname: username or courseid of destination for the file
16488: docudom: domain of user/course of destination for the file
16489: formname: same as for userfileupload()
1.1090 raeburn 16490: fname: filename (including subdirectories) for the file
16491: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 16492: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16493: allfiles: reference to hash used to store objects found by parser
16494: codebase: reference to hash used for codebases of java objects found by parser
16495: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16496: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16497: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16498: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16499: context: if 'overwrite', will move the uploaded file from its temporary location to
16500: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16501: mimetype: reference to scalar to accommodate mime type determined
16502: from File::MMagic if $parser = parse.
1.608 albertel 16503:
16504: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16505: and /adm/notfound.html if unsuccessful (or an error message if context
16506: was 'overwrite').
16507:
1.608 albertel 16508:
16509: =item *
16510:
16511: renameuserfile(): renames an existing userfile to a new name
16512:
16513: Args:
16514: docuname: username or courseid of destination for the file
16515: docudom: domain of user/course of destination for the file
16516: old: current file name (including any subdirs under userfiles)
16517: new: desired file name (including any subdirs under userfiles)
16518:
16519: =item *
16520:
16521: mkdiruserfile(): creates a directory is a userfiles dir
16522:
16523: Args:
16524: docuname: username or courseid of destination for the file
16525: docudom: domain of user/course of destination for the file
16526: dir: dir to create (including any subdirs under userfiles)
16527:
16528: =item *
16529:
16530: removeuserfile(): removes a file that exists in userfiles
16531:
16532: Args:
16533: docuname: username or courseid of destination for the file
16534: docudom: domain of user/course of destination for the file
16535: fname: filname to delete (including any subdirs under userfiles)
16536:
16537: =item *
16538:
16539: removeuploadedurl(): convience function for removeuserfile()
16540:
16541: Args:
16542: url: a full /uploaded/... url to delete
16543:
1.747 albertel 16544: =item *
16545:
16546: get_portfile_permissions():
16547: Args:
16548: domain: domain of user or course contain the portfolio files
16549: user: name of user or num of course contain the portfolio files
16550: Returns:
16551: hashref of a dump of the proper file_permissions.db
16552:
16553:
16554: =item *
16555:
16556: get_access_controls():
16557:
16558: Args:
16559: current_permissions: the hash ref returned from get_portfile_permissions()
16560: group: (optional) the group you want the files associated with
16561: file: (optional) the file you want access info on
16562:
16563: Returns:
1.749 raeburn 16564: a hash (keys are file names) of hashes containing
16565: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16566: values are XML containing access control settings (see below)
1.747 albertel 16567:
16568: Internal notes:
16569:
1.749 raeburn 16570: access controls are stored in file_permissions.db as key=value pairs.
16571: key -> path to file/file_name\0uniqueID:scope_end_start
16572: where scope -> public,guest,course,group,domains or users.
16573: end -> UNIX time for end of access (0 -> no end date)
16574: start -> UNIX time for start of access
16575:
16576: value -> XML description of access control
16577: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16578: <start></start>
16579: <end></end>
16580:
16581: <password></password> for scope type = guest
16582:
16583: <domain></domain> for scope type = course or group
16584: <number></number>
16585: <roles id="">
16586: <role></role>
16587: <access></access>
16588: <section></section>
16589: <group></group>
16590: </roles>
16591:
16592: <dom></dom> for scope type = domains
16593:
16594: <users> for scope type = users
16595: <user>
16596: <uname></uname>
16597: <udom></udom>
16598: </user>
16599: </users>
16600: </scope>
16601:
16602: Access data is also aggregated for each file in an additional key=value pair:
16603: key -> path to file/file_name\0accesscontrol
16604: value -> reference to hash
16605: hash contains key = value pairs
16606: where key = uniqueID:scope_end_start
16607: value = UNIX time record was last updated
16608:
16609: Used to improve speed of look-ups of access controls for each file.
16610:
16611: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16612:
1.1198 raeburn 16613: =item *
16614:
1.749 raeburn 16615: modify_access_controls():
16616:
16617: Modifies access controls for a portfolio file
16618: Args
16619: 1. file name
16620: 2. reference to hash of required changes,
16621: 3. domain
16622: 4. username
16623: where domain,username are the domain of the portfolio owner
16624: (either a user or a course)
16625:
16626: Returns:
16627: 1. result of additions or updates ('ok' or 'error', with error message).
16628: 2. result of deletions ('ok' or 'error', with error message).
16629: 3. reference to hash of any new or updated access controls.
16630: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16631: key = integer (inbound ID)
1.1198 raeburn 16632: value = uniqueID
16633:
16634: =item *
16635:
16636: get_timebased_id():
16637:
16638: Attempts to get a unique timestamp-based suffix for use with items added to a
16639: course via the Course Editor (e.g., folders, composite pages,
16640: group bulletin boards).
16641:
16642: Args: (first three required; six others optional)
16643:
16644: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16645: docssequence, or name of group
16646:
16647: 2. keyid (alphanumeric): name of temporary locking key in hash,
16648: e.g., num, boardids
16649:
16650: 3. namespace: name of gdbm file used to store suffixes already assigned;
16651: file will be named nohist_namespace.db
16652:
16653: 4. cdom: domain of course; default is current course domain from %env
16654:
16655: 5. cnum: course number; default is current course number from %env
16656:
16657: 6. idtype: set to concat if an additional digit is to be appended to the
16658: unix timestamp to form the suffix, if the plain timestamp is already
16659: in use. Default is to not do this, but simply increment the unix
16660: timestamp by 1 until a unique key is obtained.
16661:
16662: 7. who: holder of locking key; defaults to user:domain for user.
16663:
16664: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16665: retrying); default is 3.
16666:
16667: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16668:
16669: Returns:
16670:
16671: 1. suffix obtained (numeric)
16672:
16673: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16674:
16675: 3. error: contains (localized) error message if an error occurred.
16676:
1.747 albertel 16677:
1.608 albertel 16678: =back
16679:
1.243 albertel 16680: =head2 HTTP Helper Routines
16681:
16682: =over 4
16683:
1.191 harris41 16684: =item *
16685:
16686: escape() : unpack non-word characters into CGI-compatible hex codes
16687:
16688: =item *
16689:
16690: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16691:
1.243 albertel 16692: =back
16693:
16694: =head1 PRIVATE SUBROUTINES
16695:
16696: =head2 Underlying communication routines (Shouldn't call)
16697:
16698: =over 4
16699:
16700: =item *
16701:
16702: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16703:
16704: =item *
16705:
16706: reply() : uses subreply to send a message to remote machine, logs all failures
16707:
16708: =item *
16709:
16710: critical() : passes a critical message to another server; if cannot
16711: get through then place message in connection buffer directory and
16712: returns con_delayed, if incapable of saving message, returns
16713: con_failed
16714:
16715: =item *
16716:
16717: reconlonc() : tries to reconnect lonc client processes.
16718:
16719: =back
16720:
16721: =head2 Resource Access Logging
16722:
16723: =over 4
16724:
16725: =item *
16726:
16727: flushcourselogs() : flush (save) buffer logs and access logs
16728:
16729: =item *
16730:
16731: courselog($what) : save message for course in hash
16732:
16733: =item *
16734:
16735: courseacclog($what) : save message for course using &courselog(). Perform
16736: special processing for specific resource types (problems, exams, quizzes, etc).
16737:
1.191 harris41 16738: =item *
16739:
16740: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16741: as a PerlChildExitHandler
1.243 albertel 16742:
16743: =back
16744:
16745: =head2 Other
16746:
16747: =over 4
16748:
16749: =item *
16750:
16751: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16752:
16753: =back
16754:
16755: =cut
1.877 foxr 16756:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>