Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1422
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1422 ! raeburn 4: # $Id: lonnet.pm,v 1.1421 2020/05/13 01:58:16 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:
1.1422 ! raeburn 3386: # ------------------------------------------------- Unsubscribe from a resource
! 3387:
! 3388: sub unsubscribe {
! 3389: my ($fname) = @_;
! 3390: my $answer;
! 3391: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
! 3392: $fname=~s/[\n\r]//g;
! 3393: my $author=$fname;
! 3394: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
! 3395: my ($udom,$uname)=split(/\//,$author);
! 3396: my $home=homeserver($uname,$udom);
! 3397: if ($home eq 'no_host') {
! 3398: $answer = 'no_host';
! 3399: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
! 3400: $answer = 'home';
! 3401: } else {
! 3402: my $defdom = $perlvar{'lonDefDomain'};
! 3403: if (&will_trust('content',$defdom,$udom)) {
! 3404: $answer = reply("unsub:$fname",$home);
! 3405: } else {
! 3406: $answer = 'untrusted';
! 3407: }
! 3408: }
! 3409: return $answer;
! 3410: }
! 3411:
1.330 www 3412: # ------------------------------------------------ Get server side include body
3413: sub ssi_body {
1.381 albertel 3414: my ($filelink,%form)=@_;
1.606 matthew 3415: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3416: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3417: }
1.953 www 3418: my $output='';
3419: my $response;
1.980 raeburn 3420: if ($filelink=~/^https?\:/) {
1.954 raeburn 3421: ($output,$response)=&externalssi($filelink);
1.953 www 3422: } else {
1.1004 droeschl 3423: $filelink .= $filelink=~/\?/ ? '&' : '?';
3424: $filelink .= 'inhibitmenu=yes';
1.953 www 3425: ($output,$response)=&ssi($filelink,%form);
3426: }
1.778 albertel 3427: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3428: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3429: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3430: if (wantarray) {
3431: return ($output, $response);
3432: } else {
3433: return $output;
3434: }
1.8 www 3435: }
3436:
1.15 www 3437: # --------------------------------------------------------- Server Side Include
3438:
1.782 albertel 3439: sub absolute_url {
3440: my ($host_name) = @_;
3441: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3442: if ($host_name eq '') {
3443: $host_name = $ENV{'SERVER_NAME'};
3444: }
3445: return $protocol.$host_name;
3446: }
3447:
1.942 foxr 3448: #
3449: # Server side include.
3450: # Parameters:
3451: # fn Possibly encrypted resource name/id.
3452: # form Hash that describes how the rendering should be done
3453: # and other things.
1.944 foxr 3454: # Returns:
1.950 raeburn 3455: # Scalar context: The content of the response.
3456: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3457: #
1.15 www 3458: sub ssi {
3459:
1.944 foxr 3460: my ($fn,%form)=@_;
1.23 www 3461: my $request;
1.711 albertel 3462:
3463: $form{'no_update_last_known'}=1;
1.895 albertel 3464: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3465: if (%form) {
1.782 albertel 3466: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3467: $request->content(join('&',map {
3468: my $name = escape($_);
3469: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3470: ? join("&$name=", map {escape($_) } @{$form{$_}})
3471: : &escape($form{$_}) );
3472: } keys(%form)));
1.23 www 3473: } else {
1.782 albertel 3474: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3475: }
3476:
1.15 www 3477: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3478: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3479: my $islocal;
3480: if (($env{'request.course.id'}) &&
3481: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3482: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3483: ($form{'grade_symb'} ne '') &&
3484: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3485: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3486: $islocal = 1;
3487: }
1.1384 raeburn 3488: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385 raeburn 3489: '','','',$islocal);
1.1182 foxr 3490:
1.944 foxr 3491: if (wantarray) {
1.1345 raeburn 3492: return ($response->content, $response);
1.944 foxr 3493: } else {
1.1345 raeburn 3494: return $response->content;
1.942 foxr 3495: }
1.324 www 3496: }
3497:
3498: sub externalssi {
3499: my ($url)=@_;
3500: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3501: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3502: if (wantarray) {
3503: return ($response->content, $response);
3504: } else {
3505: return $response->content;
3506: }
1.15 www 3507: }
1.254 www 3508:
1.1354 raeburn 3509:
3510: # If the local copy of a replicated resource is outdated, trigger a
3511: # connection from the homeserver to flush the delayed queue. If no update
3512: # happens, remove local copies of outdated resource (and corresponding
3513: # metadata file).
3514:
1.1352 raeburn 3515: sub remove_stale_resfile {
3516: my ($url) = @_;
1.1354 raeburn 3517: my $removed;
1.1352 raeburn 3518: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3519: my $audom = $1;
3520: my $auname = $2;
1.1353 raeburn 3521: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3522: my $homeserver = &homeserver($auname,$audom);
3523: unless (($homeserver eq 'no_host') ||
3524: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3525: my $fname = &filelocation('',$url);
3526: if (-e $fname) {
3527: my $hostname = &hostname($homeserver);
3528: if ($hostname) {
1.1397 raeburn 3529: my $protocol = $protocol{$homeserver};
3530: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3531: my $uri = &declutter($url);
3532: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3533: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3534: if ($response->is_success()) {
3535: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3536: my $locmodtime = (stat($fname))[9];
3537: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3538: my $stale;
3539: my $answer = &reply('pong',$homeserver);
3540: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3541: sleep(0.2);
3542: $locmodtime = (stat($fname))[9];
3543: if ($locmodtime < $remmodtime) {
3544: my $posstransfer = $fname.'.in.transfer';
3545: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3546: $removed = 1;
3547: } else {
3548: $stale = 1;
3549: }
3550: } else {
3551: $removed = 1;
3552: }
3553: } else {
3554: $stale = 1;
3555: }
3556: if ($stale) {
1.1421 raeburn 3557: if (unlink($fname)) {
3558: if ($uri!~/\.meta$/) {
3559: if (-e $fname.'.meta') {
3560: unlink($fname.'.meta');
3561: }
3562: }
1.1422 ! raeburn 3563: my $unsubresult = &unsubscribe($fname);
! 3564: unless ($unsubresult eq 'ok') {
! 3565: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
! 3566: }
1.1421 raeburn 3567: $removed = 1;
1.1354 raeburn 3568: }
1.1352 raeburn 3569: }
3570: }
3571: }
3572: }
3573: }
3574: }
3575: }
3576: }
1.1354 raeburn 3577: return $removed;
1.1352 raeburn 3578: }
3579:
1.492 albertel 3580: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3581:
3582: sub allowuploaded {
3583: my ($srcurl,$url)=@_;
3584: $url=&clutter(&declutter($url));
3585: my $dir=$url;
3586: $dir=~s/\/[^\/]+$//;
3587: my %httpref=();
3588: my $httpurl=&hreflocation('',$url);
3589: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3590: &Apache::lonnet::appenv(\%httpref);
1.254 www 3591: }
1.477 raeburn 3592:
1.1193 raeburn 3593: #
3594: # Determine if the current user should be able to edit a particular resource,
3595: # when viewing in course context.
3596: # (a) When viewing resource used to determine if "Edit" item is included in
3597: # Functions.
3598: # (b) When displaying folder contents in course editor, used to determine if
3599: # "Edit" link will be displayed alongside resource.
3600: #
1.1196 raeburn 3601: # input: six args -- filename (decluttered), course number, course domain,
3602: # url, symb (if registered) and group (if this is a group
3603: # item -- e.g., bulletin board, group page etc.).
3604: # output: array of five scalars --
1.1193 raeburn 3605: # $cfile -- url for file editing if editable on current server
3606: # $home -- homeserver of resource (i.e., for author if published,
3607: # or course if uploaded.).
3608: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3609: # $forceedit -- 1 if icon/link should be to go to edit mode
3610: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3611: #
3612:
3613: sub can_edit_resource {
1.1194 raeburn 3614: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3615: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3616: #
3617: # For aboutme pages user can only edit his/her own.
3618: #
1.1199 raeburn 3619: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3620: my ($sdom,$sname) = ($1,$2);
3621: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3622: $home = $env{'user.home'};
3623: $cfile = $resurl;
3624: if ($env{'form.forceedit'}) {
3625: $forceview = 1;
3626: } else {
3627: $forceedit = 1;
3628: }
3629: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3630: } else {
3631: return;
3632: }
3633: }
3634:
3635: if ($env{'request.course.id'}) {
3636: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3637: if ($group ne '') {
3638: # if this is a group homepage or group bulletin board, check group privs
3639: my $allowed = 0;
1.1197 raeburn 3640: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3641: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3642: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3643: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3644: $allowed = 1;
3645: }
1.1197 raeburn 3646: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3647: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3648: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3649: $allowed = 1;
3650: }
3651: }
3652: if ($allowed) {
3653: $home=&homeserver($cnum,$cdom);
3654: if ($env{'form.forceedit'}) {
3655: $forceview = 1;
3656: } else {
3657: $forceedit = 1;
3658: }
3659: $cfile = $resurl;
3660: } else {
3661: return;
3662: }
3663: } else {
1.1208 raeburn 3664: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3665: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3666: return;
3667: }
3668: } elsif (!$crsedit) {
1.1194 raeburn 3669: #
3670: # No edit allowed where CC has switched to student role.
3671: #
3672: return;
3673: }
3674: }
3675: }
3676:
1.1193 raeburn 3677: if ($file ne '') {
3678: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3679: if (&is_course_upload($file,$cnum,$cdom)) {
3680: $uploaded = 1;
3681: $incourse = 1;
1.1193 raeburn 3682: if ($file =~/\.(htm|html|css|js|txt)$/) {
3683: $cfile = &hreflocation('',$file);
1.1201 raeburn 3684: if ($env{'form.forceedit'}) {
3685: $forceview = 1;
3686: } else {
3687: $forceedit = 1;
3688: }
1.1194 raeburn 3689: }
3690: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3691: $incourse = 1;
3692: if ($env{'form.forceedit'}) {
3693: $forceview = 1;
3694: } else {
3695: $forceedit = 1;
3696: }
3697: $cfile = $resurl;
3698: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3699: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3700: $incourse = 1;
3701: if ($env{'form.forceedit'}) {
3702: $forceview = 1;
3703: } else {
3704: $forceedit = 1;
3705: }
3706: $cfile = $resurl;
1.1199 raeburn 3707: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3708: $incourse = 1;
3709: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3710: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3711: $incourse = 1;
1.1199 raeburn 3712: if ($env{'form.forceedit'}) {
3713: $forceview = 1;
3714: } else {
3715: $forceedit = 1;
3716: }
3717: $cfile = $resurl;
1.1419 raeburn 3718: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3719: my ($map,$id,$res) = &decode_symb($symb);
3720: if ($map =~ /\.page$/) {
3721: $incourse = 1;
3722: if ($env{'form.forceedit'}) {
3723: $forceview = 1;
3724: $cfile = $map;
3725: } else {
3726: $forceedit = 1;
3727: $cfile = '/adm/wrapper'.$resurl;
3728: }
3729: }
1.1343 raeburn 3730: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3731: $incourse = 1;
3732: if ($env{'form.forceedit'}) {
3733: $forceview = 1;
3734: } else {
3735: $forceedit = 1;
3736: }
3737: $cfile = $resurl;
1.1208 raeburn 3738: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3739: $incourse = 1;
3740: if ($env{'form.forceedit'}) {
3741: $forceview = 1;
3742: } else {
3743: $forceedit = 1;
3744: }
3745: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3746: }
3747: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3748: my $template = '/res/lib/templates/simpleproblem.problem';
3749: if (&is_on_map($template)) {
3750: $incourse = 1;
3751: $forceview = 1;
3752: $cfile = $template;
1.1193 raeburn 3753: }
1.1199 raeburn 3754: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3755: $incourse = 1;
3756: if ($env{'form.forceedit'}) {
3757: $forceview = 1;
3758: } else {
3759: $forceedit = 1;
3760: }
3761: $cfile = $resurl;
1.1343 raeburn 3762: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3763: $incourse = 1;
3764: if ($env{'form.forceedit'}) {
3765: $forceview = 1;
3766: } else {
3767: $forceedit = 1;
3768: }
3769: $cfile = $resurl;
1.1199 raeburn 3770: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3771: $incourse = 1;
3772: $forceview = 1;
3773: if ($symb) {
3774: my ($map,$id,$res)=&decode_symb($symb);
3775: $env{'request.symb'} = $symb;
3776: $cfile = &clutter($res);
3777: } else {
3778: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3779: my $escfile = &unescape($cfile);
1.1343 raeburn 3780: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3781: $cfile = '/adm/wrapper'.$escfile;
3782: } else {
3783: $escfile =~ s{^http://}{};
3784: $cfile = &escape("/adm/wrapper/ext/$escfile");
3785: }
1.1199 raeburn 3786: }
1.1234 raeburn 3787: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3788: if ($env{'form.forceedit'}) {
3789: $forceview = 1;
3790: } else {
3791: $forceedit = 1;
3792: }
3793: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3794: }
3795: }
1.1194 raeburn 3796: if ($uploaded || $incourse) {
3797: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3798: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3799: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3800: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3801: # Check that the user has permission to edit this resource
3802: my $setpriv = 1;
3803: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3804: if (defined($cfudom)) {
3805: $home=&homeserver($cfuname,$cfudom);
3806: $cfile=$file;
3807: }
3808: }
1.1194 raeburn 3809: if (($cfile ne '') && (!$incourse || $uploaded) &&
3810: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3811: my @ids=¤t_machine_ids();
3812: unless (grep(/^\Q$home\E$/,@ids)) {
3813: $switchserver=1;
3814: }
3815: }
3816: }
1.1194 raeburn 3817: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3818: }
3819:
3820: sub is_course_upload {
3821: my ($file,$cnum,$cdom) = @_;
3822: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3823: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3824: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3825: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3826: return 1;
3827: }
3828: return;
3829: }
3830:
1.1194 raeburn 3831: sub in_course {
1.1195 raeburn 3832: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3833: if ($hideprivileged) {
3834: my $skipuser;
1.1219 raeburn 3835: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3836: my @possdoms = ($cdom);
3837: if ($coursehash{'checkforpriv'}) {
3838: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3839: }
3840: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3841: $skipuser = 1;
3842: if ($coursehash{'nothideprivileged'}) {
3843: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3844: my $user;
3845: if ($item =~ /:/) {
3846: $user = $item;
3847: } else {
3848: $user = join(':',split(/[\@]/,$item));
3849: }
3850: if ($user eq $uname.':'.$udom) {
3851: undef($skipuser);
3852: last;
3853: }
3854: }
3855: }
3856: if ($skipuser) {
3857: return 0;
3858: }
3859: }
3860: }
1.1194 raeburn 3861: $type ||= 'any';
3862: if (!defined($cdom) || !defined($cnum)) {
3863: my $cid = $env{'request.course.id'};
3864: $cdom = $env{'course.'.$cid.'.domain'};
3865: $cnum = $env{'course.'.$cid.'.num'};
3866: }
3867: my $typesref;
1.1195 raeburn 3868: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3869: $typesref = ['active','previous','future'];
3870: } elsif ($type eq 'previous' || $type eq 'future') {
3871: $typesref = [$type];
3872: }
3873: my %roles = &get_my_roles($uname,$udom,'userroles',
3874: $typesref,undef,[$cdom]);
3875: my ($tmp) = keys(%roles);
3876: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3877: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3878: if (@course_roles > 0) {
3879: return 1;
3880: }
3881: return 0;
3882: }
3883:
1.478 albertel 3884: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3885: # input: action, courseID, current domain, intended
1.637 raeburn 3886: # path to file, source of file, instruction to parse file for objects,
3887: # ref to hash for embedded objects,
3888: # ref to hash for codebase of java objects.
1.1095 raeburn 3889: # reference to scalar to accommodate mime type determined
3890: # from File::MMagic if $parser = parse.
1.637 raeburn 3891: #
1.485 raeburn 3892: # output: url to file (if action was uploaddoc),
3893: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3894: #
1.478 albertel 3895: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3896: # course.
1.477 raeburn 3897: #
1.478 albertel 3898: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3899: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3900: # course's home server.
1.477 raeburn 3901: #
1.478 albertel 3902: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3903: # be copied from $source (current location) to
3904: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3905: # and will then be copied to
3906: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3907: # course's home server.
1.485 raeburn 3908: #
1.481 raeburn 3909: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3910: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3911: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3912: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3913: # in course's home server.
1.637 raeburn 3914: #
1.477 raeburn 3915:
3916: sub process_coursefile {
1.1095 raeburn 3917: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3918: $mimetype)=@_;
1.477 raeburn 3919: my $fetchresult;
1.638 albertel 3920: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3921: if ($action eq 'propagate') {
1.638 albertel 3922: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3923: $home);
1.481 raeburn 3924: } else {
1.477 raeburn 3925: my $fpath = '';
3926: my $fname = $file;
1.478 albertel 3927: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3928: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3929: my $filepath = &build_filepath($fpath);
1.481 raeburn 3930: if ($action eq 'copy') {
3931: if ($source eq '') {
3932: $fetchresult = 'no source file';
3933: return $fetchresult;
3934: } else {
3935: my $destination = $filepath.'/'.$fname;
3936: rename($source,$destination);
3937: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3938: $home);
1.481 raeburn 3939: }
3940: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 3941: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3942: print $fh $env{'form.'.$source};
1.481 raeburn 3943: close($fh);
1.637 raeburn 3944: if ($parser eq 'parse') {
1.1024 raeburn 3945: my $mm = new File::MMagic;
1.1095 raeburn 3946: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3947: if ($type eq 'text/html') {
1.1024 raeburn 3948: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3949: unless ($parse_result eq 'ok') {
3950: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3951: }
1.637 raeburn 3952: }
1.1095 raeburn 3953: if (ref($mimetype)) {
3954: $$mimetype = $type;
3955: }
1.637 raeburn 3956: }
1.477 raeburn 3957: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3958: $home);
1.481 raeburn 3959: if ($fetchresult eq 'ok') {
3960: return '/uploaded/'.$fpath.'/'.$fname;
3961: } else {
3962: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3963: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3964: return '/adm/notfound.html';
3965: }
1.477 raeburn 3966: }
3967: }
1.485 raeburn 3968: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3969: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3970: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3971: }
3972: return $fetchresult;
3973: }
3974:
1.637 raeburn 3975: sub build_filepath {
3976: my ($fpath) = @_;
3977: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3978: unless ($fpath eq '') {
3979: my @parts=split('/',$fpath);
3980: foreach my $part (@parts) {
3981: $filepath.= '/'.$part;
3982: if ((-e $filepath)!=1) {
3983: mkdir($filepath,0777);
3984: }
3985: }
3986: }
3987: return $filepath;
3988: }
3989:
3990: sub store_edited_file {
1.638 albertel 3991: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3992: my $file = $primary_url;
3993: $file =~ s#^/uploaded/$docudom/$docuname/##;
3994: my $fpath = '';
3995: my $fname = $file;
3996: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3997: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3998: my $filepath = &build_filepath($fpath);
1.1359 raeburn 3999: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4000: print $fh $content;
4001: close($fh);
1.638 albertel 4002: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4003: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4004: $home);
1.637 raeburn 4005: if ($$fetchresult eq 'ok') {
4006: return '/uploaded/'.$fpath.'/'.$fname;
4007: } else {
1.638 albertel 4008: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4009: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4010: return '/adm/notfound.html';
4011: }
4012: }
4013:
1.531 albertel 4014: sub clean_filename {
1.831 albertel 4015: my ($fname,$args)=@_;
1.315 www 4016: # Replace Windows backslashes by forward slashes
1.257 www 4017: $fname=~s/\\/\//g;
1.831 albertel 4018: if (!$args->{'keep_path'}) {
4019: # Get rid of everything but the actual filename
4020: $fname=~s/^.*\/([^\/]+)$/$1/;
4021: }
1.315 www 4022: # Replace spaces by underscores
4023: $fname=~s/\s+/\_/g;
1.1406 raeburn 4024: # Transliterate non-ascii text to ascii
4025: my $lang = &Apache::lonlocal::current_language();
4026: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4027: # Replace all other weird characters by nothing
1.831 albertel 4028: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4029: # Replace all .\d. sequences with _\d. so they no longer look like version
4030: # numbers
4031: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 4032: return $fname;
4033: }
1.1406 raeburn 4034:
1.1051 raeburn 4035: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4036: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4037: # image with the same aspect ratio as the original, but with dimensions which do
4038: # not exceed $resizewidth and $resizeheight.
4039:
1.984 neumanie 4040: sub resizeImage {
1.1051 raeburn 4041: my ($img_path,$resizewidth,$resizeheight) = @_;
4042: my $ima = Image::Magick->new;
4043: my $resized;
4044: if (-e $img_path) {
4045: $ima->Read($img_path);
4046: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4047: my $width = $ima->Get('width');
4048: my $height = $ima->Get('height');
4049: if ($width > $resizewidth) {
4050: my $factor = $width/$resizewidth;
4051: my $newheight = $height/$factor;
4052: $ima->Scale(width=>$resizewidth,height=>$newheight);
4053: $resized = 1;
4054: }
4055: }
4056: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4057: my $width = $ima->Get('width');
4058: my $height = $ima->Get('height');
4059: if ($height > $resizeheight) {
4060: my $factor = $height/$resizeheight;
4061: my $newwidth = $width/$factor;
4062: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4063: $resized = 1;
4064: }
4065: }
4066: if ($resized) {
4067: $ima->Write($img_path);
4068: }
4069: }
4070: return;
1.977 amueller 4071: }
4072:
1.608 albertel 4073: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4074: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4075: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4076: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4077: # canceloverwrite, scantron or ''.
1.1090 raeburn 4078: # if 'coursedoc': upload to the current course
4079: # if 'existingfile': write file to tmp/overwrites directory
4080: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4081: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4082: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4083: # $parser - instruction to parse file for objects ($parser = parse) or
4084: # if context is 'scantron', $parser is hashref of csv column mapping
4085: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4086: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4087: # $allfiles - reference to hash for embedded objects
4088: # $codebase - reference to hash for codebase of java objects
4089: # $desuname - username for permanent storage of uploaded file
4090: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4091: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4092: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4093: # $resizewidth - width (pixels) to which to resize uploaded image
4094: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4095: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4096: # from File::MMagic.
1.858 raeburn 4097: #
1.686 albertel 4098: # output: url of file in userspace, or error: <message>
4099: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4100:
1.531 albertel 4101: sub userfileupload {
1.1090 raeburn 4102: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4103: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4104: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4105: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4106: $fname=&clean_filename($fname);
1.1090 raeburn 4107: # See if there is anything left
1.257 www 4108: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4109: # If filename now begins with a . prepend unix timestamp _ milliseconds
4110: if ($fname =~ /^\./) {
4111: my ($s,$usec) = &gettimeofday();
4112: while (length($usec) < 6) {
4113: $usec = '0'.$usec;
4114: }
4115: $fname = $s.'_'.substr($usec,0,3).$fname;
4116: }
1.1090 raeburn 4117: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4118: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4119: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4120: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4121: my $now = time;
1.1090 raeburn 4122: my $filepath;
1.1095 raeburn 4123: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4124: $filepath = 'tmp/helprequests/'.$now;
4125: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4126: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4127: '_'.$env{'user.domain'}.'/pending';
4128: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4129: my ($docuname,$docudom);
1.1350 raeburn 4130: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4131: $docudom = $destudom;
4132: } else {
4133: $docudom = $env{'user.domain'};
4134: }
1.1350 raeburn 4135: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4136: $docuname = $destuname;
4137: } else {
4138: $docuname = $env{'user.name'};
4139: }
4140: if (exists($env{'form.group'})) {
4141: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4142: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4143: }
4144: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4145: if ($context eq 'canceloverwrite') {
4146: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4147: if (-e $tempfile) {
4148: my @info = stat($tempfile);
4149: if ($info[9] eq $env{'form.timestamp'}) {
4150: unlink($tempfile);
4151: }
4152: }
4153: return;
1.523 raeburn 4154: }
4155: }
1.1090 raeburn 4156: # Create the directory if not present
1.741 raeburn 4157: my @parts=split(/\//,$filepath);
4158: my $fullpath = $perlvar{'lonDaemons'};
4159: for (my $i=0;$i<@parts;$i++) {
4160: $fullpath .= '/'.$parts[$i];
4161: if ((-e $fullpath)!=1) {
4162: mkdir($fullpath,0777);
4163: }
4164: }
1.1359 raeburn 4165: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4166: print $fh $env{'form.'.$formname};
4167: close($fh);
1.1090 raeburn 4168: if ($context eq 'existingfile') {
4169: my @info = stat($fullpath.'/'.$fname);
4170: return ($fullpath.'/'.$fname,$info[9]);
4171: } else {
4172: return $fullpath.'/'.$fname;
4173: }
1.523 raeburn 4174: }
1.995 raeburn 4175: if ($subdir eq 'scantron') {
4176: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4177: } else {
1.995 raeburn 4178: $fname="$subdir/$fname";
4179: }
1.1090 raeburn 4180: if ($context eq 'coursedoc') {
1.638 albertel 4181: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4182: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4183: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4184: return &finishuserfileupload($docuname,$docudom,
4185: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4186: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4187: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4188: } else {
1.1218 raeburn 4189: if ($env{'form.folder'}) {
4190: $fname=$env{'form.folder'}.'/'.$fname;
4191: }
1.638 albertel 4192: return &process_coursefile('uploaddoc',$docuname,$docudom,
4193: $fname,$formname,$parser,
1.1095 raeburn 4194: $allfiles,$codebase,$mimetype);
1.481 raeburn 4195: }
1.719 banghart 4196: } elsif (defined($destuname)) {
4197: my $docuname=$destuname;
4198: my $docudom=$destudom;
1.860 raeburn 4199: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4200: $parser,$allfiles,$codebase,
1.1051 raeburn 4201: $thumbwidth,$thumbheight,
1.1095 raeburn 4202: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4203: } else {
1.638 albertel 4204: my $docuname=$env{'user.name'};
4205: my $docudom=$env{'user.domain'};
1.1220 raeburn 4206: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4207: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4208: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4209: }
1.860 raeburn 4210: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4211: $parser,$allfiles,$codebase,
1.1051 raeburn 4212: $thumbwidth,$thumbheight,
1.1095 raeburn 4213: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4214: }
1.271 www 4215: }
4216:
4217: sub finishuserfileupload {
1.860 raeburn 4218: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4219: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4220: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4221: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4222:
1.860 raeburn 4223: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4224: $file=$fname;
4225: if ($fname=~m|/|) {
4226: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4227: $path.=$fnamepath.'/';
4228: }
1.259 www 4229: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4230: my $count;
4231: for ($count=4;$count<=$#parts;$count++) {
4232: $filepath.="/$parts[$count]";
4233: if ((-e $filepath)!=1) {
4234: mkdir($filepath,0777);
4235: }
4236: }
1.984 neumanie 4237:
1.258 www 4238: # Save the file
4239: {
1.1359 raeburn 4240: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4241: &logthis('Failed to create '.$filepath.'/'.$file);
4242: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4243: return '/adm/notfound.html';
4244: }
1.1090 raeburn 4245: if ($context eq 'overwrite') {
1.1117 foxr 4246: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4247: my $target = $filepath.'/'.$file;
4248: if (-e $source) {
4249: my @info = stat($source);
4250: if ($info[9] eq $env{'form.timestamp'}) {
4251: unless (&File::Copy::move($source,$target)) {
4252: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4253: return "Moving from $source failed";
4254: }
4255: } else {
4256: return "Temporary file: $source had unexpected date/time for last modification";
4257: }
4258: } else {
4259: return "Temporary file: $source missing";
4260: }
4261: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4262: &logthis('Failed to write to '.$filepath.'/'.$file);
4263: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4264: return '/adm/notfound.html';
4265: }
1.570 albertel 4266: close(FH);
1.1051 raeburn 4267: if ($resizewidth && $resizeheight) {
4268: my $mm = new File::MMagic;
4269: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4270: if ($mime_type =~ m{^image/}) {
4271: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4272: }
1.977 amueller 4273: }
1.258 www 4274: }
1.1152 raeburn 4275: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4276: if (ref($mimetype)) {
4277: if ($$mimetype eq '') {
4278: my $mm = new File::MMagic;
4279: my $type = $mm->checktype_filename($filepath.'/'.$file);
4280: $$mimetype = $type;
4281: }
4282: }
4283: }
1.1401 raeburn 4284: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4285: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4286: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4287: $allfiles,$codebase);
4288: unless ($parse_result eq 'ok') {
4289: &logthis('Failed to parse '.$filepath.$file.
4290: ' for embedded media: '.$parse_result);
4291: }
1.637 raeburn 4292: }
1.1401 raeburn 4293: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4294: my $format = $env{'form.scantron_format'};
4295: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4296: }
1.860 raeburn 4297: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4298: my $input = $filepath.'/'.$file;
4299: my $output = $filepath.'/'.'tn-'.$file;
4300: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4301: my @args = ('convert','-sample',$thumbsize,$input,$output);
4302: system({$args[0]} @args);
1.860 raeburn 4303: if (-e $filepath.'/'.'tn-'.$file) {
4304: $fetchthumb = 1;
4305: }
4306: }
1.858 raeburn 4307:
1.259 www 4308: # Notify homeserver to grep it
4309: #
1.984 neumanie 4310: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4311: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4312: if ($fetchresult eq 'ok') {
1.860 raeburn 4313: if ($fetchthumb) {
4314: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4315: if ($thumbresult ne 'ok') {
4316: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4317: $docuhome.': '.$thumbresult);
4318: }
4319: }
1.259 www 4320: #
1.258 www 4321: # Return the URL to it
1.494 albertel 4322: return '/uploaded/'.$path.$file;
1.263 www 4323: } else {
1.494 albertel 4324: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4325: ': '.$fetchresult);
1.263 www 4326: return '/adm/notfound.html';
1.858 raeburn 4327: }
1.493 albertel 4328: }
4329:
1.637 raeburn 4330: sub extract_embedded_items {
1.961 raeburn 4331: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4332: my @state = ();
1.1164 raeburn 4333: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4334: my %javafiles = (
4335: codebase => '',
4336: code => '',
4337: archive => ''
4338: );
4339: my %mediafiles = (
4340: src => '',
4341: movie => '',
4342: );
1.648 raeburn 4343: my $p;
4344: if ($content) {
4345: $p = HTML::LCParser->new($content);
4346: } else {
1.961 raeburn 4347: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4348: }
1.641 albertel 4349: while (my $t=$p->get_token()) {
1.640 albertel 4350: if ($t->[0] eq 'S') {
4351: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4352: push(@state, $tagname);
1.648 raeburn 4353: if (lc($tagname) eq 'allow') {
4354: &add_filetype($allfiles,$attr->{'src'},'src');
4355: }
1.640 albertel 4356: if (lc($tagname) eq 'img') {
4357: &add_filetype($allfiles,$attr->{'src'},'src');
4358: }
1.886 albertel 4359: if (lc($tagname) eq 'a') {
1.1222 raeburn 4360: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4361: &add_filetype($allfiles,$attr->{'href'},'href');
4362: }
1.886 albertel 4363: }
1.645 raeburn 4364: if (lc($tagname) eq 'script') {
1.1164 raeburn 4365: my $src;
1.645 raeburn 4366: if ($attr->{'archive'} =~ /\.jar$/i) {
4367: &add_filetype($allfiles,$attr->{'archive'},'archive');
4368: } else {
1.1164 raeburn 4369: if ($attr->{'src'} ne '') {
4370: $src = $attr->{'src'};
4371: &add_filetype($allfiles,$src,'src');
4372: }
4373: }
4374: my $text = $p->get_trimmed_text();
4375: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4376: my @swfargs = split(/,/,$1);
4377: foreach my $item (@swfargs) {
4378: $item =~ s/["']//g;
4379: $item =~ s/^\s+//;
4380: $item =~ s/\s+$//;
4381: }
4382: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4383: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4384: push(@{$related{$swfargs[0]}},$swfargs[2]);
4385: } else {
4386: $related{$swfargs[0]} = [$swfargs[2]];
4387: }
4388: }
1.645 raeburn 4389: }
4390: }
4391: if (lc($tagname) eq 'link') {
4392: if (lc($attr->{'rel'}) eq 'stylesheet') {
4393: &add_filetype($allfiles,$attr->{'href'},'href');
4394: }
4395: }
1.640 albertel 4396: if (lc($tagname) eq 'object' ||
4397: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4398: foreach my $item (keys(%javafiles)) {
4399: $javafiles{$item} = '';
4400: }
1.1164 raeburn 4401: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4402: $lastids{lc($tagname)} = $attr->{'id'};
4403: }
1.640 albertel 4404: }
4405: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4406: my $name = lc($attr->{'name'});
4407: foreach my $item (keys(%javafiles)) {
4408: if ($name eq $item) {
4409: $javafiles{$item} = $attr->{'value'};
4410: last;
4411: }
4412: }
1.1164 raeburn 4413: my $pathfrom;
1.640 albertel 4414: foreach my $item (keys(%mediafiles)) {
4415: if ($name eq $item) {
1.1164 raeburn 4416: $pathfrom = $attr->{'value'};
4417: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4418: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4419: last;
4420: }
4421: }
1.1164 raeburn 4422: if ($name eq 'flashvars') {
4423: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4424: }
4425: if ($pathfrom ne '') {
4426: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4427: $pathfrom);
4428: }
1.640 albertel 4429: }
4430: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4431: foreach my $item (keys(%javafiles)) {
4432: if ($attr->{$item}) {
4433: $javafiles{$item} = $attr->{$item};
4434: last;
4435: }
4436: }
4437: foreach my $item (keys(%mediafiles)) {
4438: if ($attr->{$item}) {
4439: &add_filetype($allfiles,$attr->{$item},$item);
4440: last;
4441: }
4442: }
1.1164 raeburn 4443: if (lc($tagname) eq 'embed') {
4444: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4445: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4446: $attr->{'src'});
4447: }
4448: }
1.640 albertel 4449: }
1.1243 raeburn 4450: if (lc($tagname) eq 'iframe') {
4451: my $src = $attr->{'src'} ;
4452: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4453: &add_filetype($allfiles,$src,'src');
4454: } elsif ($src =~ m{^/}) {
4455: if ($env{'request.course.id'}) {
4456: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4457: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4458: my $url = &hreflocation('',$fullpath);
4459: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4460: my $relpath = $1;
4461: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4462: &add_filetype($allfiles,$1,'src');
4463: }
4464: }
4465: }
4466: }
4467: }
1.1164 raeburn 4468: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4469: pop(@state);
1.1164 raeburn 4470: }
1.640 albertel 4471: } elsif ($t->[0] eq 'E') {
4472: my ($tagname) = ($t->[1]);
4473: if ($javafiles{'codebase'} ne '') {
4474: $javafiles{'codebase'} .= '/';
4475: }
4476: if (lc($tagname) eq 'applet' ||
4477: lc($tagname) eq 'object' ||
4478: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4479: ) {
4480: foreach my $item (keys(%javafiles)) {
4481: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4482: my $file=$javafiles{'codebase'}.$javafiles{$item};
4483: &add_filetype($allfiles,$file,$item);
4484: }
4485: }
4486: }
4487: pop @state;
4488: }
4489: }
1.1164 raeburn 4490: foreach my $id (sort(keys(%flashvars))) {
4491: if ($shockwave{$id} ne '') {
4492: my @pairs = split(/\&/,$flashvars{$id});
4493: foreach my $pair (@pairs) {
4494: my ($key,$value) = split(/\=/,$pair);
4495: if ($key eq 'thumb') {
4496: &add_filetype($allfiles,$value,$key);
4497: } elsif ($key eq 'content') {
4498: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4499: my ($ext) = ($value =~ /\.([^.]+)$/);
4500: if ($ext ne '') {
4501: &add_filetype($allfiles,$path.$value,$ext);
4502: }
4503: }
4504: }
4505: }
4506: }
1.637 raeburn 4507: return 'ok';
4508: }
4509:
1.639 albertel 4510: sub add_filetype {
4511: my ($allfiles,$file,$type)=@_;
4512: if (exists($allfiles->{$file})) {
4513: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4514: push(@{$allfiles->{$file}}, &escape($type));
4515: }
4516: } else {
4517: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4518: }
4519: }
4520:
1.1164 raeburn 4521: sub embedded_dependency {
4522: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4523: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4524: if (($identifier ne '') &&
4525: (ref($related->{$identifier}) eq 'ARRAY') &&
4526: ($pathfrom ne '')) {
4527: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4528: foreach my $dep (@{$related->{$identifier}}) {
4529: &add_filetype($allfiles,$path.$dep,'object');
4530: }
4531: }
4532: }
4533: return;
4534: }
4535:
1.1401 raeburn 4536: sub bubblesheet_converter {
4537: my ($cdom,$fullpath,$config,$format) = @_;
4538: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4539: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4540: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4541: my (%csvcols,%csvoptions);
4542: if (ref($config->{'fields'}) eq 'HASH') {
4543: %csvcols = %{$config->{'fields'}};
4544: }
4545: if (ref($config->{'options'}) eq 'HASH') {
4546: %csvoptions = %{$config->{'options'}};
4547: }
1.1401 raeburn 4548: my %csvbynum = reverse(%csvcols);
4549: my %scantronconf = &get_scantron_config($format,$cdom);
4550: if (keys(%scantronconf)) {
4551: my %bynum = (
4552: $scantronconf{CODEstart} => 'CODEstart',
4553: $scantronconf{IDstart} => 'IDstart',
4554: $scantronconf{PaperID} => 'PaperID',
4555: $scantronconf{FirstName} => 'FirstName',
4556: $scantronconf{LastName} => 'LastName',
4557: $scantronconf{Qstart} => 'Qstart',
4558: );
4559: my @ordered;
4560: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4561: push(@ordered,$bynum{$item});
1.1401 raeburn 4562: }
4563: my %mapstart = (
4564: CODEstart => 'CODE',
4565: IDstart => 'ID',
4566: PaperID => 'PaperID',
4567: FirstName => 'FirstName',
4568: LastName => 'LastName',
4569: Qstart => 'FirstQuestion',
4570: );
4571: my %maplength = (
4572: CODEstart => 'CODElength',
4573: IDstart => 'IDlength',
4574: PaperID => 'PaperIDlength',
4575: FirstName => 'FirstNamelength',
4576: LastName => 'LastNamelength',
4577: );
4578: if (open(my $fh,'<',$fullpath)) {
4579: my $output;
1.1403 raeburn 4580: my %lettdig = &letter_to_digits();
4581: my %diglett = reverse(%lettdig);
4582: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4583: my $num = 0;
1.1401 raeburn 4584: while (my $line=<$fh>) {
1.1404 raeburn 4585: $num ++;
4586: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4587: $line =~ s{[\r\n]+$}{};
4588: my %found;
4589: my @values = split(/,/,$line);
4590: my ($qstart,$record);
4591: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4592: if ((($qstart ne '') && ($i > $qstart)) ||
4593: ($csvbynum{$i} eq 'FirstQuestion')) {
4594: if ($values[$i] eq '') {
4595: $values[$i] = $scantronconf{'Qoff'};
4596: } elsif ($scantronconf{'Qon'} eq 'number') {
4597: if ($values[$i] =~ /^[A-Ja-j]$/) {
4598: $values[$i] = $lettdig{uc($values[$i])};
4599: }
4600: } elsif ($scantronconf{'Qon'} eq 'letter') {
4601: if ($values[$i] =~ /^[0-9]$/) {
4602: $values[$i] = $diglett{$values[$i]};
4603: }
4604: } else {
4605: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4606: my $digit;
4607: if ($values[$i] =~ /^[A-Ja-j]$/) {
4608: $digit = $lettdig{uc($values[$i])}-1;
4609: if ($values[$i] eq 'J') {
4610: $digit += $numletts;
4611: }
4612: } elsif ($values[$i] =~ /^[0-9]$/) {
4613: $digit = $values[$i]-1;
4614: if ($values[$i] eq '0') {
4615: $digit += $numletts;
4616: }
4617: }
4618: my $qval='';
4619: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4620: if ($j == $digit) {
4621: $qval .= $scantronconf{'Qon'};
4622: } else {
4623: $qval .= $scantronconf{'Qoff'};
4624: }
4625: }
4626: $values[$i] = $qval;
4627: }
4628: }
4629: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4630: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4631: }
4632: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4633: if ($numblank > 0) {
4634: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4635: }
1.1401 raeburn 4636: if ($csvbynum{$i} eq 'FirstQuestion') {
4637: $qstart = $i;
1.1403 raeburn 4638: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4639: } else {
1.1403 raeburn 4640: $found{'FirstQuestion'} .= $values[$i];
4641: }
4642: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4643: if ($csvoptions{'rem'}) {
4644: $values[$i] =~ s/^\s+//;
4645: }
4646: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4647: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4648: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4649: }
4650: }
4651: $found{$csvbynum{$i}} = $values[$i];
4652: }
4653: }
4654: foreach my $item (@ordered) {
4655: my $currlength = 1+length($record);
4656: my $numspaces = $scantronconf{$item} - $currlength;
4657: if ($numspaces > 0) {
4658: $record .= (' ' x $numspaces);
4659: }
4660: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4661: unless ($item eq 'Qstart') {
4662: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4663: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4664: }
4665: }
4666: $record .= $found{$mapstart{$item}};
4667: }
4668: }
4669: $output .= "$record\n";
4670: }
4671: close($fh);
4672: if ($output) {
4673: if (open(my $fh,'>',$fullpath)) {
4674: print $fh $output;
4675: close($fh);
4676: }
4677: }
4678: }
4679: }
4680: return;
4681: }
4682: }
4683:
1.1403 raeburn 4684: sub letter_to_digits {
4685: my %lettdig = (
4686: A => 1,
4687: B => 2,
4688: C => 3,
4689: D => 4,
4690: E => 5,
4691: F => 6,
4692: G => 7,
4693: H => 8,
4694: I => 9,
4695: J => 0,
4696: );
4697: return %lettdig;
4698: }
4699:
1.1401 raeburn 4700: sub get_scantron_config {
4701: my ($which,$cdom) = @_;
4702: my @lines = &get_scantronformat_file($cdom);
4703: my %config;
4704: #FIXME probably should move to XML it has already gotten a bit much now
4705: foreach my $line (@lines) {
4706: my ($name,$descrip)=split(/:/,$line);
4707: if ($name ne $which ) { next; }
4708: chomp($line);
4709: my @config=split(/:/,$line);
4710: $config{'name'}=$config[0];
4711: $config{'description'}=$config[1];
4712: $config{'CODElocation'}=$config[2];
4713: $config{'CODEstart'}=$config[3];
4714: $config{'CODElength'}=$config[4];
4715: $config{'IDstart'}=$config[5];
4716: $config{'IDlength'}=$config[6];
4717: $config{'Qstart'}=$config[7];
4718: $config{'Qlength'}=$config[8];
4719: $config{'Qoff'}=$config[9];
4720: $config{'Qon'}=$config[10];
4721: $config{'PaperID'}=$config[11];
4722: $config{'PaperIDlength'}=$config[12];
4723: $config{'FirstName'}=$config[13];
4724: $config{'FirstNamelength'}=$config[14];
4725: $config{'LastName'}=$config[15];
4726: $config{'LastNamelength'}=$config[16];
4727: $config{'BubblesPerRow'}=$config[17];
4728: last;
4729: }
4730: return %config;
4731: }
4732:
4733: sub get_scantronformat_file {
4734: my ($cdom) = @_;
4735: if ($cdom eq '') {
4736: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4737: }
4738: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4739: my $gottab = 0;
4740: my @lines;
4741: if (ref($domconfig{'scantron'}) eq 'HASH') {
4742: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4743: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4744: if ($formatfile ne '-1') {
4745: @lines = split("\n",$formatfile,-1);
4746: $gottab = 1;
4747: }
4748: }
4749: }
4750: if (!$gottab) {
4751: my $confname = $cdom.'-domainconfig';
4752: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4753: my $formatfile = &getfile($default);
4754: if ($formatfile ne '-1') {
4755: @lines = split("\n",$formatfile,-1);
4756: $gottab = 1;
4757: }
4758: }
4759: if (!$gottab) {
4760: my @domains = ¤t_machine_domains();
4761: if (grep(/^\Q$cdom\E$/,@domains)) {
4762: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4763: @lines = <$fh>;
4764: close($fh);
1.1403 raeburn 4765: }
1.1401 raeburn 4766: } else {
4767: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4768: @lines = <$fh>;
4769: close($fh);
4770: }
4771: }
4772: }
4773: return @lines;
4774: }
4775:
1.493 albertel 4776: sub removeuploadedurl {
1.984 neumanie 4777: my ($url)=@_;
4778: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4779: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4780: }
4781:
4782: sub removeuserfile {
4783: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4784: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4785: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4786: if ($result eq 'ok') {
1.798 raeburn 4787: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4788: my $metafile = $fname.'.meta';
4789: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4790: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4791: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4792: my $sqlresult =
1.823 albertel 4793: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4794: 'portfolio_metadata',$group,
4795: 'delete');
1.798 raeburn 4796: }
4797: }
4798: return $result;
1.257 www 4799: }
1.15 www 4800:
1.530 albertel 4801: sub mkdiruserfile {
4802: my ($docuname,$docudom,$dir)=@_;
4803: my $home=&homeserver($docuname,$docudom);
4804: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4805: }
4806:
1.531 albertel 4807: sub renameuserfile {
4808: my ($docuname,$docudom,$old,$new)=@_;
4809: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4810: my $result = &reply("renameuserfile:$docudom:$docuname:".
4811: &escape("$old").':'.&escape("$new"),$home);
4812: if ($result eq 'ok') {
4813: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4814: my $oldmeta = $old.'.meta';
4815: my $newmeta = $new.'.meta';
4816: my $metaresult =
4817: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4818: my $url = "/uploaded/$docudom/$docuname/$old";
4819: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4820: my $sqlresult =
1.823 albertel 4821: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4822: 'portfolio_metadata',$group,
4823: 'delete');
1.798 raeburn 4824: }
4825: }
4826: return $result;
1.531 albertel 4827: }
4828:
1.14 www 4829: # ------------------------------------------------------------------------- Log
4830:
4831: sub log {
4832: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4833: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4834: }
4835:
4836: # ------------------------------------------------------------------ Course Log
1.352 www 4837: #
4838: # This routine flushes several buffers of non-mission-critical nature
4839: #
1.157 www 4840:
4841: sub flushcourselogs {
1.352 www 4842: &logthis('Flushing log buffers');
4843: #
4844: # course logs
4845: # This is a log of all transactions in a course, which can be used
4846: # for data mining purposes
4847: #
4848: # It also collects the courseid database, which lists last transaction
4849: # times and course titles for all courseids
4850: #
4851: my %courseidbuffer=();
1.921 raeburn 4852: foreach my $crsid (keys(%courselogs)) {
1.352 www 4853: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4854: &escape($courselogs{$crsid}),
4855: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4856: delete $courselogs{$crsid};
4857: } else {
4858: &logthis('Failed to flush log buffer for '.$crsid);
4859: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4860: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4861: " exceeded maximum size, deleting.</font>");
4862: delete $courselogs{$crsid};
4863: }
1.352 www 4864: }
1.920 raeburn 4865: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4866: 'description' => $coursedescrbuf{$crsid},
4867: 'inst_code' => $courseinstcodebuf{$crsid},
4868: 'type' => $coursetypebuf{$crsid},
4869: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4870: };
1.191 harris41 4871: }
1.352 www 4872: #
4873: # Write course id database (reverse lookup) to homeserver of courses
4874: # Is used in pickcourse
4875: #
1.840 albertel 4876: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4877: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4878: $courseidbuffer{$crs_home},
4879: $crs_home,'timeonly');
1.352 www 4880: }
4881: #
4882: # File accesses
4883: # Writes to the dynamic metadata of resources to get hit counts, etc.
4884: #
1.449 matthew 4885: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4886: if ($entry =~ /___count$/) {
4887: my ($dom,$name);
1.807 albertel 4888: ($dom,$name,undef)=
1.811 albertel 4889: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4890: if (! defined($dom) || $dom eq '' ||
4891: ! defined($name) || $name eq '') {
1.620 albertel 4892: my $cid = $env{'request.course.id'};
4893: $dom = $env{'request.'.$cid.'.domain'};
4894: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4895: }
1.450 matthew 4896: my $value = $accesshash{$entry};
4897: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4898: my %temphash=($url => $value);
1.449 matthew 4899: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4900: if ($result eq 'ok') {
4901: delete $accesshash{$entry};
4902: }
4903: } else {
1.811 albertel 4904: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4905: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4906: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4907: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4908: delete $accesshash{$entry};
4909: }
1.185 www 4910: }
1.191 harris41 4911: }
1.352 www 4912: #
4913: # Roles
4914: # Reverse lookup of user roles for course faculty/staff and co-authorship
4915: #
1.800 albertel 4916: foreach my $entry (keys(%userrolehash)) {
1.351 www 4917: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4918: split(/\:/,$entry);
4919: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4920: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4921: $rudom,$runame) eq 'ok') {
4922: delete $userrolehash{$entry};
4923: }
4924: }
1.662 raeburn 4925: #
1.1334 raeburn 4926: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4927: #
4928: my %domrolebuffer = ();
1.1000 raeburn 4929: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4930: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4931: if ($domrolebuffer{$rudom}) {
4932: $domrolebuffer{$rudom}.='&'.&escape($entry).
4933: '='.&escape($domainrolehash{$entry});
4934: } else {
4935: $domrolebuffer{$rudom}.=&escape($entry).
4936: '='.&escape($domainrolehash{$entry});
4937: }
4938: delete $domainrolehash{$entry};
4939: }
4940: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4941: my %servers;
4942: if (defined(&domain($dom,'primary'))) {
4943: my $primary=&domain($dom,'primary');
4944: my $hostname=&hostname($primary);
4945: $servers{$primary} = $hostname;
4946: } else {
4947: %servers = &get_servers($dom,'library');
4948: }
1.841 albertel 4949: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4950: if (&reply('domroleput:'.$dom.':'.
4951: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4952: last;
4953: } else {
1.841 albertel 4954: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4955: }
1.662 raeburn 4956: }
4957: }
1.186 www 4958: $dumpcount++;
1.157 www 4959: }
4960:
4961: sub courselog {
4962: my $what=shift;
1.158 www 4963: $what=time.':'.$what;
1.620 albertel 4964: unless ($env{'request.course.id'}) { return ''; }
4965: $coursedombuf{$env{'request.course.id'}}=
4966: $env{'course.'.$env{'request.course.id'}.'.domain'};
4967: $coursenumbuf{$env{'request.course.id'}}=
4968: $env{'course.'.$env{'request.course.id'}.'.num'};
4969: $coursehombuf{$env{'request.course.id'}}=
4970: $env{'course.'.$env{'request.course.id'}.'.home'};
4971: $coursedescrbuf{$env{'request.course.id'}}=
4972: $env{'course.'.$env{'request.course.id'}.'.description'};
4973: $courseinstcodebuf{$env{'request.course.id'}}=
4974: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4975: $courseownerbuf{$env{'request.course.id'}}=
4976: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4977: $coursetypebuf{$env{'request.course.id'}}=
4978: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4979: if (defined $courselogs{$env{'request.course.id'}}) {
4980: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4981: } else {
1.620 albertel 4982: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4983: }
1.620 albertel 4984: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4985: &flushcourselogs();
4986: }
1.158 www 4987: }
4988:
4989: sub courseacclog {
4990: my $fnsymb=shift;
1.620 albertel 4991: unless ($env{'request.course.id'}) { return ''; }
4992: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4993: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4994: $what.=':POST';
1.583 matthew 4995: # FIXME: Probably ought to escape things....
1.800 albertel 4996: foreach my $key (keys(%env)) {
4997: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4998: my $formitem = $1;
4999: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5000: $what.=':'.$formitem.'='.$env{$key};
5001: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
5002: $what.=':'.$formitem.'='.$env{$key};
5003: }
1.158 www 5004: }
1.191 harris41 5005: }
1.583 matthew 5006: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5007: # FIXME: We should not be depending on a form parameter that someone
5008: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5009: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5010: $what.= ':POST';
5011: # FIXME: Probably ought to escape things....
5012: foreach my $element ('courseexp','crsfulltext','crsrelated',
5013: 'crsdiscuss') {
1.620 albertel 5014: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5015: }
5016: }
1.158 www 5017: }
5018: &courselog($what);
1.149 www 5019: }
5020:
1.185 www 5021: sub countacc {
5022: my $url=&declutter(shift);
1.458 matthew 5023: return if (! defined($url) || $url eq '');
1.620 albertel 5024: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5025: #
5026: # Mark that this url was used in this course
5027: #
1.620 albertel 5028: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5029: #
5030: # Increase the access count for this resource in this child process
5031: #
1.281 www 5032: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5033: $accesshash{$key}++;
1.185 www 5034: }
1.349 www 5035:
1.361 www 5036: sub linklog {
5037: my ($from,$to)=@_;
5038: $from=&declutter($from);
5039: $to=&declutter($to);
5040: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5041: $accesshash{$to.'___'.$from.'___goto'}=1;
5042: }
1.1160 www 5043:
5044: sub statslog {
5045: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5046: if ($users<2) { return; }
5047: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5048: 'course' => $env{'request.course.id'},
5049: 'sections' => '"all"',
5050: 'num_students' => $users,
5051: 'part' => $part,
5052: 'symb' => $symb,
5053: 'mean_tries' => $av_attempts,
5054: 'deg_of_diff' => $degdiff});
5055: foreach my $key (keys(%dynstore)) {
5056: $accesshash{$key}=$dynstore{$key};
5057: }
5058: }
1.361 www 5059:
1.349 www 5060: sub userrolelog {
5061: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5062: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5063: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5064: $userrolehash
5065: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5066: =$tend.':'.$tstart;
1.662 raeburn 5067: }
1.1169 droeschl 5068: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5069: $userrolehash
5070: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5071: =$tend.':'.$tstart;
5072: }
1.1334 raeburn 5073: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5074: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5075: $domainrolehash
5076: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5077: = $tend.':'.$tstart;
5078: }
1.351 www 5079: }
5080:
1.957 raeburn 5081: sub courserolelog {
5082: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5083: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5084: my $cdom = $1;
5085: my $cnum = $2;
5086: my $sec = $3;
5087: my $namespace = 'rolelog';
5088: my %storehash = (
5089: role => $trole,
5090: start => $tstart,
5091: end => $tend,
5092: selfenroll => $selfenroll,
5093: context => $context,
5094: );
5095: if ($trole eq 'gr') {
5096: $namespace = 'groupslog';
5097: $storehash{'group'} = $sec;
5098: } else {
5099: $storehash{'section'} = $sec;
5100: }
1.1188 raeburn 5101: &write_log('course',$namespace,\%storehash,$delflag,$username,
5102: $domain,$cnum,$cdom);
1.1184 raeburn 5103: if (($trole ne 'st') || ($sec ne '')) {
5104: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5105: }
5106: }
5107: return;
5108: }
5109:
1.1184 raeburn 5110: sub domainrolelog {
5111: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5112: if ($area =~ m{^/($match_domain)/$}) {
5113: my $cdom = $1;
5114: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5115: my $namespace = 'rolelog';
5116: my %storehash = (
5117: role => $trole,
5118: start => $tstart,
5119: end => $tend,
5120: context => $context,
5121: );
1.1188 raeburn 5122: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5123: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5124: }
5125: return;
5126:
5127: }
5128:
5129: sub coauthorrolelog {
5130: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5131: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5132: my $audom = $1;
5133: my $auname = $2;
5134: my $namespace = 'rolelog';
5135: my %storehash = (
5136: role => $trole,
5137: start => $tstart,
5138: end => $tend,
5139: context => $context,
5140: );
1.1188 raeburn 5141: &write_log('author',$namespace,\%storehash,$delflag,$username,
5142: $domain,$auname,$audom);
1.1184 raeburn 5143: }
5144: return;
5145: }
5146:
1.351 www 5147: sub get_course_adv_roles {
1.948 raeburn 5148: my ($cid,$codes) = @_;
1.620 albertel 5149: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5150: my %coursehash=&coursedescription($cid);
1.988 raeburn 5151: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5152: my %nothide=();
1.800 albertel 5153: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5154: if ($user !~ /:/) {
5155: $nothide{join(':',split(/[\@]/,$user))}=1;
5156: } else {
5157: $nothide{$user}=1;
5158: }
1.470 www 5159: }
1.1219 raeburn 5160: my @possdoms = ($coursehash{'domain'});
5161: if ($coursehash{'checkforpriv'}) {
5162: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5163: }
1.351 www 5164: my %returnhash=();
5165: my %dumphash=
5166: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5167: my $now=time;
1.997 raeburn 5168: my %privileged;
1.1000 raeburn 5169: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5170: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5171: if (($tstart) && ($tstart<0)) { next; }
5172: if (($tend) && ($tend<$now)) { next; }
5173: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5174: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5175: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5176: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5177: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5178: if ($role eq 'cr') { next; }
1.948 raeburn 5179: if ($codes) {
5180: if ($section) { $role .= ':'.$section; }
5181: if ($returnhash{$role}) {
5182: $returnhash{$role}.=','.$username.':'.$domain;
5183: } else {
5184: $returnhash{$role}=$username.':'.$domain;
5185: }
1.351 www 5186: } else {
1.988 raeburn 5187: my $key=&plaintext($role,$crstype);
1.973 bisitz 5188: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5189: if ($returnhash{$key}) {
5190: $returnhash{$key}.=','.$username.':'.$domain;
5191: } else {
5192: $returnhash{$key}=$username.':'.$domain;
5193: }
1.351 www 5194: }
1.948 raeburn 5195: }
1.400 www 5196: return %returnhash;
5197: }
5198:
5199: sub get_my_roles {
1.937 raeburn 5200: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5201: unless (defined($uname)) { $uname=$env{'user.name'}; }
5202: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5203: my (%dumphash,%nothide);
1.1086 raeburn 5204: if ($context eq 'userroles') {
1.1166 raeburn 5205: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5206: } else {
1.1219 raeburn 5207: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5208: if ($hidepriv) {
5209: my %coursehash=&coursedescription($udom.'_'.$uname);
5210: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5211: if ($user !~ /:/) {
5212: $nothide{join(':',split(/[\@]/,$user))} = 1;
5213: } else {
5214: $nothide{$user} = 1;
5215: }
5216: }
5217: }
1.858 raeburn 5218: }
1.400 www 5219: my %returnhash=();
5220: my $now=time;
1.999 raeburn 5221: my %privileged;
1.800 albertel 5222: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5223: my ($role,$tend,$tstart);
5224: if ($context eq 'userroles') {
1.1149 raeburn 5225: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5226: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5227: } else {
5228: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5229: }
1.400 www 5230: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5231: my $status = 'active';
1.939 raeburn 5232: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5233: $status = 'previous';
5234: }
5235: if (($tstart) && ($now<$tstart)) {
5236: $status = 'future';
5237: }
5238: if (ref($types) eq 'ARRAY') {
5239: if (!grep(/^\Q$status\E$/,@{$types})) {
5240: next;
5241: }
5242: } else {
5243: if ($status ne 'active') {
5244: next;
5245: }
5246: }
1.867 raeburn 5247: my ($rolecode,$username,$domain,$section,$area);
5248: if ($context eq 'userroles') {
1.1186 raeburn 5249: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5250: (undef,$domain,$username,$section) = split(/\//,$area);
5251: } else {
5252: ($role,$username,$domain,$section) = split(/\:/,$entry);
5253: }
1.832 raeburn 5254: if (ref($roledoms) eq 'ARRAY') {
5255: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5256: next;
5257: }
5258: }
5259: if (ref($roles) eq 'ARRAY') {
5260: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5261: if ($role =~ /^cr\//) {
5262: if (!grep(/^cr$/,@{$roles})) {
5263: next;
5264: }
1.1104 raeburn 5265: } elsif ($role =~ /^gr\//) {
5266: if (!grep(/^gr$/,@{$roles})) {
5267: next;
5268: }
1.922 raeburn 5269: } else {
5270: next;
5271: }
1.832 raeburn 5272: }
1.867 raeburn 5273: }
1.937 raeburn 5274: if ($hidepriv) {
1.1219 raeburn 5275: my @privroles = ('dc','su');
1.999 raeburn 5276: if ($context eq 'userroles') {
1.1219 raeburn 5277: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5278: } else {
1.1219 raeburn 5279: my $possdoms = [$domain];
5280: if (ref($roledoms) eq 'ARRAY') {
5281: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5282: }
1.1219 raeburn 5283: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5284: if (!$nothide{$username.':'.$domain}) {
5285: next;
5286: }
5287: }
1.937 raeburn 5288: }
5289: }
1.933 raeburn 5290: if ($withsec) {
5291: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5292: $tstart.':'.$tend;
5293: } else {
5294: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5295: }
1.832 raeburn 5296: }
1.373 www 5297: return %returnhash;
1.399 www 5298: }
5299:
1.1333 raeburn 5300: sub get_all_adhocroles {
5301: my ($dom) = @_;
5302: my @roles_by_num = ();
5303: my %domdefaults = &get_domain_defaults($dom);
5304: my (%description,%access_in_dom,%access_info);
5305: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5306: my $count = 0;
5307: my %domcurrent = %{$domdefaults{'adhocroles'}};
5308: my %ordered;
5309: foreach my $role (sort(keys(%domcurrent))) {
5310: my ($order,$desc,$access_in_dom);
5311: if (ref($domcurrent{$role}) eq 'HASH') {
5312: $order = $domcurrent{$role}{'order'};
5313: $desc = $domcurrent{$role}{'desc'};
5314: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5315: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5316: }
5317: if ($order eq '') {
5318: $order = $count;
5319: }
5320: $ordered{$order} = $role;
5321: if ($desc ne '') {
5322: $description{$role} = $desc;
5323: } else {
5324: $description{$role}= $role;
5325: }
5326: $count++;
5327: }
5328: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5329: push(@roles_by_num,$ordered{$item});
5330: }
5331: }
5332: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5333: }
5334:
1.1332 raeburn 5335: sub get_my_adhocroles {
1.1333 raeburn 5336: my ($cid,$checkreg) = @_;
5337: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5338: if ($env{'request.course.id'} eq $cid) {
5339: $cdom = $env{'course.'.$cid.'.domain'};
5340: $cnum = $env{'course.'.$cid.'.num'};
5341: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5342: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5343: $cdom = $1;
5344: $cnum = $2;
5345: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5346: $cdom,$cnum);
5347: }
5348: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5349: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5350: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5351: if ($rosterhash{$user} ne '') {
5352: my $type = (split(/:/,$rosterhash{$user}))[5];
5353: return ([],{}) if ($type eq 'auto');
5354: }
5355: }
5356: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5357: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5358: my $then=$env{'user.login.time'};
5359: my $update=$env{'user.update.time'};
1.1335 raeburn 5360: if (!$update) {
5361: $update = $then;
5362: }
5363: my @liveroles;
1.1334 raeburn 5364: foreach my $role ('dh','da') {
5365: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5366: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5367: my $limit = $update;
5368: if ($env{'request.role'} eq "$role./$cdom/") {
5369: $limit = $then;
5370: }
1.1335 raeburn 5371: my $activerole = 1;
5372: if ($tstart && $tstart>$limit) { $activerole = 0; }
5373: if ($tend && $tend <$limit) { $activerole = 0; }
5374: if ($activerole) {
5375: push(@liveroles,$role);
5376: }
1.1334 raeburn 5377: }
1.1332 raeburn 5378: }
1.1335 raeburn 5379: if (@liveroles) {
1.1332 raeburn 5380: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5381: my ($accessref,$accessinfo,%access_in_dom);
5382: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5383: if (ref($roles_by_num) eq 'ARRAY') {
5384: if (@{$roles_by_num}) {
1.1332 raeburn 5385: my %settings;
5386: if ($env{'request.course.id'} eq $cid) {
5387: foreach my $envkey (keys(%env)) {
5388: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5389: $settings{$1} = $env{$envkey};
5390: }
5391: }
5392: } else {
5393: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5394: }
5395: my %setincrs;
5396: if ($settings{'internal.adhocaccess'}) {
5397: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5398: }
5399: my @statuses;
5400: if ($env{'environment.inststatus'}) {
5401: @statuses = split(/,/,$env{'environment.inststatus'});
5402: }
5403: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5404: if (ref($accessref) eq 'HASH') {
5405: %access_in_dom = %{$accessref};
5406: }
5407: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5408: my ($curraccess,@okstatus,@personnel);
5409: if ($setincrs{$role}) {
5410: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5411: if ($curraccess eq 'status') {
5412: @okstatus = split(/\&/,$rest);
5413: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5414: @personnel = split(/\&/,$rest);
5415: }
5416: } else {
5417: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5418: if (ref($accessinfo) eq 'HASH') {
5419: if ($curraccess eq 'status') {
5420: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5421: @okstatus = @{$accessinfo->{$role}};
5422: }
5423: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5424: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5425: @personnel = @{$accessinfo->{$role}};
5426: }
1.1332 raeburn 5427: }
5428: }
5429: }
5430: if ($curraccess eq 'none') {
5431: next;
5432: } elsif ($curraccess eq 'all') {
5433: push(@possroles,$role);
1.1336 raeburn 5434: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5435: if (grep(/^dh$/,@liveroles)) {
5436: push(@possroles,$role);
5437: } else {
5438: next;
5439: }
1.1336 raeburn 5440: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5441: if (grep(/^da$/,@liveroles)) {
5442: push(@possroles,$role);
5443: } else {
5444: next;
5445: }
1.1332 raeburn 5446: } elsif ($curraccess eq 'status') {
5447: if (@okstatus) {
5448: if (!@statuses) {
5449: if (grep(/^default$/,@okstatus)) {
5450: push(@possroles,$role);
5451: }
5452: } else {
5453: foreach my $status (@okstatus) {
5454: if (grep(/^\Q$status\E$/,@statuses)) {
5455: push(@possroles,$role);
5456: last;
5457: }
5458: }
5459: }
5460: }
5461: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5462: if (grep(/^\Q$user\E$/,@personnel)) {
5463: if ($curraccess eq 'exc') {
5464: push(@possroles,$role);
5465: }
5466: } elsif ($curraccess eq 'inc') {
5467: push(@possroles,$role);
5468: }
5469: }
5470: }
5471: }
5472: }
5473: }
5474: }
5475: }
5476: }
1.1333 raeburn 5477: unless (ref($description) eq 'HASH') {
5478: if (ref($roles_by_num) eq 'ARRAY') {
5479: my %desc;
5480: map { $desc{$_} = $_; } (@{$roles_by_num});
5481: $description = \%desc;
5482: } else {
5483: $description = {};
5484: }
5485: }
5486: return (\@possroles,$description);
1.1332 raeburn 5487: }
5488:
1.399 www 5489: # ----------------------------------------------------- Frontpage Announcements
5490: #
5491: #
5492:
5493: sub postannounce {
5494: my ($server,$text)=@_;
1.844 albertel 5495: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5496: unless ($text=~/\w/) { $text=''; }
5497: return &reply('setannounce:'.&escape($text),$server);
5498: }
5499:
5500: sub getannounce {
1.448 albertel 5501:
1.1359 raeburn 5502: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5503: my $announcement='';
1.800 albertel 5504: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5505: close($fh);
1.399 www 5506: if ($announcement=~/\w/) {
5507: return
5508: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5509: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5510: } else {
5511: return '';
5512: }
5513: } else {
5514: return '';
5515: }
1.351 www 5516: }
1.353 www 5517:
5518: # ---------------------------------------------------------- Course ID routines
5519: # Deal with domain's nohist_courseid.db files
5520: #
5521:
5522: sub courseidput {
1.921 raeburn 5523: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5524: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5525: my $outcome;
5526: if ($caller eq 'timeonly') {
5527: my $cids = '';
5528: foreach my $item (keys(%$storehash)) {
5529: $cids.=&escape($item).'&';
5530: }
5531: $cids=~s/\&$//;
5532: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5533: $coursehome);
5534: } else {
5535: my $items = '';
5536: foreach my $item (keys(%$storehash)) {
5537: $items.= &escape($item).'='.
5538: &freeze_escape($$storehash{$item}).'&';
5539: }
5540: $items=~s/\&$//;
5541: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5542: $coursehome);
1.918 raeburn 5543: }
5544: if ($outcome eq 'unknown_cmd') {
5545: my $what;
5546: foreach my $cid (keys(%$storehash)) {
5547: $what .= &escape($cid).'=';
1.921 raeburn 5548: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5549: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5550: }
5551: $what =~ s/\:$/&/;
5552: }
5553: $what =~ s/\&$//;
5554: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5555: } else {
5556: return $outcome;
5557: }
1.353 www 5558: }
5559:
5560: sub courseiddump {
1.921 raeburn 5561: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5562: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5563: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5564: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5565: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5566: my $as_hash = 1;
5567: my %returnhash;
5568: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5569: my %libserv = &all_library();
5570: foreach my $tryserver (keys(%libserv)) {
5571: if ( ( $hostidflag == 1
5572: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5573: || (!defined($hostidflag)) ) {
5574:
1.918 raeburn 5575: if (($domfilter eq '') ||
5576: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5577: my $rep;
5578: if (grep { $_ eq $tryserver } current_machine_ids()) {
5579: $rep = LONCAPA::Lond::dump_course_id_handler(
5580: join(":", (&host_domain($tryserver), $sincefilter,
5581: &escape($descfilter), &escape($instcodefilter),
5582: &escape($ownerfilter), &escape($coursefilter),
5583: &escape($typefilter), &escape($regexp_ok),
5584: $as_hash, &escape($selfenrollonly),
5585: &escape($catfilter), $showhidden, $caller,
5586: &escape($cloner), &escape($cc_clone), $cloneonly,
5587: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5588: &escape($creationcontext),$domcloner,$hasuniquecode,
5589: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5590: } else {
5591: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5592: $sincefilter.':'.&escape($descfilter).':'.
5593: &escape($instcodefilter).':'.&escape($ownerfilter).
5594: ':'.&escape($coursefilter).':'.&escape($typefilter).
5595: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5596: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5597: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5598: &escape($cc_clone).':'.$cloneonly.':'.
5599: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5600: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5601: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5602: }
5603:
1.918 raeburn 5604: my @pairs=split(/\&/,$rep);
5605: foreach my $item (@pairs) {
5606: my ($key,$value)=split(/\=/,$item,2);
5607: $key = &unescape($key);
5608: next if ($key =~ /^error: 2 /);
5609: my $result = &thaw_unescape($value);
5610: if (ref($result) eq 'HASH') {
5611: $returnhash{$key}=$result;
5612: } else {
1.921 raeburn 5613: my @responses = split(/:/,$value);
5614: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5615: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5616: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5617: }
1.1008 raeburn 5618: }
1.353 www 5619: }
5620: }
5621: }
5622: }
5623: return %returnhash;
5624: }
5625:
1.1055 raeburn 5626: sub courselastaccess {
5627: my ($cdom,$cnum,$hostidref) = @_;
5628: my %returnhash;
5629: if ($cdom && $cnum) {
5630: my $chome = &homeserver($cnum,$cdom);
5631: if ($chome ne 'no_host') {
5632: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5633: &extract_lastaccess(\%returnhash,$rep);
5634: }
5635: } else {
5636: if (!$cdom) { $cdom=''; }
5637: my %libserv = &all_library();
5638: foreach my $tryserver (keys(%libserv)) {
5639: if (ref($hostidref) eq 'ARRAY') {
5640: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5641: }
5642: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5643: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5644: &extract_lastaccess(\%returnhash,$rep);
5645: }
5646: }
5647: }
5648: return %returnhash;
5649: }
5650:
5651: sub extract_lastaccess {
5652: my ($returnhash,$rep) = @_;
5653: if (ref($returnhash) eq 'HASH') {
5654: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5655: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5656: $rep eq '') {
5657: my @pairs=split(/\&/,$rep);
5658: foreach my $item (@pairs) {
5659: my ($key,$value)=split(/\=/,$item,2);
5660: $key = &unescape($key);
5661: next if ($key =~ /^error: 2 /);
5662: $returnhash->{$key} = &thaw_unescape($value);
5663: }
5664: }
5665: }
5666: return;
5667: }
5668:
1.658 raeburn 5669: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5670:
5671: sub dcmailput {
1.685 raeburn 5672: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5673: my $status = &Apache::lonnet::critical(
1.740 www 5674: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5675: &escape($message),$server);
1.662 raeburn 5676: return $status;
5677: }
5678:
1.658 raeburn 5679: sub dcmaildump {
5680: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5681: my %returnhash=();
1.846 albertel 5682:
5683: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5684: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5685: &escape($enddate).':';
5686: my @esc_senders=map { &escape($_)} @$senders;
5687: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5688: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5689: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5690: if (($key) && ($value)) {
5691: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5692: }
5693: }
5694: }
5695: return %returnhash;
5696: }
1.662 raeburn 5697: # ---------------------------------------------------------- Domain roles
5698:
5699: sub get_domain_roles {
5700: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5701: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5702: $startdate = '.';
5703: }
1.1018 raeburn 5704: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5705: $enddate = '.';
5706: }
1.922 raeburn 5707: my $rolelist;
5708: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5709: $rolelist = join('&',@{$roles});
1.922 raeburn 5710: }
1.662 raeburn 5711: my %personnel = ();
1.841 albertel 5712:
5713: my %servers = &get_servers($dom,'library');
5714: foreach my $tryserver (keys(%servers)) {
5715: %{$personnel{$tryserver}}=();
5716: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5717: &escape($startdate).':'.
5718: &escape($enddate).':'.
5719: &escape($rolelist), $tryserver))) {
5720: my ($key,$value) = split(/\=/,$line,2);
5721: if (($key) && ($value)) {
5722: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5723: }
5724: }
1.662 raeburn 5725: }
5726: return %personnel;
5727: }
1.658 raeburn 5728:
1.1332 raeburn 5729: sub get_active_domroles {
5730: my ($dom,$roles) = @_;
5731: return () unless (ref($roles) eq 'ARRAY');
5732: my $now = time;
5733: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5734: my %domroles;
5735: foreach my $server (keys(%dompersonnel)) {
5736: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5737: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5738: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5739: }
5740: }
5741: return %domroles;
5742: }
5743:
1.1057 www 5744: # ----------------------------------------------------------- Interval timing
1.149 www 5745:
1.1153 www 5746: {
5747: # Caches needed for speedup of navmaps
5748: # We don't want to cache this for very long at all (5 seconds at most)
5749: #
5750: # The user for whom we cache
5751: my $cachedkey='';
5752: # The cached times for this user
5753: my %cachedtimes=();
5754: # When this was last done
1.1282 raeburn 5755: my $cachedtime='';
1.1153 www 5756:
5757: sub load_all_first_access {
1.1308 raeburn 5758: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5759: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5760: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5761: (!$ignorecache)) {
1.1154 raeburn 5762: return;
5763: }
5764: $cachedtime=time;
5765: $cachedkey=$uname.':'.$udom;
5766: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5767: }
5768:
1.504 albertel 5769: sub get_first_access {
1.1308 raeburn 5770: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5771: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5772: if ($argsymb) { $symb=$argsymb; }
5773: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5774: if ($argmap) { $map = $argmap; }
1.926 albertel 5775: if ($type eq 'course') {
5776: $res='course';
5777: } elsif ($type eq 'map') {
1.588 albertel 5778: $res=&symbread($map);
5779: } else {
5780: $res=$symb;
5781: }
1.1308 raeburn 5782: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5783: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5784: }
5785:
5786: sub set_first_access {
1.1162 raeburn 5787: my ($type,$interval)=@_;
1.790 albertel 5788: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5789: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5790: if ($type eq 'course') {
5791: $res='course';
5792: } elsif ($type eq 'map') {
1.588 albertel 5793: $res=&symbread($map);
5794: } else {
5795: $res=$symb;
5796: }
1.1153 www 5797: $cachedkey='';
1.1162 raeburn 5798: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5799: if ($firstaccess) {
5800: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5801: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5802: "in $courseid");
1.1386 raeburn 5803: return 'already_set';
5804: } else {
1.1162 raeburn 5805: my $start = time;
5806: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5807: $udom,$uname);
5808: if ($putres eq 'ok') {
5809: &put('timerinterval',{"$courseid\0$res"=>$interval},
5810: $udom,$uname);
5811: &appenv(
5812: {
5813: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5814: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5815: }
5816: );
1.1365 raeburn 5817: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5818: $cachedtimes{"$courseid\0$res"} = $start;
5819: }
1.1386 raeburn 5820: } elsif ($putres ne 'refused') {
5821: &logthis("Result: $putres when attempting to set first access time ".
5822: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5823: }
5824: return $putres;
1.505 albertel 5825: }
5826: return 'already_set';
1.504 albertel 5827: }
1.1153 www 5828: }
1.1282 raeburn 5829:
1.110 www 5830: # --------------------------------------------- Set Expire Date for Spreadsheet
5831:
5832: sub expirespread {
5833: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5834: my $cid=$env{'request.course.id'};
1.110 www 5835: if ($cid) {
5836: my $now=time;
5837: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5838: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5839: $env{'course.'.$cid.'.num'}.
1.110 www 5840: ':nohist_expirationdates:'.
5841: &escape($key).'='.$now,
1.620 albertel 5842: $env{'course.'.$cid.'.home'})
1.110 www 5843: }
5844: return 'ok';
1.14 www 5845: }
5846:
1.109 www 5847: # ----------------------------------------------------- Devalidate Spreadsheets
5848:
5849: sub devalidate {
1.325 www 5850: my ($symb,$uname,$udom)=@_;
1.620 albertel 5851: my $cid=$env{'request.course.id'};
1.109 www 5852: if ($cid) {
1.391 matthew 5853: # delete the stored spreadsheets for
5854: # - the student level sheet of this user in course's homespace
5855: # - the assessment level sheet for this resource
5856: # for this user in user's homespace
1.553 albertel 5857: # - current conditional state info
1.325 www 5858: my $key=$uname.':'.$udom.':';
1.109 www 5859: my $status=
1.299 matthew 5860: &del('nohist_calculatedsheets',
1.391 matthew 5861: [$key.'studentcalc:'],
1.620 albertel 5862: $env{'course.'.$cid.'.domain'},
5863: $env{'course.'.$cid.'.num'})
1.133 albertel 5864: .' '.
5865: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5866: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5867: unless ($status eq 'ok ok') {
5868: &logthis('Could not devalidate spreadsheet '.
1.325 www 5869: $uname.' at '.$udom.' for '.
1.109 www 5870: $symb.': '.$status);
1.133 albertel 5871: }
1.553 albertel 5872: &delenv('user.state.'.$cid);
1.109 www 5873: }
5874: }
5875:
1.265 albertel 5876: sub get_scalar {
5877: my ($string,$end) = @_;
5878: my $value;
5879: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5880: $value = $1;
5881: } elsif ($$string =~ s/^([^&]*?)&//) {
5882: $value = $1;
5883: }
5884: return &unescape($value);
5885: }
5886:
5887: sub array2str {
5888: my (@array) = @_;
5889: my $result=&arrayref2str(\@array);
5890: $result=~s/^__ARRAY_REF__//;
5891: $result=~s/__END_ARRAY_REF__$//;
5892: return $result;
5893: }
5894:
1.204 albertel 5895: sub arrayref2str {
5896: my ($arrayref) = @_;
1.265 albertel 5897: my $result='__ARRAY_REF__';
1.204 albertel 5898: foreach my $elem (@$arrayref) {
1.265 albertel 5899: if(ref($elem) eq 'ARRAY') {
5900: $result.=&arrayref2str($elem).'&';
5901: } elsif(ref($elem) eq 'HASH') {
5902: $result.=&hashref2str($elem).'&';
5903: } elsif(ref($elem)) {
5904: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5905: } else {
5906: $result.=&escape($elem).'&';
5907: }
5908: }
5909: $result=~s/\&$//;
1.265 albertel 5910: $result .= '__END_ARRAY_REF__';
1.204 albertel 5911: return $result;
5912: }
5913:
1.168 albertel 5914: sub hash2str {
1.204 albertel 5915: my (%hash) = @_;
5916: my $result=&hashref2str(\%hash);
1.265 albertel 5917: $result=~s/^__HASH_REF__//;
5918: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5919: return $result;
5920: }
5921:
5922: sub hashref2str {
5923: my ($hashref)=@_;
1.265 albertel 5924: my $result='__HASH_REF__';
1.800 albertel 5925: foreach my $key (sort(keys(%$hashref))) {
5926: if (ref($key) eq 'ARRAY') {
5927: $result.=&arrayref2str($key).'=';
5928: } elsif (ref($key) eq 'HASH') {
5929: $result.=&hashref2str($key).'=';
5930: } elsif (ref($key)) {
1.265 albertel 5931: $result.='=';
1.800 albertel 5932: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5933: } else {
1.1132 raeburn 5934: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5935: }
5936:
1.800 albertel 5937: if(ref($hashref->{$key}) eq 'ARRAY') {
5938: $result.=&arrayref2str($hashref->{$key}).'&';
5939: } elsif(ref($hashref->{$key}) eq 'HASH') {
5940: $result.=&hashref2str($hashref->{$key}).'&';
5941: } elsif(ref($hashref->{$key})) {
1.265 albertel 5942: $result.='&';
1.800 albertel 5943: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5944: } else {
1.800 albertel 5945: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5946: }
5947: }
1.168 albertel 5948: $result=~s/\&$//;
1.265 albertel 5949: $result .= '__END_HASH_REF__';
1.168 albertel 5950: return $result;
5951: }
5952:
5953: sub str2hash {
1.265 albertel 5954: my ($string)=@_;
5955: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5956: return %$hash;
5957: }
5958:
5959: sub str2hashref {
1.168 albertel 5960: my ($string) = @_;
1.265 albertel 5961:
5962: my %hash;
5963:
5964: if($string !~ /^__HASH_REF__/) {
5965: if (! ($string eq '' || !defined($string))) {
5966: $hash{'error'}='Not hash reference';
5967: }
5968: return (\%hash, $string);
5969: }
5970:
5971: $string =~ s/^__HASH_REF__//;
5972:
5973: while($string !~ /^__END_HASH_REF__/) {
5974: #key
5975: my $key='';
5976: if($string =~ /^__HASH_REF__/) {
5977: ($key, $string)=&str2hashref($string);
5978: if(defined($key->{'error'})) {
5979: $hash{'error'}='Bad data';
5980: return (\%hash, $string);
5981: }
5982: } elsif($string =~ /^__ARRAY_REF__/) {
5983: ($key, $string)=&str2arrayref($string);
5984: if($key->[0] eq 'Array reference error') {
5985: $hash{'error'}='Bad data';
5986: return (\%hash, $string);
5987: }
5988: } else {
5989: $string =~ s/^(.*?)=//;
1.267 albertel 5990: $key=&unescape($1);
1.265 albertel 5991: }
5992: $string =~ s/^=//;
5993:
5994: #value
5995: my $value='';
5996: if($string =~ /^__HASH_REF__/) {
5997: ($value, $string)=&str2hashref($string);
5998: if(defined($value->{'error'})) {
5999: $hash{'error'}='Bad data';
6000: return (\%hash, $string);
6001: }
6002: } elsif($string =~ /^__ARRAY_REF__/) {
6003: ($value, $string)=&str2arrayref($string);
6004: if($value->[0] eq 'Array reference error') {
6005: $hash{'error'}='Bad data';
6006: return (\%hash, $string);
6007: }
6008: } else {
6009: $value=&get_scalar(\$string,'__END_HASH_REF__');
6010: }
6011: $string =~ s/^&//;
6012:
6013: $hash{$key}=$value;
1.204 albertel 6014: }
1.265 albertel 6015:
6016: $string =~ s/^__END_HASH_REF__//;
6017:
6018: return (\%hash, $string);
1.204 albertel 6019: }
6020:
6021: sub str2array {
1.265 albertel 6022: my ($string)=@_;
6023: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6024: return @$array;
6025: }
6026:
6027: sub str2arrayref {
1.204 albertel 6028: my ($string) = @_;
1.265 albertel 6029: my @array;
6030:
6031: if($string !~ /^__ARRAY_REF__/) {
6032: if (! ($string eq '' || !defined($string))) {
6033: $array[0]='Array reference error';
6034: }
6035: return (\@array, $string);
6036: }
6037:
6038: $string =~ s/^__ARRAY_REF__//;
6039:
6040: while($string !~ /^__END_ARRAY_REF__/) {
6041: my $value='';
6042: if($string =~ /^__HASH_REF__/) {
6043: ($value, $string)=&str2hashref($string);
6044: if(defined($value->{'error'})) {
6045: $array[0] ='Array reference error';
6046: return (\@array, $string);
6047: }
6048: } elsif($string =~ /^__ARRAY_REF__/) {
6049: ($value, $string)=&str2arrayref($string);
6050: if($value->[0] eq 'Array reference error') {
6051: $array[0] ='Array reference error';
6052: return (\@array, $string);
6053: }
6054: } else {
6055: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6056: }
6057: $string =~ s/^&//;
6058:
6059: push(@array, $value);
1.191 harris41 6060: }
1.265 albertel 6061:
6062: $string =~ s/^__END_ARRAY_REF__//;
6063:
6064: return (\@array, $string);
1.168 albertel 6065: }
6066:
1.167 albertel 6067: # -------------------------------------------------------------------Temp Store
6068:
1.168 albertel 6069: sub tmpreset {
6070: my ($symb,$namespace,$domain,$stuname) = @_;
6071: if (!$symb) {
6072: $symb=&symbread();
1.620 albertel 6073: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6074: }
6075: $symb=escape($symb);
6076:
1.620 albertel 6077: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6078: $namespace=~s/\//\_/g;
6079: $namespace=~s/\W//g;
6080:
1.620 albertel 6081: if (!$domain) { $domain=$env{'user.domain'}; }
6082: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6083: if ($domain eq 'public' && $stuname eq 'public') {
6084: $stuname=$ENV{'REMOTE_ADDR'};
6085: }
1.1117 foxr 6086: my $path=LONCAPA::tempdir();
1.168 albertel 6087: my %hash;
6088: if (tie(%hash,'GDBM_File',
6089: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6090: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6091: foreach my $key (keys(%hash)) {
1.180 albertel 6092: if ($key=~ /:$symb/) {
1.168 albertel 6093: delete($hash{$key});
6094: }
6095: }
6096: }
6097: }
6098:
1.167 albertel 6099: sub tmpstore {
1.168 albertel 6100: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6101:
6102: if (!$symb) {
6103: $symb=&symbread();
1.620 albertel 6104: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6105: }
6106: $symb=escape($symb);
6107:
6108: if (!$namespace) {
6109: # I don't think we would ever want to store this for a course.
6110: # it seems this will only be used if we don't have a course.
1.620 albertel 6111: #$namespace=$env{'request.course.id'};
1.168 albertel 6112: #if (!$namespace) {
1.620 albertel 6113: $namespace=$env{'request.state'};
1.168 albertel 6114: #}
6115: }
6116: $namespace=~s/\//\_/g;
6117: $namespace=~s/\W//g;
1.620 albertel 6118: if (!$domain) { $domain=$env{'user.domain'}; }
6119: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6120: if ($domain eq 'public' && $stuname eq 'public') {
6121: $stuname=$ENV{'REMOTE_ADDR'};
6122: }
1.168 albertel 6123: my $now=time;
6124: my %hash;
1.1117 foxr 6125: my $path=LONCAPA::tempdir();
1.168 albertel 6126: if (tie(%hash,'GDBM_File',
6127: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6128: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6129: $hash{"version:$symb"}++;
6130: my $version=$hash{"version:$symb"};
6131: my $allkeys='';
6132: foreach my $key (keys(%$storehash)) {
6133: $allkeys.=$key.':';
1.591 albertel 6134: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6135: }
6136: $hash{"$version:$symb:timestamp"}=$now;
6137: $allkeys.='timestamp';
6138: $hash{"$version:keys:$symb"}=$allkeys;
6139: if (untie(%hash)) {
6140: return 'ok';
6141: } else {
6142: return "error:$!";
6143: }
6144: } else {
6145: return "error:$!";
6146: }
6147: }
1.167 albertel 6148:
1.168 albertel 6149: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6150:
1.168 albertel 6151: sub tmprestore {
6152: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6153:
1.168 albertel 6154: if (!$symb) {
6155: $symb=&symbread();
1.620 albertel 6156: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6157: }
6158: $symb=escape($symb);
6159:
1.620 albertel 6160: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6161:
1.620 albertel 6162: if (!$domain) { $domain=$env{'user.domain'}; }
6163: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6164: if ($domain eq 'public' && $stuname eq 'public') {
6165: $stuname=$ENV{'REMOTE_ADDR'};
6166: }
1.168 albertel 6167: my %returnhash;
6168: $namespace=~s/\//\_/g;
6169: $namespace=~s/\W//g;
6170: my %hash;
1.1117 foxr 6171: my $path=LONCAPA::tempdir();
1.168 albertel 6172: if (tie(%hash,'GDBM_File',
6173: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6174: &GDBM_READER(),0640)) {
1.168 albertel 6175: my $version=$hash{"version:$symb"};
6176: $returnhash{'version'}=$version;
6177: my $scope;
6178: for ($scope=1;$scope<=$version;$scope++) {
6179: my $vkeys=$hash{"$scope:keys:$symb"};
6180: my @keys=split(/:/,$vkeys);
6181: my $key;
6182: $returnhash{"$scope:keys"}=$vkeys;
6183: foreach $key (@keys) {
1.591 albertel 6184: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6185: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6186: }
6187: }
1.168 albertel 6188: if (!(untie(%hash))) {
6189: return "error:$!";
6190: }
6191: } else {
6192: return "error:$!";
6193: }
6194: return %returnhash;
1.167 albertel 6195: }
6196:
1.9 www 6197: # ----------------------------------------------------------------------- Store
6198:
6199: sub store {
1.1269 raeburn 6200: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6201: my $home='';
6202:
1.168 albertel 6203: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6204:
1.213 www 6205: $symb=&symbclean($symb);
1.122 albertel 6206: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6207:
1.620 albertel 6208: if (!$domain) { $domain=$env{'user.domain'}; }
6209: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6210:
6211: &devalidate($symb,$stuname,$domain);
1.109 www 6212:
6213: $symb=escape($symb);
1.187 www 6214: if (!$namespace) {
1.620 albertel 6215: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6216: return '';
6217: }
6218: }
1.620 albertel 6219: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6220:
6221: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6222: $$storehash{'host'}=$perlvar{'lonHostID'};
6223:
1.12 www 6224: my $namevalue='';
1.800 albertel 6225: foreach my $key (keys(%$storehash)) {
6226: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6227: }
1.12 www 6228: $namevalue=~s/\&$//;
1.187 www 6229: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6230: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6231: }
6232:
1.47 www 6233: # -------------------------------------------------------------- Critical Store
6234:
6235: sub cstore {
1.1269 raeburn 6236: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6237: my $home='';
6238:
1.168 albertel 6239: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6240:
1.213 www 6241: $symb=&symbclean($symb);
1.122 albertel 6242: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6243:
1.620 albertel 6244: if (!$domain) { $domain=$env{'user.domain'}; }
6245: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6246:
6247: &devalidate($symb,$stuname,$domain);
1.109 www 6248:
6249: $symb=escape($symb);
1.187 www 6250: if (!$namespace) {
1.620 albertel 6251: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6252: return '';
6253: }
6254: }
1.620 albertel 6255: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6256:
6257: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
6258: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6259:
1.47 www 6260: my $namevalue='';
1.800 albertel 6261: foreach my $key (keys(%$storehash)) {
6262: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6263: }
1.47 www 6264: $namevalue=~s/\&$//;
1.187 www 6265: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6266: return critical
1.1269 raeburn 6267: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6268: }
6269:
1.9 www 6270: # --------------------------------------------------------------------- Restore
6271:
6272: sub restore {
1.124 www 6273: my ($symb,$namespace,$domain,$stuname) = @_;
6274: my $home='';
6275:
1.168 albertel 6276: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6277:
1.122 albertel 6278: if (!$symb) {
1.1224 raeburn 6279: return if ($namespace eq 'courserequests');
6280: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6281: } else {
1.1224 raeburn 6282: unless ($namespace eq 'courserequests') {
6283: $symb=&escape(&symbclean($symb));
6284: }
1.122 albertel 6285: }
1.188 www 6286: if (!$namespace) {
1.620 albertel 6287: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6288: return '';
6289: }
6290: }
1.620 albertel 6291: if (!$domain) { $domain=$env{'user.domain'}; }
6292: if (!$stuname) { $stuname=$env{'user.name'}; }
6293: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6294: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6295:
1.12 www 6296: my %returnhash=();
1.800 albertel 6297: foreach my $line (split(/\&/,$answer)) {
6298: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6299: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6300: }
1.75 www 6301: my $version;
6302: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6303: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6304: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6305: }
1.75 www 6306: }
1.13 www 6307: return %returnhash;
1.34 www 6308: }
6309:
6310: # ---------------------------------------------------------- Course Description
1.1118 foxr 6311: #
6312: #
1.34 www 6313:
6314: sub coursedescription {
1.731 albertel 6315: my ($courseid,$args)=@_;
1.34 www 6316: $courseid=~s/^\///;
1.49 www 6317: $courseid=~s/\_/\//g;
1.34 www 6318: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6319: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6320: my $normalid=$cdomain.'_'.$cnum;
6321: # need to always cache even if we get errors otherwise we keep
6322: # trying and trying and trying to get the course description.
6323: my %envhash=();
6324: my %returnhash=();
1.731 albertel 6325:
6326: my $expiretime=600;
6327: if ($env{'request.course.id'} eq $normalid) {
6328: $expiretime=120;
6329: }
6330:
6331: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6332: if (!$args->{'freshen_cache'}
6333: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6334: foreach my $key (keys(%env)) {
6335: next if ($key !~ /^\Q$prefix\E(.*)/);
6336: my ($setting) = $1;
6337: $returnhash{$setting} = $env{$key};
6338: }
6339: return %returnhash;
6340: }
6341:
1.1118 foxr 6342: # get the data again
6343:
1.731 albertel 6344: if (!$args->{'one_time'}) {
6345: $envhash{'course.'.$normalid.'.last_cache'}=time;
6346: }
1.811 albertel 6347:
1.34 www 6348: if ($chome ne 'no_host') {
1.302 albertel 6349: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6350: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6351: my $username = $env{'user.name'}; # Defult username
6352: if(defined $args->{'user'}) {
6353: $username = $args->{'user'};
6354: }
1.129 albertel 6355: $returnhash{'home'}= $chome;
6356: $returnhash{'domain'} = $cdomain;
6357: $returnhash{'num'} = $cnum;
1.741 raeburn 6358: if (!defined($returnhash{'type'})) {
6359: $returnhash{'type'} = 'Course';
6360: }
1.130 albertel 6361: while (my ($name,$value) = each %returnhash) {
1.53 www 6362: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6363: }
1.270 www 6364: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6365: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6366: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6367: $envhash{'course.'.$normalid.'.home'}=$chome;
6368: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6369: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6370: }
6371: }
1.731 albertel 6372: if (!$args->{'one_time'}) {
1.949 raeburn 6373: &appenv(\%envhash);
1.731 albertel 6374: }
1.302 albertel 6375: return %returnhash;
1.461 www 6376: }
6377:
1.1080 raeburn 6378: sub update_released_required {
6379: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6380: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6381: $cid = $env{'request.course.id'};
6382: $cdom = $env{'course.'.$cid.'.domain'};
6383: $cnum = $env{'course.'.$cid.'.num'};
6384: $chome = $env{'course.'.$cid.'.home'};
6385: }
6386: if ($needsrelease) {
6387: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6388: my $needsupdate;
6389: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6390: $needsupdate = 1;
6391: } else {
6392: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6393: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6394: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6395: $needsupdate = 1;
6396: }
6397: }
6398: if ($needsupdate) {
6399: my %needshash = (
6400: 'internal.releaserequired' => $needsrelease,
6401: );
6402: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6403: if ($putresult eq 'ok') {
6404: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6405: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6406: if (ref($crsinfo{$cid}) eq 'HASH') {
6407: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6408: &courseidput($cdom,\%crsinfo,$chome,'notime');
6409: }
6410: }
6411: }
6412: }
6413: return;
6414: }
6415:
1.461 www 6416: # -------------------------------------------------See if a user is privileged
6417:
6418: sub privileged {
1.1219 raeburn 6419: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6420: my $now = time;
1.1219 raeburn 6421: my $roles;
6422: if (ref($possroles) eq 'ARRAY') {
6423: $roles = $possroles;
6424: } else {
6425: $roles = ['dc','su'];
6426: }
6427: if (ref($possdomains) eq 'ARRAY') {
6428: my %privileged = &privileged_by_domain($possdomains,$roles);
6429: foreach my $dom (@{$possdomains}) {
6430: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6431: (ref($privileged{$dom}) eq 'HASH')) {
6432: foreach my $role (@{$roles}) {
6433: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6434: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6435: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6436: return 1 unless (($end && $end < $now) ||
6437: ($start && $start > $now));
6438: }
6439: }
6440: }
6441: }
6442: }
6443: } else {
6444: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6445: my $now = time;
1.1170 droeschl 6446:
1.1275 musolffc 6447: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6448: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6449: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6450: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6451: or ($tstart && $tstart > $now);
1.1170 droeschl 6452: }
1.1219 raeburn 6453: }
6454: }
6455: return 0;
6456: }
1.1170 droeschl 6457:
1.1219 raeburn 6458: sub privileged_by_domain {
6459: my ($domains,$roles) = @_;
6460: my %privileged = ();
6461: my $cachetime = 60*60*24;
6462: my $now = time;
6463: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6464: return %privileged;
6465: }
6466: foreach my $dom (@{$domains}) {
6467: next if (ref($privileged{$dom}) eq 'HASH');
6468: my $needroles;
6469: foreach my $role (@{$roles}) {
6470: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6471: if (defined($cached)) {
6472: if (ref($result) eq 'HASH') {
6473: $privileged{$dom}{$role} = $result;
6474: }
6475: } else {
6476: $needroles = 1;
6477: }
6478: }
6479: if ($needroles) {
6480: my %dompersonnel = &get_domain_roles($dom,$roles);
6481: $privileged{$dom} = {};
6482: foreach my $server (keys(%dompersonnel)) {
6483: if (ref($dompersonnel{$server}) eq 'HASH') {
6484: foreach my $item (keys(%{$dompersonnel{$server}})) {
6485: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6486: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6487: next if ($end && $end < $now);
6488: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6489: $dompersonnel{$server}{$item};
6490: }
6491: }
6492: }
6493: if (ref($privileged{$dom}) eq 'HASH') {
6494: foreach my $role (@{$roles}) {
6495: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6496: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6497: } else {
6498: my %hash = ();
6499: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6500: }
6501: }
6502: }
6503: }
6504: }
6505: return %privileged;
1.9 www 6506: }
1.1 albertel 6507:
1.103 harris41 6508: # -------------------------------------------------------- Get user privileges
1.11 www 6509:
6510: sub rolesinit {
1.1169 droeschl 6511: my ($domain, $username) = @_;
6512: my %userroles = ('user.login.time' => time);
6513: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6514:
6515: # firstaccess and timerinterval are related to timed maps/resources.
6516: # also, blocking can be triggered by an activating timer
6517: # it's saved in the user's %env.
6518: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6519: my %timerinterval = &dump('timerinterval', $domain, $username);
6520: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6521: %timerintchk, %timerintenv);
6522:
1.1162 raeburn 6523: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6524: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6525: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6526: }
1.1169 droeschl 6527:
1.1162 raeburn 6528: foreach my $key (keys(%timerinterval)) {
6529: my ($cid,$rest) = split(/\0/,$key);
6530: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6531: }
1.1169 droeschl 6532:
1.11 www 6533: my %allroles=();
1.1162 raeburn 6534: my %allgroups=();
1.11 www 6535:
1.1274 raeburn 6536: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6537: my $role = $rolesdump{$area};
6538: $area =~ s/\_\w\w$//;
6539:
6540: my ($trole, $tend, $tstart, $group_privs);
6541:
6542: if ($role =~ /^cr/) {
6543: # Custom role, defined by a user
6544: # e.g., user.role.cr/msu/smith/mynewrole
6545: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6546: $trole = $1;
6547: ($tend, $tstart) = split('_', $2);
6548: } else {
6549: $trole = $role;
6550: }
6551: } elsif ($role =~ m|^gr/|) {
6552: # Role of member in a group, defined within a course/community
6553: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6554: ($trole, $tend, $tstart) = split(/_/, $role);
6555: next if $tstart eq '-1';
6556: ($trole, $group_privs) = split(/\//, $trole);
6557: $group_privs = &unescape($group_privs);
6558: } else {
6559: # Just a normal role, defined in roles.tab
6560: ($trole, $tend, $tstart) = split(/_/,$role);
6561: }
6562:
6563: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6564: $username);
6565: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6566:
6567: # role expired or not available yet?
6568: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6569: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6570:
6571: next if $area eq '' or $trole eq '';
6572:
6573: my $spec = "$trole.$area";
6574: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6575:
6576: if ($trole =~ /^cr\//) {
6577: # Custom role, defined by a user
6578: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6579: } elsif ($trole eq 'gr') {
6580: # Role of a member in a group, defined within a course/community
6581: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6582: next;
6583: } else {
6584: # Normal role, defined in roles.tab
6585: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6586: }
6587:
6588: my $cid = $tdomain.'_'.$trest;
6589: unless ($firstaccchk{$cid}) {
6590: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6591: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6592: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6593: $coursetimerstarts{$cid}{$item};
6594: }
6595: }
6596: $firstaccchk{$cid} = 1;
6597: }
6598: unless ($timerintchk{$cid}) {
6599: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6600: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6601: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6602: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6603: }
1.12 www 6604: }
1.1169 droeschl 6605: $timerintchk{$cid} = 1;
1.191 harris41 6606: }
1.11 www 6607: }
1.1169 droeschl 6608:
1.1341 raeburn 6609: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6610: \%allroles, \%allgroups);
1.1169 droeschl 6611: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6612: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6613:
1.1162 raeburn 6614: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6615: }
6616:
1.567 raeburn 6617: sub set_arearole {
1.1215 raeburn 6618: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6619: unless ($nolog) {
1.567 raeburn 6620: # log the associated role with the area
1.1215 raeburn 6621: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6622: }
1.743 albertel 6623: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6624: }
6625:
6626: sub custom_roleprivs {
6627: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6628: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6629: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6630: if (&hostname($homsvr) ne '') {
1.567 raeburn 6631: my ($rdummy,$roledef)=
6632: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6633: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6634: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6635: if (defined($syspriv)) {
1.1043 raeburn 6636: if ($trest =~ /^$match_community$/) {
6637: $syspriv =~ s/bre\&S//;
6638: }
1.567 raeburn 6639: $$allroles{'cm./'}.=':'.$syspriv;
6640: $$allroles{$spec.'./'}.=':'.$syspriv;
6641: }
6642: if ($tdomain ne '') {
6643: if (defined($dompriv)) {
6644: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6645: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6646: }
6647: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6648: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6649: my $rolename = $1;
6650: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6651: }
1.567 raeburn 6652: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6653: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6654: }
6655: }
6656: }
6657: }
6658: }
6659:
1.1332 raeburn 6660: sub course_adhocrole_privs {
6661: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6662: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6663: if ($overrides{"internal.adhocpriv.$rolename"}) {
6664: my (%currprivs,%storeprivs);
6665: foreach my $item (split(/:/,$coursepriv)) {
6666: my ($priv,$restrict) = split(/\&/,$item);
6667: $currprivs{$priv} = $restrict;
6668: }
6669: my (%possadd,%possremove,%full);
6670: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6671: my ($priv,$restrict)=split(/\&/,$item);
6672: $full{$priv} = $restrict;
6673: }
6674: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6675: next if ($item eq '');
6676: my ($rule,$rest) = split(/=/,$item);
6677: next unless (($rule eq 'off') || ($rule eq 'on'));
6678: foreach my $priv (split(/:/,$rest)) {
6679: if ($priv ne '') {
6680: if ($rule eq 'off') {
6681: $possremove{$priv} = 1;
6682: } else {
6683: $possadd{$priv} = 1;
6684: }
6685: }
6686: }
6687: }
6688: foreach my $priv (sort(keys(%full))) {
6689: if (exists($currprivs{$priv})) {
6690: unless (exists($possremove{$priv})) {
6691: $storeprivs{$priv} = $currprivs{$priv};
6692: }
6693: } elsif (exists($possadd{$priv})) {
6694: $storeprivs{$priv} = $full{$priv};
6695: }
6696: }
6697: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6698: }
6699: return $coursepriv;
6700: }
6701:
1.678 raeburn 6702: sub group_roleprivs {
6703: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6704: my $access = 1;
6705: my $now = time;
6706: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6707: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6708: if ($access) {
1.811 albertel 6709: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6710: $$allgroups{$course}{$group} .=':'.$group_privs;
6711: }
6712: }
1.567 raeburn 6713:
6714: sub standard_roleprivs {
6715: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6716: if (defined($pr{$trole.':s'})) {
6717: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6718: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6719: }
6720: if ($tdomain ne '') {
6721: if (defined($pr{$trole.':d'})) {
6722: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6723: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6724: }
6725: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6726: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6727: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6728: }
6729: }
6730: }
6731:
6732: sub set_userprivs {
1.1064 raeburn 6733: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6734: my $author=0;
6735: my $adv=0;
1.1341 raeburn 6736: my $rar=0;
1.678 raeburn 6737: my %grouproles = ();
6738: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6739: my @groupkeys;
1.1000 raeburn 6740: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6741: push(@groupkeys,$role);
6742: }
6743: if (ref($groups_roles) eq 'HASH') {
6744: foreach my $key (keys(%{$groups_roles})) {
6745: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6746: push(@groupkeys,$key);
6747: }
6748: }
6749: }
6750: if (@groupkeys > 0) {
6751: foreach my $role (@groupkeys) {
6752: my ($trole,$area,$sec,$extendedarea);
6753: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6754: $trole = $1;
6755: $area = $2;
6756: $sec = $3;
6757: $extendedarea = $area.$sec;
6758: if (exists($$allgroups{$area})) {
6759: foreach my $group (keys(%{$$allgroups{$area}})) {
6760: my $spec = $trole.'.'.$extendedarea;
6761: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6762: $$allgroups{$area}{$group};
1.1064 raeburn 6763: }
1.678 raeburn 6764: }
6765: }
6766: }
6767: }
6768: }
1.800 albertel 6769: foreach my $group (keys(%grouproles)) {
6770: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6771: }
1.800 albertel 6772: foreach my $role (keys(%{$allroles})) {
6773: my %thesepriv;
1.941 raeburn 6774: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6775: foreach my $item (split(/:/,$$allroles{$role})) {
6776: if ($item ne '') {
6777: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6778: if ($restrictions eq '') {
6779: $thesepriv{$privilege}='F';
6780: } elsif ($thesepriv{$privilege} ne 'F') {
6781: $thesepriv{$privilege}.=$restrictions;
6782: }
6783: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6784: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6785: }
6786: }
6787: my $thesestr='';
1.1104 raeburn 6788: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6789: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6790: }
6791: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6792: }
1.1341 raeburn 6793: return ($author,$adv,$rar);
1.567 raeburn 6794: }
6795:
1.994 raeburn 6796: sub role_status {
1.1104 raeburn 6797: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6798: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6799: my ($one,$two) = split(m{\./},$rolekey,2);
6800: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6801: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6802: $$where = '/'.$two;
1.994 raeburn 6803: $$trolecode=$$role.'.'.$$where;
6804: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6805: $$tstatus='is';
1.1104 raeburn 6806: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6807: $$tstatus='future';
1.1034 raeburn 6808: if ($$tstart<$now) {
6809: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6810: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6811: my (%allroles,%allgroups,$group_privs,
6812: %groups_roles,@rolecodes);
1.1002 raeburn 6813: my %userroles = (
6814: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6815: );
1.1064 raeburn 6816: @rolecodes = ('cm');
1.1002 raeburn 6817: my $spec=$$role.'.'.$$where;
6818: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6819: if ($$role =~ /^cr\//) {
6820: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6821: push(@rolecodes,'cr');
1.1002 raeburn 6822: } elsif ($$role eq 'gr') {
1.1064 raeburn 6823: push(@rolecodes,$$role);
1.1002 raeburn 6824: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6825: $env{'user.name'});
1.1064 raeburn 6826: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6827: (undef,my $group_privs) = split(/\//,$trole);
6828: $group_privs = &unescape($group_privs);
6829: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6830: 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 6831: &get_groups_roles($tdomain,$trest,
6832: \%course_roles,\@rolecodes,
6833: \%groups_roles);
1.1002 raeburn 6834: } else {
1.1064 raeburn 6835: push(@rolecodes,$$role);
1.1002 raeburn 6836: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6837: }
1.1341 raeburn 6838: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6839: \%groups_roles);
1.1064 raeburn 6840: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6841: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6842: }
6843: }
1.1034 raeburn 6844: $$tstatus = 'is';
1.1002 raeburn 6845: }
1.994 raeburn 6846: }
6847: if ($$tend) {
1.1104 raeburn 6848: if ($$tend<$update) {
1.994 raeburn 6849: $$tstatus='expired';
6850: } elsif ($$tend<$now) {
6851: $$tstatus='will_not';
6852: }
6853: }
6854: }
6855: }
6856: }
6857:
1.1104 raeburn 6858: sub get_groups_roles {
6859: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6860: return unless((ref($cdom_courseroles) eq 'HASH') &&
6861: (ref($rolecodes) eq 'ARRAY') &&
6862: (ref($groups_roles) eq 'HASH'));
6863: if (keys(%{$cdom_courseroles}) > 0) {
6864: my ($cnum) = ($rest =~ /^($match_courseid)/);
6865: if ($cdom ne '' && $cnum ne '') {
6866: foreach my $key (keys(%{$cdom_courseroles})) {
6867: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6868: my $crsrole = $1;
6869: my $crssec = $2;
6870: if ($crsrole =~ /^cr/) {
6871: unless (grep(/^cr$/,@{$rolecodes})) {
6872: push(@{$rolecodes},'cr');
6873: }
6874: } else {
6875: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6876: push(@{$rolecodes},$crsrole);
6877: }
6878: }
6879: my $rolekey = "$crsrole./$cdom/$cnum";
6880: if ($crssec ne '') {
6881: $rolekey .= "/$crssec";
6882: }
6883: $rolekey .= './';
6884: $groups_roles->{$rolekey} = $rolecodes;
6885: }
6886: }
6887: }
6888: }
6889: return;
6890: }
6891:
6892: sub delete_env_groupprivs {
6893: my ($where,$courseroles,$possroles) = @_;
6894: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6895: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6896: unless (ref($courseroles->{$udom}) eq 'HASH') {
6897: %{$courseroles->{$udom}} =
6898: &get_my_roles('','','userroles',['active'],
6899: $possroles,[$udom],1);
6900: }
6901: if (ref($courseroles->{$udom}) eq 'HASH') {
6902: foreach my $item (keys(%{$courseroles->{$udom}})) {
6903: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6904: my $area = '/'.$cdom.'/'.$cnum;
6905: my $privkey = "user.priv.$crsrole.$area";
6906: if ($crssec ne '') {
6907: $privkey .= '/'.$crssec;
6908: }
6909: $privkey .= ".$area/$group";
6910: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6911: }
6912: }
6913: return;
6914: }
6915:
1.994 raeburn 6916: sub check_adhoc_privs {
1.1329 raeburn 6917: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6918: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6919: if ($sec) {
6920: $cckey .= '/'.$sec;
6921: }
1.1185 raeburn 6922: my $setprivs;
1.994 raeburn 6923: if ($env{$cckey}) {
6924: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6925: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6926: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6927: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6928: $setprivs = 1;
1.994 raeburn 6929: }
6930: } else {
1.1330 raeburn 6931: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6932: $setprivs = 1;
1.994 raeburn 6933: }
1.1185 raeburn 6934: return $setprivs;
1.994 raeburn 6935: }
6936:
6937: sub set_adhoc_privileges {
1.1326 raeburn 6938: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6939: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6940: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6941: if ($sec ne '') {
6942: $area .= '/'.$sec;
6943: }
1.994 raeburn 6944: my $spec = $role.'.'.$area;
6945: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6946: $env{'user.name'},1);
1.1326 raeburn 6947: my %rolehash = ();
1.1332 raeburn 6948: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6949: my $rolename = $1;
1.1326 raeburn 6950: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6951: my %domdef = &get_domain_defaults($dcdom);
6952: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6953: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6954: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6955: }
6956: }
1.1326 raeburn 6957: } else {
6958: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6959: }
1.1341 raeburn 6960: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6961: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6962: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 6963: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
6964: ($caller eq 'tiny')) {
1.1088 raeburn 6965: &appenv( {'request.role' => $spec,
6966: 'request.role.domain' => $dcdom,
1.1332 raeburn 6967: 'request.course.sec' => $sec,
1.1088 raeburn 6968: }
6969: );
6970: my $tadv=0;
6971: if (&allowed('adv') eq 'F') { $tadv=1; }
6972: &appenv({'request.role.adv' => $tadv});
6973: }
1.994 raeburn 6974: }
6975:
1.12 www 6976: # --------------------------------------------------------------- get interface
6977:
6978: sub get {
1.131 albertel 6979: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6980: my $items='';
1.800 albertel 6981: foreach my $item (@$storearr) {
6982: $items.=&escape($item).'&';
1.191 harris41 6983: }
1.12 www 6984: $items=~s/\&$//;
1.620 albertel 6985: if (!$udomain) { $udomain=$env{'user.domain'}; }
6986: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6987: my $uhome=&homeserver($uname,$udomain);
6988:
1.133 albertel 6989: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6990: my @pairs=split(/\&/,$rep);
1.273 albertel 6991: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6992: return @pairs;
6993: }
1.15 www 6994: my %returnhash=();
1.42 www 6995: my $i=0;
1.800 albertel 6996: foreach my $item (@$storearr) {
6997: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6998: $i++;
1.191 harris41 6999: }
1.15 www 7000: return %returnhash;
1.27 www 7001: }
7002:
7003: # --------------------------------------------------------------- del interface
7004:
7005: sub del {
1.133 albertel 7006: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7007: my $items='';
1.800 albertel 7008: foreach my $item (@$storearr) {
7009: $items.=&escape($item).'&';
1.191 harris41 7010: }
1.984 neumanie 7011:
1.27 www 7012: $items=~s/\&$//;
1.620 albertel 7013: if (!$udomain) { $udomain=$env{'user.domain'}; }
7014: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7015: my $uhome=&homeserver($uname,$udomain);
7016: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7017: }
7018:
7019: # -------------------------------------------------------------- dump interface
7020:
1.1180 droeschl 7021: sub unserialize {
7022: my ($rep, $escapedkeys) = @_;
7023:
7024: return {} if $rep =~ /^error/;
7025:
7026: my %returnhash=();
1.1252 raeburn 7027: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7028: my ($key, $value) = split(/=/, $item, 2);
7029: $key = unescape($key) unless $escapedkeys;
7030: next if $key =~ /^error: 2 /;
1.1252 raeburn 7031: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7032: }
7033: #return %returnhash;
7034: return \%returnhash;
7035: }
7036:
7037: # see Lond::dump_with_regexp
7038: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7039: sub dump {
1.1180 droeschl 7040: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 7041: if (!$udomain) { $udomain=$env{'user.domain'}; }
7042: if (!$uname) { $uname=$env{'user.name'}; }
7043: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7044:
1.1266 raeburn 7045: if ($regexp) {
7046: $regexp=&escape($regexp);
7047: } else {
7048: $regexp='.';
7049: }
1.1180 droeschl 7050: if (grep { $_ eq $uhome } current_machine_ids()) {
7051: # user is hosted on this machine
1.1266 raeburn 7052: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7053: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7054: return %{unserialize($reply, $escapedkeys)};
7055: }
1.1166 raeburn 7056: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 7057: my @pairs=split(/\&/,$rep);
7058: my %returnhash=();
1.1098 foxr 7059: if (!($rep =~ /^error/ )) {
7060: foreach my $item (@pairs) {
7061: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7062: $key = unescape($key) unless $escapedkeys;
7063: #$key = &unescape($key);
1.1098 foxr 7064: next if ($key =~ /^error: 2 /);
7065: $returnhash{$key}=&thaw_unescape($value);
7066: }
1.755 albertel 7067: }
7068: return %returnhash;
1.407 www 7069: }
7070:
1.1098 foxr 7071:
1.717 albertel 7072: # --------------------------------------------------------- dumpstore interface
7073:
7074: sub dumpstore {
7075: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7076: # same as dump but keys must be escaped. They may contain colon separated
7077: # lists of values that may themself contain colons (e.g. symbs).
7078: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7079: }
7080:
1.407 www 7081: # -------------------------------------------------------------- keys interface
7082:
7083: sub getkeys {
7084: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7085: if (!$udomain) { $udomain=$env{'user.domain'}; }
7086: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7087: my $uhome=&homeserver($uname,$udomain);
7088: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7089: my @keyarray=();
1.800 albertel 7090: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7091: next if ($key =~ /^error: 2 /);
1.800 albertel 7092: push(@keyarray,&unescape($key));
1.407 www 7093: }
7094: return @keyarray;
1.318 matthew 7095: }
7096:
1.319 matthew 7097: # --------------------------------------------------------------- currentdump
7098: sub currentdump {
1.328 matthew 7099: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7100: $courseid = $env{'request.course.id'} if (! defined($courseid));
7101: $sdom = $env{'user.domain'} if (! defined($sdom));
7102: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7103: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7104: my $rep;
7105:
7106: if (grep { $_ eq $uhome } current_machine_ids()) {
7107: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7108: $courseid)));
7109: } else {
7110: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7111: }
7112:
1.318 matthew 7113: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7114: #
1.318 matthew 7115: my %returnhash=();
1.319 matthew 7116: #
1.1343 raeburn 7117: if ($rep eq 'unknown_cmd') {
1.319 matthew 7118: # an old lond will not know currentdump
7119: # Do a dump and make it look like a currentdump
1.822 albertel 7120: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7121: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7122: my %hash = @tmp;
7123: @tmp=();
1.424 matthew 7124: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7125: } else {
7126: my @pairs=split(/\&/,$rep);
1.800 albertel 7127: foreach my $pair (@pairs) {
7128: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7129: my ($symb,$param) = split(/:/,$key);
7130: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7131: &thaw_unescape($value);
1.319 matthew 7132: }
1.191 harris41 7133: }
1.12 www 7134: return %returnhash;
1.424 matthew 7135: }
7136:
7137: sub convert_dump_to_currentdump{
7138: my %hash = %{shift()};
7139: my %returnhash;
7140: # Code ripped from lond, essentially. The only difference
7141: # here is the unescaping done by lonnet::dump(). Conceivably
7142: # we might run in to problems with parameter names =~ /^v\./
7143: while (my ($key,$value) = each(%hash)) {
7144: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7145: $symb = &unescape($symb);
7146: $param = &unescape($param);
1.424 matthew 7147: next if ($v eq 'version' || $symb eq 'keys');
7148: next if (exists($returnhash{$symb}) &&
7149: exists($returnhash{$symb}->{$param}) &&
7150: $returnhash{$symb}->{'v.'.$param} > $v);
7151: $returnhash{$symb}->{$param}=$value;
7152: $returnhash{$symb}->{'v.'.$param}=$v;
7153: }
7154: #
7155: # Remove all of the keys in the hashes which keep track of
7156: # the version of the parameter.
7157: while (my ($symb,$param_hash) = each(%returnhash)) {
7158: # use a foreach because we are going to delete from the hash.
7159: foreach my $key (keys(%$param_hash)) {
7160: delete($param_hash->{$key}) if ($key =~ /^v\./);
7161: }
7162: }
7163: return \%returnhash;
1.12 www 7164: }
7165:
1.627 albertel 7166: # ------------------------------------------------------ critical inc interface
7167:
7168: sub cinc {
7169: return &inc(@_,'critical');
7170: }
7171:
1.449 matthew 7172: # --------------------------------------------------------------- inc interface
7173:
7174: sub inc {
1.627 albertel 7175: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7176: if (!$udomain) { $udomain=$env{'user.domain'}; }
7177: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7178: my $uhome=&homeserver($uname,$udomain);
7179: my $items='';
7180: if (! ref($store)) {
7181: # got a single value, so use that instead
7182: $items = &escape($store).'=&';
7183: } elsif (ref($store) eq 'SCALAR') {
7184: $items = &escape($$store).'=&';
7185: } elsif (ref($store) eq 'ARRAY') {
7186: $items = join('=&',map {&escape($_);} @{$store});
7187: } elsif (ref($store) eq 'HASH') {
7188: while (my($key,$value) = each(%{$store})) {
7189: $items.= &escape($key).'='.&escape($value).'&';
7190: }
7191: }
7192: $items=~s/\&$//;
1.627 albertel 7193: if ($critical) {
7194: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7195: } else {
7196: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7197: }
1.449 matthew 7198: }
7199:
1.12 www 7200: # --------------------------------------------------------------- put interface
7201:
7202: sub put {
1.134 albertel 7203: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7204: if (!$udomain) { $udomain=$env{'user.domain'}; }
7205: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7206: my $uhome=&homeserver($uname,$udomain);
1.12 www 7207: my $items='';
1.800 albertel 7208: foreach my $item (keys(%$storehash)) {
7209: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7210: }
1.12 www 7211: $items=~s/\&$//;
1.134 albertel 7212: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7213: }
7214:
1.631 albertel 7215: # ------------------------------------------------------------ newput interface
7216:
7217: sub newput {
7218: my ($namespace,$storehash,$udomain,$uname)=@_;
7219: if (!$udomain) { $udomain=$env{'user.domain'}; }
7220: if (!$uname) { $uname=$env{'user.name'}; }
7221: my $uhome=&homeserver($uname,$udomain);
7222: my $items='';
7223: foreach my $key (keys(%$storehash)) {
7224: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7225: }
7226: $items=~s/\&$//;
7227: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7228: }
7229:
7230: # --------------------------------------------------------- putstore interface
7231:
1.524 raeburn 7232: sub putstore {
1.1269 raeburn 7233: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7234: if (!$udomain) { $udomain=$env{'user.domain'}; }
7235: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7236: my $uhome=&homeserver($uname,$udomain);
7237: my $items='';
1.715 albertel 7238: foreach my $key (keys(%$storehash)) {
7239: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7240: }
1.715 albertel 7241: $items=~s/\&$//;
1.716 albertel 7242: my $esc_symb=&escape($symb);
7243: my $esc_v=&escape($version);
1.715 albertel 7244: my $reply =
1.716 albertel 7245: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7246: $uhome);
1.1269 raeburn 7247: if (($tolog) && ($reply eq 'ok')) {
7248: my $namevalue='';
7249: foreach my $key (keys(%{$storehash})) {
7250: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7251: }
7252: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
7253: '&host='.&escape($perlvar{'lonHostID'}).
7254: '&version='.$esc_v.
7255: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7256: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7257: }
1.715 albertel 7258: if ($reply eq 'unknown_cmd') {
1.716 albertel 7259: # gfall back to way things use to be done
1.715 albertel 7260: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7261: $uname);
1.524 raeburn 7262: }
1.715 albertel 7263: return $reply;
7264: }
7265:
7266: sub old_putstore {
1.716 albertel 7267: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7268: if (!$udomain) { $udomain=$env{'user.domain'}; }
7269: if (!$uname) { $uname=$env{'user.name'}; }
7270: my $uhome=&homeserver($uname,$udomain);
7271: my %newstorehash;
1.800 albertel 7272: foreach my $item (keys(%$storehash)) {
7273: my $key = $version.':'.&escape($symb).':'.$item;
7274: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7275: }
7276: my $items='';
7277: my %allitems = ();
1.800 albertel 7278: foreach my $item (keys(%newstorehash)) {
7279: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7280: my $key = $1.':keys:'.$2;
7281: $allitems{$key} .= $3.':';
7282: }
1.800 albertel 7283: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7284: }
1.800 albertel 7285: foreach my $item (keys(%allitems)) {
7286: $allitems{$item} =~ s/\:$//;
7287: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7288: }
7289: $items=~s/\&$//;
7290: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7291: }
7292:
1.47 www 7293: # ------------------------------------------------------ critical put interface
7294:
7295: sub cput {
1.134 albertel 7296: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7297: if (!$udomain) { $udomain=$env{'user.domain'}; }
7298: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7299: my $uhome=&homeserver($uname,$udomain);
1.47 www 7300: my $items='';
1.800 albertel 7301: foreach my $item (keys(%$storehash)) {
7302: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7303: }
1.47 www 7304: $items=~s/\&$//;
1.134 albertel 7305: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7306: }
7307:
7308: # -------------------------------------------------------------- eget interface
7309:
7310: sub eget {
1.133 albertel 7311: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7312: my $items='';
1.800 albertel 7313: foreach my $item (@$storearr) {
7314: $items.=&escape($item).'&';
1.191 harris41 7315: }
1.12 www 7316: $items=~s/\&$//;
1.620 albertel 7317: if (!$udomain) { $udomain=$env{'user.domain'}; }
7318: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7319: my $uhome=&homeserver($uname,$udomain);
7320: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7321: my @pairs=split(/\&/,$rep);
7322: my %returnhash=();
1.42 www 7323: my $i=0;
1.800 albertel 7324: foreach my $item (@$storearr) {
7325: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7326: $i++;
1.191 harris41 7327: }
1.12 www 7328: return %returnhash;
7329: }
7330:
1.667 albertel 7331: # ------------------------------------------------------------ tmpput interface
7332: sub tmpput {
1.802 raeburn 7333: my ($storehash,$server,$context)=@_;
1.667 albertel 7334: my $items='';
1.800 albertel 7335: foreach my $item (keys(%$storehash)) {
7336: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7337: }
7338: $items=~s/\&$//;
1.802 raeburn 7339: if (defined($context)) {
7340: $items .= ':'.&escape($context);
7341: }
1.667 albertel 7342: return &reply("tmpput:$items",$server);
7343: }
7344:
7345: # ------------------------------------------------------------ tmpget interface
7346: sub tmpget {
1.688 albertel 7347: my ($token,$server)=@_;
7348: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7349: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7350: my %returnhash;
1.1328 raeburn 7351: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7352: return %returnhash;
7353: }
1.667 albertel 7354: foreach my $item (split(/\&/,$rep)) {
7355: my ($key,$value)=split(/=/,$item);
7356: $returnhash{&unescape($key)}=&thaw_unescape($value);
7357: }
7358: return %returnhash;
7359: }
7360:
1.1113 raeburn 7361: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7362: sub tmpdel {
7363: my ($token,$server)=@_;
7364: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7365: return &reply("tmpdel:$token",$server);
7366: }
7367:
1.1198 raeburn 7368: # ------------------------------------------------------------ get_timebased_id
7369:
7370: sub get_timebased_id {
7371: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7372: $maxtries) = @_;
7373: my ($newid,$error,$dellock);
7374: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7375: return ('','ok','invalid call to get suffix');
7376: }
7377:
7378: # set defaults for any optional args for which values were not supplied
7379: if ($who eq '') {
7380: $who = $env{'user.name'}.':'.$env{'user.domain'};
7381: }
7382: if (!$locktries) {
7383: $locktries = 3;
7384: }
7385: if (!$maxtries) {
7386: $maxtries = 10;
7387: }
7388:
7389: if (($cdom eq '') || ($cnum eq '')) {
7390: if ($env{'request.course.id'}) {
7391: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7392: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7393: }
7394: if (($cdom eq '') || ($cnum eq '')) {
7395: return ('','ok','call to get suffix not in course context');
7396: }
7397: }
7398:
7399: # construct locking item
7400: my $lockhash = {
7401: $prefix."\0".'locked_'.$keyid => $who,
7402: };
7403: my $tries = 0;
7404:
7405: # attempt to get lock on nohist_$namespace file
7406: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7407: while (($gotlock ne 'ok') && $tries <$locktries) {
7408: $tries ++;
7409: sleep 1;
7410: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7411: }
7412:
7413: # attempt to get unique identifier, based on current timestamp
7414: if ($gotlock eq 'ok') {
7415: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7416: my $id = time;
7417: $newid = $id;
1.1268 raeburn 7418: if ($idtype eq 'addcode') {
7419: $newid .= &sixnum_code();
7420: }
1.1198 raeburn 7421: my $idtries = 0;
7422: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7423: if ($idtype eq 'concat') {
7424: $newid = $id.$idtries;
1.1268 raeburn 7425: } elsif ($idtype eq 'addcode') {
7426: $newid = $newid.&sixnum_code();
1.1198 raeburn 7427: } else {
7428: $newid ++;
7429: }
7430: $idtries ++;
7431: }
7432: if (!exists($inuse{$prefix."\0".$newid})) {
7433: my %new_item = (
7434: $prefix."\0".$newid => $who,
7435: );
7436: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7437: $cdom,$cnum);
7438: if ($putresult ne 'ok') {
7439: undef($newid);
7440: $error = 'error saving new item: '.$putresult;
7441: }
7442: } else {
1.1268 raeburn 7443: undef($newid);
1.1198 raeburn 7444: $error = ('error: no unique suffix available for the new item ');
7445: }
7446: # remove lock
7447: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7448: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7449: } else {
7450: $error = "error: could not obtain lockfile\n";
7451: $dellock = 'ok';
1.1276 raeburn 7452: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7453: $dellock = 'nolock';
7454: }
1.1198 raeburn 7455: }
7456: return ($newid,$dellock,$error);
7457: }
7458:
1.1268 raeburn 7459: sub sixnum_code {
7460: my $code;
7461: for (0..6) {
7462: $code .= int( rand(9) );
7463: }
7464: return $code;
7465: }
7466:
1.765 albertel 7467: # -------------------------------------------------- portfolio access checking
7468:
7469: sub portfolio_access {
1.1270 raeburn 7470: my ($requrl,$clientip) = @_;
1.765 albertel 7471: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7472: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7473: if ($result) {
7474: my %setters;
7475: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7476: my ($startblock,$endblock) =
7477: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7478: if ($startblock && $endblock) {
7479: return 'B';
7480: }
7481: } else {
7482: my ($startblock,$endblock) =
7483: &Apache::loncommon::blockcheck(\%setters,'port');
7484: if ($startblock && $endblock) {
7485: return 'B';
7486: }
7487: }
7488: }
1.765 albertel 7489: if ($result eq 'ok') {
1.766 albertel 7490: return 'F';
1.765 albertel 7491: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7492: return 'A';
1.765 albertel 7493: }
1.766 albertel 7494: return '';
1.765 albertel 7495: }
7496:
7497: sub get_portfolio_access {
1.1270 raeburn 7498: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7499:
7500: if (!ref($access_hash)) {
7501: my $current_perms = &get_portfile_permissions($udom,$unum);
7502: my %access_controls = &get_access_controls($current_perms,$group,
7503: $file_name);
7504: $access_hash = $access_controls{$file_name};
7505: }
7506:
1.1270 raeburn 7507: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7508: my $now = time;
7509: if (ref($access_hash) eq 'HASH') {
7510: foreach my $key (keys(%{$access_hash})) {
7511: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7512: if ($start > $now) {
7513: next;
7514: }
7515: if ($end && $end<$now) {
7516: next;
7517: }
7518: if ($scope eq 'public') {
7519: $public = $key;
7520: last;
7521: } elsif ($scope eq 'guest') {
7522: $guest = $key;
7523: } elsif ($scope eq 'domains') {
7524: push(@domains,$key);
7525: } elsif ($scope eq 'users') {
7526: push(@users,$key);
7527: } elsif ($scope eq 'course') {
7528: push(@courses,$key);
7529: } elsif ($scope eq 'group') {
7530: push(@groups,$key);
1.1270 raeburn 7531: } elsif ($scope eq 'ip') {
7532: push(@ips,$key);
1.765 albertel 7533: }
7534: }
7535: if ($public) {
7536: return 'ok';
1.1270 raeburn 7537: } elsif (@ips > 0) {
7538: my $allowed;
7539: foreach my $ipkey (@ips) {
7540: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7541: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7542: $allowed = 1;
7543: last;
7544: }
7545: }
7546: }
7547: if ($allowed) {
7548: return 'ok';
7549: }
1.765 albertel 7550: }
7551: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7552: if ($guest) {
7553: return $guest;
7554: }
7555: } else {
7556: if (@domains > 0) {
7557: foreach my $domkey (@domains) {
7558: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7559: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7560: return 'ok';
7561: }
7562: }
7563: }
7564: }
7565: if (@users > 0) {
7566: foreach my $userkey (@users) {
1.865 raeburn 7567: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7568: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7569: if (ref($item) eq 'HASH') {
7570: if (($item->{'uname'} eq $env{'user.name'}) &&
7571: ($item->{'udom'} eq $env{'user.domain'})) {
7572: return 'ok';
7573: }
7574: }
7575: }
7576: }
1.765 albertel 7577: }
7578: }
7579: my %roleshash;
7580: my @courses_and_groups = @courses;
7581: push(@courses_and_groups,@groups);
7582: if (@courses_and_groups > 0) {
7583: my (%allgroups,%allroles);
7584: my ($start,$end,$role,$sec,$group);
7585: foreach my $envkey (%env) {
1.1060 raeburn 7586: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7587: my $cid = $2.'_'.$3;
7588: if ($1 eq 'gr') {
7589: $group = $4;
7590: $allgroups{$cid}{$group} = $env{$envkey};
7591: } else {
7592: if ($4 eq '') {
7593: $sec = 'none';
7594: } else {
7595: $sec = $4;
7596: }
7597: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7598: }
1.811 albertel 7599: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7600: my $cid = $2.'_'.$3;
7601: if ($4 eq '') {
7602: $sec = 'none';
7603: } else {
7604: $sec = $4;
7605: }
7606: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7607: }
7608: }
7609: if (keys(%allroles) == 0) {
7610: return;
7611: }
7612: foreach my $key (@courses_and_groups) {
7613: my %content = %{$$access_hash{$key}};
7614: my $cnum = $content{'number'};
7615: my $cdom = $content{'domain'};
7616: my $cid = $cdom.'_'.$cnum;
7617: if (!exists($allroles{$cid})) {
7618: next;
7619: }
7620: foreach my $role_id (keys(%{$content{'roles'}})) {
7621: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7622: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7623: my @status = @{$content{'roles'}{$role_id}{'access'}};
7624: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7625: foreach my $role (keys(%{$allroles{$cid}})) {
7626: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7627: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7628: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7629: if (grep/^all$/,@sections) {
7630: return 'ok';
7631: } else {
7632: if (grep/^$sec$/,@sections) {
7633: return 'ok';
7634: }
7635: }
7636: }
7637: }
7638: if (keys(%{$allgroups{$cid}}) == 0) {
7639: if (grep/^none$/,@groups) {
7640: return 'ok';
7641: }
7642: } else {
7643: if (grep/^all$/,@groups) {
7644: return 'ok';
7645: }
7646: foreach my $group (keys(%{$allgroups{$cid}})) {
7647: if (grep/^$group$/,@groups) {
7648: return 'ok';
7649: }
7650: }
7651: }
7652: }
7653: }
7654: }
7655: }
7656: }
7657: if ($guest) {
7658: return $guest;
7659: }
7660: }
7661: }
7662: return;
7663: }
7664:
7665: sub course_group_datechecker {
7666: my ($dates,$now,$status) = @_;
7667: my ($start,$end) = split(/\./,$dates);
7668: if (!$start && !$end) {
7669: return 'ok';
7670: }
7671: if (grep/^active$/,@{$status}) {
7672: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7673: return 'ok';
7674: }
7675: }
7676: if (grep/^previous$/,@{$status}) {
7677: if ($end > $now ) {
7678: return 'ok';
7679: }
7680: }
7681: if (grep/^future$/,@{$status}) {
7682: if ($start > $now) {
7683: return 'ok';
7684: }
7685: }
7686: return;
7687: }
7688:
7689: sub parse_portfolio_url {
7690: my ($url) = @_;
7691:
7692: my ($type,$udom,$unum,$group,$file_name);
7693:
1.823 albertel 7694: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7695: $type = 1;
7696: $udom = $1;
7697: $unum = $2;
7698: $file_name = $3;
1.823 albertel 7699: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7700: $type = 2;
7701: $udom = $1;
7702: $unum = $2;
7703: $group = $3;
7704: $file_name = $3.'/'.$4;
7705: }
7706: if (wantarray) {
7707: return ($type,$udom,$unum,$file_name,$group);
7708: }
7709: return $type;
7710: }
7711:
7712: sub is_portfolio_url {
7713: my ($url) = @_;
7714: return scalar(&parse_portfolio_url($url));
7715: }
7716:
1.798 raeburn 7717: sub is_portfolio_file {
7718: my ($file) = @_;
1.820 raeburn 7719: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7720: return 1;
7721: }
7722: return;
7723: }
7724:
1.976 raeburn 7725: sub usertools_access {
1.1084 raeburn 7726: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7727: my ($access,%tools);
7728: if ($context eq '') {
7729: $context = 'tools';
7730: }
7731: if ($context eq 'requestcourses') {
7732: %tools = (
7733: official => 1,
7734: unofficial => 1,
1.1006 raeburn 7735: community => 1,
1.1246 raeburn 7736: textbook => 1,
1.1305 raeburn 7737: placement => 1,
1.1368 raeburn 7738: lti => 1,
1.985 raeburn 7739: );
1.1183 raeburn 7740: } elsif ($context eq 'requestauthor') {
7741: %tools = (
7742: requestauthor => 1,
7743: );
1.985 raeburn 7744: } else {
7745: %tools = (
7746: aboutme => 1,
7747: blog => 1,
1.1177 raeburn 7748: webdav => 1,
1.985 raeburn 7749: portfolio => 1,
7750: );
7751: }
1.976 raeburn 7752: return if (!defined($tools{$tool}));
7753:
1.1242 raeburn 7754: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7755: $udom = $env{'user.domain'};
7756: $uname = $env{'user.name'};
7757: }
7758:
1.978 raeburn 7759: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7760: if ($action ne 'reload') {
1.985 raeburn 7761: if ($context eq 'requestcourses') {
7762: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7763: } elsif ($context eq 'requestauthor') {
7764: return $env{'environment.canrequest.author'};
1.985 raeburn 7765: } else {
7766: return $env{'environment.availabletools.'.$tool};
7767: }
7768: }
1.976 raeburn 7769: }
7770:
1.1183 raeburn 7771: my ($toolstatus,$inststatus,$envkey);
7772: if ($context eq 'requestauthor') {
7773: $envkey = $context;
7774: } else {
7775: $envkey = $context.'.'.$tool;
7776: }
1.976 raeburn 7777:
1.985 raeburn 7778: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7779: ($action ne 'reload')) {
1.1183 raeburn 7780: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7781: $inststatus = $env{'environment.inststatus'};
7782: } else {
1.1084 raeburn 7783: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7784: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7785: $inststatus = $userenvref->{'inststatus'};
7786: } else {
1.1183 raeburn 7787: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7788: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7789: $inststatus = $userenv{'inststatus'};
7790: }
1.976 raeburn 7791: }
7792:
7793: if ($toolstatus ne '') {
7794: if ($toolstatus) {
7795: $access = 1;
7796: } else {
7797: $access = 0;
7798: }
7799: return $access;
7800: }
7801:
1.1084 raeburn 7802: my ($is_adv,%domdef);
7803: if (ref($is_advref) eq 'HASH') {
7804: $is_adv = $is_advref->{'is_adv'};
7805: } else {
7806: $is_adv = &is_advanced_user($udom,$uname);
7807: }
7808: if (ref($domdefref) eq 'HASH') {
7809: %domdef = %{$domdefref};
7810: } else {
7811: %domdef = &get_domain_defaults($udom);
7812: }
1.976 raeburn 7813: if (ref($domdef{$tool}) eq 'HASH') {
7814: if ($is_adv) {
7815: if ($domdef{$tool}{'_LC_adv'} ne '') {
7816: if ($domdef{$tool}{'_LC_adv'}) {
7817: $access = 1;
7818: } else {
7819: $access = 0;
7820: }
7821: return $access;
7822: }
7823: }
7824: if ($inststatus ne '') {
7825: my ($hasaccess,$hasnoaccess);
7826: foreach my $affiliation (split(/:/,$inststatus)) {
7827: if ($domdef{$tool}{$affiliation} ne '') {
7828: if ($domdef{$tool}{$affiliation}) {
7829: $hasaccess = 1;
7830: } else {
7831: $hasnoaccess = 1;
7832: }
7833: }
7834: }
7835: if ($hasaccess || $hasnoaccess) {
7836: if ($hasaccess) {
7837: $access = 1;
7838: } elsif ($hasnoaccess) {
7839: $access = 0;
7840: }
7841: return $access;
7842: }
7843: } else {
7844: if ($domdef{$tool}{'default'} ne '') {
7845: if ($domdef{$tool}{'default'}) {
7846: $access = 1;
7847: } elsif ($domdef{$tool}{'default'} == 0) {
7848: $access = 0;
7849: }
7850: return $access;
7851: }
7852: }
7853: } else {
1.1177 raeburn 7854: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7855: $access = 1;
7856: } else {
7857: $access = 0;
7858: }
1.976 raeburn 7859: return $access;
7860: }
7861: }
7862:
1.1050 raeburn 7863: sub is_course_owner {
7864: my ($cdom,$cnum,$udom,$uname) = @_;
7865: if (($udom eq '') || ($uname eq '')) {
7866: $udom = $env{'user.domain'};
7867: $uname = $env{'user.name'};
7868: }
7869: unless (($udom eq '') || ($uname eq '')) {
7870: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7871: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7872: return 1;
7873: } else {
7874: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7875: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7876: return 1;
7877: }
7878: }
7879: }
7880: }
7881: return;
7882: }
7883:
1.976 raeburn 7884: sub is_advanced_user {
7885: my ($udom,$uname) = @_;
1.1085 raeburn 7886: if ($udom ne '' && $uname ne '') {
7887: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7888: if (wantarray) {
7889: return ($env{'user.adv'},$env{'user.author'});
7890: } else {
7891: return $env{'user.adv'};
7892: }
1.1085 raeburn 7893: }
7894: }
1.976 raeburn 7895: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7896: my %allroles;
1.1128 raeburn 7897: my ($is_adv,$is_author);
1.976 raeburn 7898: foreach my $role (keys(%roleshash)) {
7899: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7900: my $area = '/'.$tdomain.'/'.$trest;
7901: if ($sec ne '') {
7902: $area .= '/'.$sec;
7903: }
7904: if (($area ne '') && ($trole ne '')) {
7905: my $spec=$trole.'.'.$area;
7906: if ($trole =~ /^cr\//) {
7907: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7908: } elsif ($trole ne 'gr') {
7909: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7910: }
1.1128 raeburn 7911: if ($trole eq 'au') {
7912: $is_author = 1;
7913: }
1.976 raeburn 7914: }
7915: }
7916: foreach my $role (keys(%allroles)) {
7917: last if ($is_adv);
7918: foreach my $item (split(/:/,$allroles{$role})) {
7919: if ($item ne '') {
7920: my ($privilege,$restrictions)=split(/&/,$item);
7921: if ($privilege eq 'adv') {
7922: $is_adv = 1;
7923: last;
7924: }
7925: }
7926: }
7927: }
1.1128 raeburn 7928: if (wantarray) {
7929: return ($is_adv,$is_author);
7930: }
1.976 raeburn 7931: return $is_adv;
7932: }
1.798 raeburn 7933:
1.1035 raeburn 7934: sub check_can_request {
1.1368 raeburn 7935: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 7936: my $canreq = 0;
1.1368 raeburn 7937: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7938: $uname = $env{'user.name'};
7939: $udom = $env{'user.domain'};
7940: }
1.1035 raeburn 7941: my ($types,$typename) = &Apache::loncommon::course_types();
7942: my @options = ('approval','validate','autolimit');
7943: my $optregex = join('|',@options);
7944: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7945: foreach my $type (@{$types}) {
1.1368 raeburn 7946: if (&usertools_access($uname,$udom,$type,undef,
7947: 'requestcourses')) {
1.1035 raeburn 7948: $canreq ++;
1.1036 raeburn 7949: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 7950: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 7951: }
1.1368 raeburn 7952: if ($dom eq $udom) {
1.1035 raeburn 7953: $can_request->{$type} = 1;
7954: }
7955: }
1.1368 raeburn 7956: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
7957: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 7958: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7959: if (@curr > 0) {
1.1036 raeburn 7960: foreach my $item (@curr) {
7961: if (ref($request_domains) eq 'HASH') {
7962: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7963: if ($otherdom ne '') {
7964: if (ref($request_domains->{$type}) eq 'ARRAY') {
7965: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7966: push(@{$request_domains->{$type}},$otherdom);
7967: }
7968: } else {
7969: push(@{$request_domains->{$type}},$otherdom);
7970: }
7971: }
7972: }
7973: }
1.1368 raeburn 7974: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 7975: $canreq ++;
1.1035 raeburn 7976: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7977: $can_request->{$type} = 1;
7978: }
7979: }
7980: }
7981: }
7982: }
7983: }
7984: return $canreq;
7985: }
7986:
1.341 www 7987: # ---------------------------------------------- Custom access rule evaluation
7988:
7989: sub customaccess {
7990: my ($priv,$uri)=@_;
1.807 albertel 7991: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7992: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7993: $udom = &LONCAPA::clean_domain($udom);
7994: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7995: my $access=0;
1.800 albertel 7996: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7997: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7998: if ($type eq 'user') {
7999: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8000: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8001: if ($tdom) {
8002: if ($tdom ne $env{'user.domain'}) { next; }
8003: }
1.896 albertel 8004: if ($tuname) {
8005: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8006: }
8007: $access=($effect eq 'allow');
8008: last;
8009: }
8010: } else {
8011: if ($role) {
8012: if ($role ne $urole) { next; }
8013: }
8014: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8015: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8016: if ($tdom) {
8017: if ($tdom ne $udom) { next; }
8018: }
8019: if ($tcrs) {
8020: if ($tcrs ne $ucrs) { next; }
8021: }
8022: if ($tsec) {
8023: if ($tsec ne $usec) { next; }
8024: }
8025: $access=($effect eq 'allow');
8026: last;
8027: }
8028: if ($realm eq '' && $role eq '') {
8029: $access=($effect eq 'allow');
8030: }
1.402 bowersj2 8031: }
1.341 www 8032: }
8033: return $access;
8034: }
8035:
1.103 harris41 8036: # ------------------------------------------------- Check for a user privilege
1.12 www 8037:
8038: sub allowed {
1.1281 raeburn 8039: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 8040: my $ver_orguri=$uri;
1.439 www 8041: $uri=&deversion($uri);
1.152 www 8042: my $orguri=$uri;
1.52 www 8043: $uri=&declutter($uri);
1.809 raeburn 8044:
1.810 raeburn 8045: if ($priv eq 'evb') {
8046: # Evade communication block restrictions for specified role in a course
8047: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8048: return $1;
8049: } else {
8050: return;
8051: }
8052: }
8053:
1.620 albertel 8054: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8055: # Free bre access to adm and meta resources
1.1343 raeburn 8056: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 8057: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8058: && ($priv eq 'bre')) {
1.14 www 8059: return 'F';
1.159 www 8060: }
8061:
1.545 banghart 8062: # Free bre access to user's own portfolio contents
1.714 raeburn 8063: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8064: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8065: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8066: my %setters;
8067: my ($startblock,$endblock) =
8068: &Apache::loncommon::blockcheck(\%setters,'port');
8069: if ($startblock && $endblock) {
8070: return 'B';
8071: } else {
8072: return 'F';
8073: }
1.545 banghart 8074: }
8075:
1.762 raeburn 8076: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8077: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8078: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8079: if (exists($env{'request.course.id'})) {
8080: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8081: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8082: if (($domain eq $cdom) && ($name eq $cnum)) {
8083: my $courseprivid=$env{'request.course.id'};
8084: $courseprivid=~s/\_/\//;
8085: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8086: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8087: return $1;
1.762 raeburn 8088: } else {
8089: if ($env{'request.course.sec'}) {
8090: $courseprivid.='/'.$env{'request.course.sec'};
8091: }
8092: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8093: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8094: return $2;
8095: }
1.714 raeburn 8096: }
8097: }
8098: }
8099: }
8100:
1.159 www 8101: # Free bre to public access
8102:
8103: if ($priv eq 'bre') {
1.1362 raeburn 8104: my $copyright;
8105: unless ($uri =~ /ext\.tool/) {
8106: $copyright=&metadata($uri,'copyright');
8107: }
1.620 albertel 8108: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8109: return 'F';
8110: }
1.238 www 8111: if ($copyright eq 'priv') {
8112: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8113: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8114: return '';
8115: }
8116: }
8117: if ($copyright eq 'domain') {
8118: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8119: unless (($env{'user.domain'} eq $1) ||
8120: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8121: return '';
8122: }
1.262 matthew 8123: }
1.620 albertel 8124: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8125: # Library role, so allow browsing of resources in this domain.
8126: return 'F';
1.238 www 8127: }
1.341 www 8128: if ($copyright eq 'custom') {
8129: unless (&customaccess($priv,$uri)) { return ''; }
8130: }
1.14 www 8131: }
1.264 matthew 8132: # Domain coordinator is trying to create a course
1.620 albertel 8133: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8134: # uri is the requested domain in this case.
8135: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8136: # a role of dc for the domain in question.
1.620 albertel 8137: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8138: }
1.29 www 8139:
1.52 www 8140: my $thisallowed='';
8141: my $statecond=0;
8142: my $courseprivid='';
8143:
1.1039 raeburn 8144: my $ownaccess;
1.1043 raeburn 8145: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8146: if (($priv eq 'bro') && ($env{'user.author'})) {
8147: if ($uri eq '') {
8148: $ownaccess = 1;
8149: } else {
8150: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8151: my $udom = $env{'user.domain'};
8152: my $uname = $env{'user.name'};
8153: if ($uri =~ m{^\Q$udom\E/?$}) {
8154: $ownaccess = 1;
1.1040 raeburn 8155: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8156: unless ($uri =~ m{\.\./}) {
8157: $ownaccess = 1;
8158: }
8159: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8160: my $now = time;
8161: if ($uri =~ m{^([^/]+)/?$}) {
8162: my $adom = $1;
8163: foreach my $key (keys(%env)) {
1.1042 raeburn 8164: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 8165: my ($start,$end) = split('.',$env{$key});
8166: if (($now >= $start) && (!$end || $end < $now)) {
8167: $ownaccess = 1;
8168: last;
8169: }
8170: }
8171: }
8172: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8173: my $adom = $1;
8174: my $aname = $2;
1.1042 raeburn 8175: foreach my $role ('ca','aa') {
8176: if ($env{"user.role.$role./$adom/$aname"}) {
8177: my ($start,$end) =
8178: split('.',$env{"user.role.$role./$adom/$aname"});
8179: if (($now >= $start) && (!$end || $end < $now)) {
8180: $ownaccess = 1;
8181: last;
8182: }
1.1039 raeburn 8183: }
8184: }
8185: }
8186: }
8187: }
8188: }
8189: }
8190:
1.52 www 8191: # Course
8192:
1.620 albertel 8193: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8194: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8195: $thisallowed.=$1;
8196: }
1.52 www 8197: }
1.29 www 8198:
1.52 www 8199: # Domain
8200:
1.620 albertel 8201: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8202: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8203: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8204: $thisallowed.=$1;
8205: }
1.12 www 8206: }
1.52 www 8207:
1.1141 raeburn 8208: # User who is not author or co-author might still be able to edit
8209: # resource of an author in the domain (e.g., if Domain Coordinator).
8210: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8211: (&allowed('mdc',$env{'request.course.id'}))) {
8212: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8213: $thisallowed.=$1;
8214: }
8215: }
8216:
1.52 www 8217: # Course: uri itself is a course
1.66 www 8218: my $courseuri=$uri;
8219: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8220: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8221:
1.620 albertel 8222: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8223: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8224: if ($priv eq 'mip') {
8225: my $rem = $1;
8226: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8227: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8228: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8229: if ($cdom ne '') {
1.1410 raeburn 8230: my %passwdconf = &get_passwdconf($cdom);
8231: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8232: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8233: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8234: my @inststatuses = split(':',$env{'environment.inststatus'});
8235: unless (@inststatuses) {
8236: @inststatuses = ('default');
8237: }
8238: foreach my $status (@inststatuses) {
8239: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8240: $thisallowed.=$rem;
8241: }
8242: }
8243: }
8244: }
1.1409 raeburn 8245: }
8246: }
8247: }
8248: } else {
8249: unless (($priv eq 'bro') && (!$ownaccess)) {
8250: $thisallowed.=$1;
8251: }
1.1039 raeburn 8252: }
1.12 www 8253: }
1.29 www 8254:
1.665 albertel 8255: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8256: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8257: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8258: $thisallowed='';
1.671 raeburn 8259: my ($match)=&is_on_map($uri);
8260: if ($match) {
8261: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8262: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8263: my $value = $1;
1.1402 raeburn 8264: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8265: if ($deeplinkblock) {
8266: $thisallowed='D';
8267: } elsif ($noblockcheck) {
1.1281 raeburn 8268: $thisallowed.=$value;
1.1162 raeburn 8269: } else {
1.1281 raeburn 8270: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8271: if (@blockers > 0) {
8272: $thisallowed = 'B';
8273: } else {
8274: $thisallowed.=$value;
8275: }
1.1162 raeburn 8276: }
1.671 raeburn 8277: }
8278: } else {
1.705 albertel 8279: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8280: if ($refuri) {
8281: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8282: $thisallowed='F';
1.671 raeburn 8283: } else {
8284: $refuri=&declutter($refuri);
8285: my ($match) = &is_on_map($refuri);
8286: if ($match) {
1.1402 raeburn 8287: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8288: if ($deeplinkblock) {
8289: $thisallowed='D';
8290: } elsif ($noblockcheck) {
1.1281 raeburn 8291: $thisallowed='F';
1.1162 raeburn 8292: } else {
1.1281 raeburn 8293: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8294: if (@blockers > 0) {
8295: $thisallowed = 'B';
8296: } else {
8297: $thisallowed='F';
8298: }
1.1162 raeburn 8299: }
1.671 raeburn 8300: }
1.669 raeburn 8301: }
1.671 raeburn 8302: }
8303: }
1.314 www 8304: }
1.492 albertel 8305:
1.766 albertel 8306: if ($priv eq 'bre'
8307: && $thisallowed ne 'F'
8308: && $thisallowed ne '2'
8309: && &is_portfolio_url($uri)) {
1.1270 raeburn 8310: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8311: }
1.1250 raeburn 8312:
1.52 www 8313: # Full access at system, domain or course-wide level? Exit.
1.29 www 8314: if ($thisallowed=~/F/) {
8315: return 'F';
8316: }
8317:
1.52 www 8318: # If this is generating or modifying users, exit with special codes
1.29 www 8319:
1.643 www 8320: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8321: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8322: my ($audom,$auname)=split('/',$uri);
1.643 www 8323: # no author name given, so this just checks on the general right to make a co-author in this domain
8324: unless ($auname) { return $thisallowed; }
8325: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8326: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8327: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8328: ($audom ne $env{'request.role.domain'}))) { return ''; }
8329: }
1.52 www 8330: return $thisallowed;
8331: }
8332: #
1.103 harris41 8333: # Gathered so far: system, domain and course wide privileges
1.52 www 8334: #
8335: # Course: See if uri or referer is an individual resource that is part of
8336: # the course
8337:
1.620 albertel 8338: if ($env{'request.course.id'}) {
1.232 www 8339:
1.1409 raeburn 8340: # If this is modifying password (internal auth) domains must match for user and user's role.
8341:
8342: if ($priv eq 'mip') {
8343: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8344: return $thisallowed;
8345: } else {
8346: return '';
8347: }
8348: }
8349:
1.620 albertel 8350: $courseprivid=$env{'request.course.id'};
8351: if ($env{'request.course.sec'}) {
8352: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8353: }
8354: $courseprivid=~s/\_/\//;
8355: my $checkreferer=1;
1.232 www 8356: my ($match,$cond)=&is_on_map($uri);
8357: if ($match) {
8358: $statecond=$cond;
1.620 albertel 8359: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8360: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8361: my $value = $1;
8362: if ($priv eq 'bre') {
1.1281 raeburn 8363: if ($noblockcheck) {
8364: $thisallowed.=$value;
1.1162 raeburn 8365: } else {
1.1281 raeburn 8366: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8367: if (@blockers > 0) {
8368: $thisallowed = 'B';
8369: } else {
8370: $thisallowed.=$value;
8371: }
1.1162 raeburn 8372: }
8373: } else {
8374: $thisallowed.=$value;
8375: }
1.52 www 8376: $checkreferer=0;
8377: }
1.29 www 8378: }
1.83 www 8379:
1.148 www 8380: if ($checkreferer) {
1.620 albertel 8381: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8382: unless ($refuri) {
1.800 albertel 8383: foreach my $key (keys(%env)) {
8384: if ($key=~/^httpref\..*\*/) {
8385: my $pattern=$key;
1.156 www 8386: $pattern=~s/^httpref\.\/res\///;
1.148 www 8387: $pattern=~s/\*/\[\^\/\]\+/g;
8388: $pattern=~s/\//\\\//g;
1.152 www 8389: if ($orguri=~/$pattern/) {
1.800 albertel 8390: $refuri=$env{$key};
1.148 www 8391: }
8392: }
1.191 harris41 8393: }
1.148 www 8394: }
1.232 www 8395:
1.148 www 8396: if ($refuri) {
1.152 www 8397: $refuri=&declutter($refuri);
1.232 www 8398: my ($match,$cond)=&is_on_map($refuri);
8399: if ($match) {
8400: my $refstatecond=$cond;
1.620 albertel 8401: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8402: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8403: my $value = $1;
8404: if ($priv eq 'bre') {
1.1402 raeburn 8405: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8406: if ($deeplinkblock) {
8407: $thisallowed = 'D';
8408: } elsif ($noblockcheck) {
1.1281 raeburn 8409: $thisallowed.=$value;
1.1162 raeburn 8410: } else {
1.1281 raeburn 8411: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8412: if (@blockers > 0) {
8413: $thisallowed = 'B';
8414: } else {
8415: $thisallowed.=$value;
8416: }
1.1162 raeburn 8417: }
8418: } else {
8419: $thisallowed.=$value;
8420: }
1.53 www 8421: $uri=$refuri;
8422: $statecond=$refstatecond;
1.52 www 8423: }
8424: }
1.148 www 8425: }
1.29 www 8426: }
1.52 www 8427: }
1.29 www 8428:
1.52 www 8429: #
1.103 harris41 8430: # Gathered now: all privileges that could apply, and condition number
1.52 www 8431: #
8432: #
8433: # Full or no access?
8434: #
1.29 www 8435:
1.52 www 8436: if ($thisallowed=~/F/) {
8437: return 'F';
8438: }
1.29 www 8439:
1.52 www 8440: unless ($thisallowed) {
8441: return '';
8442: }
1.29 www 8443:
1.52 www 8444: # Restrictions exist, deal with them
8445: #
8446: # C:according to course preferences
8447: # R:according to resource settings
8448: # L:unless locked
8449: # X:according to user session state
8450: #
8451:
8452: # Possibly locked functionality, check all courses
1.54 www 8453: # Locks might take effect only after 10 minutes cache expiration for other
8454: # courses, and 2 minutes for current course
1.52 www 8455:
8456: my $envkey;
8457: if ($thisallowed=~/L/) {
1.1000 raeburn 8458: foreach $envkey (keys(%env)) {
1.54 www 8459: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8460: my $courseid=$2;
8461: my $roleid=$1.'.'.$2;
1.92 www 8462: $courseid=~s/^\///;
1.54 www 8463: my $expiretime=600;
1.620 albertel 8464: if ($env{'request.role'} eq $roleid) {
1.54 www 8465: $expiretime=120;
8466: }
8467: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8468: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8469: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8470: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8471: }
1.620 albertel 8472: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8473: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8474: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8475: &log($env{'user.domain'},$env{'user.name'},
8476: $env{'user.home'},
1.57 www 8477: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8478: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8479: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8480: return '';
8481: }
8482: }
1.620 albertel 8483: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8484: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8485: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8486: &log($env{'user.domain'},$env{'user.name'},
8487: $env{'user.home'},
1.57 www 8488: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8489: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8490: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8491: return '';
8492: }
8493: }
8494: }
1.29 www 8495: }
1.52 www 8496: }
8497:
8498: #
8499: # Rest of the restrictions depend on selected course
8500: #
8501:
1.620 albertel 8502: unless ($env{'request.course.id'}) {
1.766 albertel 8503: if ($thisallowed eq 'A') {
8504: return 'A';
1.814 raeburn 8505: } elsif ($thisallowed eq 'B') {
8506: return 'B';
1.766 albertel 8507: } else {
8508: return '1';
8509: }
1.52 www 8510: }
1.29 www 8511:
1.52 www 8512: #
8513: # Now user is definitely in a course
8514: #
1.53 www 8515:
8516:
8517: # Course preferences
8518:
8519: if ($thisallowed=~/C/) {
1.620 albertel 8520: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8521: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8522: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8523: =~/\Q$rolecode\E/) {
1.1304 raeburn 8524: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8525: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8526: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8527: $env{'request.course.id'});
8528: }
1.237 www 8529: return '';
8530: }
8531:
1.620 albertel 8532: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8533: =~/\Q$unamedom\E/) {
1.1304 raeburn 8534: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8535: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8536: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8537: $env{'request.course.id'});
8538: }
1.54 www 8539: return '';
8540: }
1.53 www 8541: }
8542:
8543: # Resource preferences
8544:
8545: if ($thisallowed=~/R/) {
1.620 albertel 8546: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8547: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8548: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8549: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8550: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8551: }
8552: return '';
1.54 www 8553: }
1.53 www 8554: }
1.30 www 8555:
1.246 www 8556: # Restricted by state or randomout?
1.30 www 8557:
1.52 www 8558: if ($thisallowed=~/X/) {
1.620 albertel 8559: if ($env{'acc.randomout'}) {
1.579 albertel 8560: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8561: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8562: return '';
8563: }
1.247 www 8564: }
8565: if (&condval($statecond)) {
1.52 www 8566: return '2';
8567: } else {
8568: return '';
8569: }
8570: }
1.30 www 8571:
1.766 albertel 8572: if ($thisallowed eq 'A') {
8573: return 'A';
1.814 raeburn 8574: } elsif ($thisallowed eq 'B') {
8575: return 'B';
1.1402 raeburn 8576: } elsif ($thisallowed eq 'D') {
8577: return 'D';
1.766 albertel 8578: }
1.52 www 8579: return 'F';
1.232 www 8580: }
1.1162 raeburn 8581:
1.1192 raeburn 8582: # ------------------------------------------- Check construction space access
8583:
8584: sub constructaccess {
8585: my ($url,$setpriv)=@_;
8586:
8587: # We do not allow editing of previous versions of files
8588: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8589:
8590: # Get username and domain from URL
8591: my ($ownername,$ownerdomain,$ownerhome);
8592:
8593: ($ownerdomain,$ownername) =
1.1325 raeburn 8594: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8595:
8596: # The URL does not really point to any authorspace, forget it
8597: unless (($ownername) && ($ownerdomain)) { return ''; }
8598:
8599: # Now we need to see if the user has access to the authorspace of
8600: # $ownername at $ownerdomain
8601:
8602: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8603: # Real author for this?
8604: $ownerhome = $env{'user.home'};
8605: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8606: return ($ownername,$ownerdomain,$ownerhome);
8607: }
8608: } else {
8609: # Co-author for this?
8610: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8611: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8612: $ownerhome = &homeserver($ownername,$ownerdomain);
8613: return ($ownername,$ownerdomain,$ownerhome);
8614: }
1.1312 raeburn 8615: if ($env{'request.course.id'}) {
8616: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8617: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8618: if (&allowed('mdc',$env{'request.course.id'})) {
8619: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8620: return ($ownername,$ownerdomain,$ownerhome);
8621: }
8622: }
8623: }
1.1192 raeburn 8624: }
8625:
8626: # We don't have any access right now. If we are not possibly going to do anything about this,
8627: # we might as well leave
8628: unless ($setpriv) { return ''; }
8629:
8630: # Backdoor access?
8631: my $allowed=&allowed('eco',$ownerdomain);
8632: # Nope
8633: unless ($allowed) { return ''; }
8634: # Looks like we may have access, but could be locked by the owner of the construction space
8635: if ($allowed eq 'U') {
8636: my %blocked=&get('environment',['domcoord.author'],
8637: $ownerdomain,$ownername);
8638: # Is blocked by owner
8639: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8640: }
8641: if (($allowed eq 'F') || ($allowed eq 'U')) {
8642: # Grant temporary access
8643: my $then=$env{'user.login.time'};
1.1209 raeburn 8644: my $update=$env{'user.update.time'};
1.1192 raeburn 8645: if (!$update) { $update = $then; }
8646: my $refresh=$env{'user.refresh.time'};
8647: if (!$refresh) { $refresh = $update; }
8648: my $now = time;
8649: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8650: $now,'ca','constructaccess');
8651: $ownerhome = &homeserver($ownername,$ownerdomain);
8652: return($ownername,$ownerdomain,$ownerhome);
8653: }
8654: # No business here
8655: return '';
8656: }
8657:
1.1282 raeburn 8658: # ----------------------------------------------------------- Content Blocking
8659:
8660: {
8661: # Caches for faster Course Contents display where content blocking
8662: # is in operation (i.e., interval param set) for timed quiz.
8663: #
8664: # User for whom data are being temporarily cached.
8665: my $cacheduser='';
8666: # Cached blockers for this user (a hash of blocking items).
8667: my %cachedblockers=();
8668: # When the data were last cached.
8669: my $cachedlast='';
8670:
8671: sub load_all_blockers {
8672: my ($uname,$udom,$blocks)=@_;
8673: if (($uname ne '') && ($udom ne '')) {
8674: if (($cacheduser eq $uname.':'.$udom) &&
8675: (abs($cachedlast-time)<5)) {
8676: return;
8677: }
8678: }
8679: $cachedlast=time;
8680: $cacheduser=$uname.':'.$udom;
8681: %cachedblockers = &get_commblock_resources($blocks);
8682: }
8683:
1.1162 raeburn 8684: sub get_comm_blocks {
8685: my ($cdom,$cnum) = @_;
8686: if ($cdom eq '' || $cnum eq '') {
8687: return unless ($env{'request.course.id'});
8688: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8689: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8690: }
8691: my %commblocks;
8692: my $hashid=$cdom.'_'.$cnum;
8693: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8694: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8695: %commblocks = %{$blocksref};
8696: } else {
8697: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8698: my $cachetime = 600;
8699: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8700: }
8701: return %commblocks;
8702: }
8703:
1.1282 raeburn 8704: sub get_commblock_resources {
8705: my ($blocks) = @_;
8706: my %blockers = ();
8707: return %blockers unless ($env{'request.course.id'});
8708: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8709: my %commblocks;
8710: if (ref($blocks) eq 'HASH') {
8711: %commblocks = %{$blocks};
8712: } else {
8713: %commblocks = &get_comm_blocks();
8714: }
1.1282 raeburn 8715: return %blockers unless (keys(%commblocks) > 0);
8716: my $navmap = Apache::lonnavmaps::navmap->new();
8717: return %blockers unless (ref($navmap));
1.1162 raeburn 8718: my $now = time;
8719: foreach my $block (keys(%commblocks)) {
8720: if ($block =~ /^(\d+)____(\d+)$/) {
8721: my ($start,$end) = ($1,$2);
8722: if ($start <= $now && $end >= $now) {
8723: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8724: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8725: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8726: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8727: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8728: }
8729: }
8730: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8731: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8732: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8733: }
8734: }
8735: }
8736: }
8737: }
8738: } elsif ($block =~ /^firstaccess____(.+)$/) {
8739: my $item = $1;
1.1163 raeburn 8740: my @to_test;
1.1162 raeburn 8741: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8742: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8743: my @interval;
8744: my $type = 'map';
8745: if ($item eq 'course') {
8746: $type = 'course';
8747: @interval=&EXT("resource.0.interval");
8748: } else {
8749: if ($item =~ /___\d+___/) {
8750: $type = 'resource';
8751: @interval=&EXT("resource.0.interval",$item);
8752: if (ref($navmap)) {
8753: my $res = $navmap->getBySymb($item);
8754: push(@to_test,$res);
8755: }
1.1162 raeburn 8756: } else {
1.1282 raeburn 8757: my $mapsymb = &symbread($item,1);
8758: if ($mapsymb) {
8759: if (ref($navmap)) {
8760: my $mapres = $navmap->getBySymb($mapsymb);
8761: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8762: foreach my $res (@to_test) {
8763: my $symb = $res->symb();
8764: next if ($symb eq $mapsymb);
8765: if ($symb ne '') {
8766: @interval=&EXT("resource.0.interval",$symb);
8767: if ($interval[1] eq 'map') {
8768: last;
1.1162 raeburn 8769: }
8770: }
8771: }
8772: }
8773: }
8774: }
1.1282 raeburn 8775: }
1.1310 raeburn 8776: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8777: my $timelimit = $1;
1.1282 raeburn 8778: my $first_access;
8779: if ($type eq 'resource') {
8780: $first_access=&get_first_access($interval[1],$item);
8781: } elsif ($type eq 'map') {
8782: $first_access=&get_first_access($interval[1],undef,$item);
8783: } else {
8784: $first_access=&get_first_access($interval[1]);
8785: }
8786: if ($first_access) {
1.1292 raeburn 8787: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8788: if ($timesup > $now) {
8789: my $activeblock;
8790: foreach my $res (@to_test) {
1.1283 raeburn 8791: if ($res->answerable()) {
1.1282 raeburn 8792: $activeblock = 1;
8793: last;
8794: }
8795: }
8796: if ($activeblock) {
8797: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8798: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8799: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8800: }
8801: }
8802: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8803: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8804: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8805: }
1.1162 raeburn 8806: }
8807: }
8808: }
8809: }
8810: }
8811: }
8812: }
8813: }
8814: }
1.1282 raeburn 8815: return %blockers;
1.1162 raeburn 8816: }
8817:
1.1282 raeburn 8818: sub has_comm_blocking {
8819: my ($priv,$symb,$uri,$blocks) = @_;
8820: my @blockers;
8821: return unless ($env{'request.course.id'});
8822: return unless ($priv eq 'bre');
8823: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8824: return if ($env{'request.state'} eq 'construct');
8825: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8826: return unless (keys(%cachedblockers) > 0);
8827: my (%possibles,@symbs);
8828: if (!$symb) {
8829: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8830: }
1.1282 raeburn 8831: if ($symb) {
8832: @symbs = ($symb);
8833: } elsif (keys(%possibles)) {
8834: @symbs = keys(%possibles);
8835: }
8836: my $noblock;
8837: foreach my $symb (@symbs) {
8838: last if ($noblock);
8839: my ($map,$resid,$resurl)=&decode_symb($symb);
8840: foreach my $block (keys(%cachedblockers)) {
8841: if ($block =~ /^firstaccess____(.+)$/) {
8842: my $item = $1;
8843: if (($item eq $map) || ($item eq $symb)) {
8844: $noblock = 1;
8845: last;
8846: }
8847: }
8848: if (ref($cachedblockers{$block}) eq 'HASH') {
8849: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8850: if ($cachedblockers{$block}{'resources'}{$symb}) {
8851: unless (grep(/^\Q$block\E$/,@blockers)) {
8852: push(@blockers,$block);
8853: }
8854: }
8855: }
1.1162 raeburn 8856: }
1.1282 raeburn 8857: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8858: if ($cachedblockers{$block}{'maps'}{$map}) {
8859: unless (grep(/^\Q$block\E$/,@blockers)) {
8860: push(@blockers,$block);
8861: }
8862: }
1.1162 raeburn 8863: }
8864: }
8865: }
1.1282 raeburn 8866: return if ($noblock);
8867: return @blockers;
8868: }
1.1162 raeburn 8869: }
8870:
1.1402 raeburn 8871: sub deeplink_check {
8872: my ($priv,$symb,$uri) = @_;
8873: return unless ($env{'request.course.id'});
8874: return unless ($priv eq 'bre');
8875: return if ($env{'request.state'} eq 'construct');
8876: return if ($env{'request.role.adv'});
8877: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8878: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8879: my (%possibles,@symbs);
8880: if (!$symb) {
8881: $symb = &symbread($uri,1,1,1,\%possibles);
8882: }
8883: if ($symb) {
8884: @symbs = ($symb);
8885: } elsif (keys(%possibles)) {
8886: @symbs = keys(%possibles);
8887: }
8888:
8889: my ($login,$switchrole,$allow);
8890: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
8891: my $key = $1;
8892: my $tinyurl;
8893: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
8894: if (defined($cached)) {
8895: $tinyurl = $result;
8896: } else {
8897: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
8898: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
8899: if ($currtiny{$key} ne '') {
8900: $tinyurl = $currtiny{$key};
8901: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
8902: }
8903: }
8904: if ($tinyurl ne '') {
8905: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
8906: if ($cnumreq eq $cnum) {
8907: $login = $posslogin;
8908: } else {
8909: $switchrole = 1;
8910: }
8911: }
8912: }
8913: foreach my $symb (@symbs) {
8914: last if ($allow);
8915: my $deeplink = &EXT("resource.0.deeplink",$symb);
8916: if ($deeplink eq '') {
8917: $allow = 1;
8918: } else {
8919: my ($listed,$scope,$access) = split(/,/,$deeplink);
8920: if ($access eq 'any') {
8921: $allow = 1;
8922: } elsif ($login) {
8923: if ($access eq 'only') {
8924: if ($scope eq 'res') {
8925: if ($symb eq $login) {
8926: $allow = 1;
8927: }
8928: } elsif ($scope eq 'map') {
8929: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
8930: } elsif ($scope eq 'rec') {
8931: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
8932: }
8933: } else {
8934: my ($acctype,$item) = split(/:/,$access);
8935: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
8936: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
8937: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8938: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
8939: $allow = 1;
8940: }
8941: }
8942: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
8943: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
8944: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
8945: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
8946: $allow = 1;
8947: }
8948: }
8949: }
8950: }
8951: }
8952: }
8953: }
8954: return if ($allow);
8955: return 1;
8956: }
8957:
1.1282 raeburn 8958: # -------------------------------- Deversion and split uri into path an filename
8959:
1.1133 foxr 8960: #
1.1282 raeburn 8961: # Removes the version from a URI and
1.1133 foxr 8962: # splits it in to its filename and path to the filename.
8963: # Seems like File::Basename could have done this more clearly.
8964: # Parameters:
8965: # $uri - input URI
8966: # Returns:
8967: # Two element list consisting of
8968: # $pathname - the URI up to and excluding the trailing /
8969: # $filename - The part of the URI following the last /
8970: # NOTE:
8971: # Another realization of this is simply:
8972: # use File::Basename;
8973: # ...
8974: # $uri = shift;
8975: # $filename = basename($uri);
8976: # $path = dirname($uri);
8977: # return ($filename, $path);
8978: #
8979: # The implementation below is probably faster however.
8980: #
1.710 albertel 8981: sub split_uri_for_cond {
8982: my $uri=&deversion(&declutter(shift));
8983: my @uriparts=split(/\//,$uri);
8984: my $filename=pop(@uriparts);
8985: my $pathname=join('/',@uriparts);
8986: return ($pathname,$filename);
8987: }
1.232 www 8988: # --------------------------------------------------- Is a resource on the map?
8989:
8990: sub is_on_map {
1.710 albertel 8991: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8992: #Trying to find the conditional for the file
1.620 albertel 8993: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8994: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8995: if ($match) {
1.289 bowersj2 8996: return (1,$1);
8997: } else {
1.434 www 8998: return (0,0);
1.289 bowersj2 8999: }
1.12 www 9000: }
9001:
1.427 www 9002: # --------------------------------------------------------- Get symb from alias
9003:
9004: sub get_symb_from_alias {
9005: my $symb=shift;
9006: my ($map,$resid,$url)=&decode_symb($symb);
9007: # Already is a symb
9008: if ($url) { return $symb; }
9009: # Must be an alias
9010: my $aliassymb='';
9011: my %bighash;
1.620 albertel 9012: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9013: &GDBM_READER(),0640)) {
9014: my $rid=$bighash{'mapalias_'.$symb};
9015: if ($rid) {
9016: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9017: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9018: $resid,$bighash{'src_'.$rid});
1.427 www 9019: }
9020: untie %bighash;
9021: }
9022: return $aliassymb;
9023: }
9024:
1.12 www 9025: # ----------------------------------------------------------------- Define Role
9026:
9027: sub definerole {
9028: if (allowed('mcr','/')) {
1.1326 raeburn 9029: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9030: foreach my $role (split(':',$sysrole)) {
9031: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9032: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9033: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9034: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9035: return "refused:s:$crole&$cqual";
9036: }
9037: }
1.191 harris41 9038: }
1.800 albertel 9039: foreach my $role (split(':',$domrole)) {
9040: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9041: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9042: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9043: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9044: return "refused:d:$crole&$cqual";
9045: }
9046: }
1.191 harris41 9047: }
1.800 albertel 9048: foreach my $role (split(':',$courole)) {
9049: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9050: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9051: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9052: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9053: return "refused:c:$crole&$cqual";
9054: }
9055: }
1.191 harris41 9056: }
1.1326 raeburn 9057: my $uhome;
9058: if (($uname ne '') && ($udom ne '')) {
9059: $uhome = &homeserver($uname,$udom);
9060: return $uhome if ($uhome eq 'no_host');
9061: } else {
9062: $uname = $env{'user.name'};
9063: $udom = $env{'user.domain'};
9064: $uhome = $env{'user.home'};
9065: }
1.620 albertel 9066: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9067: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9068: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9069: return reply($command,$uhome);
1.12 www 9070: } else {
9071: return 'refused';
9072: }
1.105 harris41 9073: }
9074:
9075: # ---------------- Make a metadata query against the network of library servers
9076:
9077: sub metadata_query {
1.1237 raeburn 9078: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9079: my %rhash;
1.845 albertel 9080: my %libserv = &all_library();
1.244 matthew 9081: my @server_list = (defined($server_array) ? @$server_array
9082: : keys(%libserv) );
9083: for my $server (@server_list) {
1.1237 raeburn 9084: my $domains = '';
9085: if (ref($domains_hash) eq 'HASH') {
9086: $domains = $domains_hash->{$server};
9087: }
1.118 harris41 9088: unless ($custom or $customshow) {
1.1237 raeburn 9089: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9090: $rhash{$server}=$reply;
9091: }
9092: else {
9093: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9094: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9095: $server);
9096: $rhash{$server}=$reply;
9097: }
1.112 harris41 9098: }
1.118 harris41 9099: return \%rhash;
1.240 www 9100: }
9101:
9102: # ----------------------------------------- Send log queries and wait for reply
9103:
9104: sub log_query {
9105: my ($uname,$udom,$query,%filters)=@_;
9106: my $uhome=&homeserver($uname,$udom);
9107: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9108: my $uhost=&hostname($uhome);
1.800 albertel 9109: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9110: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9111: $uhome);
1.479 albertel 9112: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9113: return get_query_reply($queryid);
9114: }
9115:
1.818 raeburn 9116: # -------------------------- Update MySQL table for portfolio file
9117:
9118: sub update_portfolio_table {
1.821 raeburn 9119: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9120: if ($group ne '') {
9121: $file_name =~s /^\Q$group\E//;
9122: }
1.818 raeburn 9123: my $homeserver = &homeserver($uname,$udom);
9124: my $queryid=
1.821 raeburn 9125: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9126: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9127: my $reply = &get_query_reply($queryid);
9128: return $reply;
9129: }
9130:
1.899 raeburn 9131: # -------------------------- Update MySQL allusers table
9132:
9133: sub update_allusers_table {
9134: my ($uname,$udom,$names) = @_;
9135: my $homeserver = &homeserver($uname,$udom);
9136: my $queryid=
9137: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9138: 'lastname='.&escape($names->{'lastname'}).'%%'.
9139: 'firstname='.&escape($names->{'firstname'}).'%%'.
9140: 'middlename='.&escape($names->{'middlename'}).'%%'.
9141: 'generation='.&escape($names->{'generation'}).'%%'.
9142: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9143: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9144: return;
1.899 raeburn 9145: }
9146:
1.508 raeburn 9147: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9148:
9149: sub fetch_enrollment_query {
1.511 raeburn 9150: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9151: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9152: my $maxtries = 1;
1.508 raeburn 9153: if ($context eq 'automated') {
9154: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9155: $sleep = 2;
9156: $loopmax = 100;
1.547 raeburn 9157: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9158: } else {
9159: $homeserver = &homeserver($cnum,$dom);
9160: }
1.838 albertel 9161: my $host=&hostname($homeserver);
1.506 raeburn 9162: my $cmd = '';
1.1000 raeburn 9163: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9164: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9165: }
9166: $cmd =~ s/%%$//;
9167: $cmd = &escape($cmd);
9168: my $query = 'fetchenrollment';
1.620 albertel 9169: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9170: unless ($queryid=~/^\Q$host\E\_/) {
9171: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9172: return 'error: '.$queryid;
9173: }
1.1317 raeburn 9174: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9175: my $tries = 1;
9176: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9177: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9178: $tries ++;
9179: }
1.526 raeburn 9180: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9181: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9182: } else {
1.901 albertel 9183: my @responses = split(/:/,$reply);
1.1322 raeburn 9184: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9185: foreach my $line (@responses) {
9186: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9187: $$replyref{$key} = $value;
9188: }
9189: } else {
1.1117 foxr 9190: my $pathname = LONCAPA::tempdir();
1.800 albertel 9191: foreach my $line (@responses) {
9192: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9193: $$replyref{$key} = $value;
9194: if ($value > 0) {
1.800 albertel 9195: foreach my $item (@{$$affiliatesref{$key}}) {
9196: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9197: my $destname = $pathname.'/'.$filename;
9198: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9199: if ($xml_classlist =~ /^error/) {
9200: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9201: } else {
1.1359 raeburn 9202: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9203: print FILE &unescape($xml_classlist);
9204: close(FILE);
1.526 raeburn 9205: } else {
9206: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9207: }
9208: }
9209: }
9210: }
9211: }
9212: }
9213: return 'ok';
9214: }
9215: return 'error';
9216: }
9217:
1.242 www 9218: sub get_query_reply {
1.1317 raeburn 9219: my ($queryid,$sleep,$loopmax) = @_;;
9220: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9221: $sleep = 0.2;
9222: }
9223: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9224: $loopmax = 100;
9225: }
1.1117 foxr 9226: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9227: my $reply='';
1.1317 raeburn 9228: for (1..$loopmax) {
9229: sleep($sleep);
1.240 www 9230: if (-e $replyfile.'.end') {
1.1359 raeburn 9231: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9232: $reply = join('',<$fh>);
9233: close($fh);
1.240 www 9234: } else { return 'error: reply_file_error'; }
1.242 www 9235: return &unescape($reply);
9236: }
1.240 www 9237: }
1.242 www 9238: return 'timeout:'.$queryid;
1.240 www 9239: }
9240:
9241: sub courselog_query {
1.241 www 9242: #
9243: # possible filters:
9244: # url: url or symb
9245: # username
9246: # domain
9247: # action: view, submit, grade
9248: # start: timestamp
9249: # end: timestamp
9250: #
1.240 www 9251: my (%filters)=@_;
1.620 albertel 9252: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9253: if ($filters{'url'}) {
9254: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9255: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9256: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9257: }
1.620 albertel 9258: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9259: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9260: return &log_query($cname,$cdom,'courselog',%filters);
9261: }
9262:
9263: sub userlog_query {
1.858 raeburn 9264: #
9265: # possible filters:
9266: # action: log check role
9267: # start: timestamp
9268: # end: timestamp
9269: #
1.240 www 9270: my ($uname,$udom,%filters)=@_;
9271: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9272: }
9273:
1.506 raeburn 9274: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9275:
9276: sub auto_run {
1.508 raeburn 9277: my ($cnum,$cdom) = @_;
1.876 raeburn 9278: my $response = 0;
9279: my $settings;
9280: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9281: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9282: $settings = $domconfig{'autoenroll'};
9283: if ($settings->{'run'} eq '1') {
9284: $response = 1;
9285: }
9286: } else {
1.934 raeburn 9287: my $homeserver;
9288: if (&is_course($cdom,$cnum)) {
9289: $homeserver = &homeserver($cnum,$cdom);
9290: } else {
9291: $homeserver = &domain($cdom,'primary');
9292: }
9293: if ($homeserver ne 'no_host') {
9294: $response = &reply('autorun:'.$cdom,$homeserver);
9295: }
1.876 raeburn 9296: }
1.506 raeburn 9297: return $response;
9298: }
1.776 albertel 9299:
1.506 raeburn 9300: sub auto_get_sections {
1.508 raeburn 9301: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9302: my $homeserver;
9303: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9304: $homeserver = &homeserver($cnum,$cdom);
9305: }
9306: if (!defined($homeserver)) {
9307: if ($cdom =~ /^$match_domain$/) {
9308: $homeserver = &domain($cdom,'primary');
9309: }
9310: }
9311: my @secs;
9312: if (defined($homeserver)) {
9313: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9314: unless ($response eq 'refused') {
9315: @secs = split(/:/,$response);
9316: }
1.506 raeburn 9317: }
9318: return @secs;
9319: }
1.776 albertel 9320:
1.506 raeburn 9321: sub auto_new_course {
1.1099 raeburn 9322: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9323: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9324: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9325: return $response;
9326: }
1.776 albertel 9327:
1.506 raeburn 9328: sub auto_validate_courseID {
1.508 raeburn 9329: my ($cnum,$cdom,$inst_course_id) = @_;
9330: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9331: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9332: return $response;
9333: }
1.776 albertel 9334:
1.1007 raeburn 9335: sub auto_validate_instcode {
1.1020 raeburn 9336: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9337: my ($homeserver,$response);
9338: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9339: $homeserver = &homeserver($cnum,$cdom);
9340: }
9341: if (!defined($homeserver)) {
9342: if ($cdom =~ /^$match_domain$/) {
9343: $homeserver = &domain($cdom,'primary');
9344: }
9345: }
1.1065 raeburn 9346: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9347: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9348: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9349: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9350: }
9351:
1.506 raeburn 9352: sub auto_create_password {
1.873 raeburn 9353: my ($cnum,$cdom,$authparam,$udom) = @_;
9354: my ($homeserver,$response);
1.506 raeburn 9355: my $create_passwd = 0;
9356: my $authchk = '';
1.873 raeburn 9357: if ($udom =~ /^$match_domain$/) {
9358: $homeserver = &domain($udom,'primary');
9359: }
9360: if ($homeserver eq '') {
9361: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9362: $homeserver = &homeserver($cnum,$cdom);
9363: }
9364: }
9365: if ($homeserver eq '') {
9366: $authchk = 'nodomain';
1.506 raeburn 9367: } else {
1.873 raeburn 9368: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9369: if ($response eq 'refused') {
9370: $authchk = 'refused';
9371: } else {
1.901 albertel 9372: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9373: }
1.506 raeburn 9374: }
9375: return ($authparam,$create_passwd,$authchk);
9376: }
9377:
1.706 raeburn 9378: sub auto_photo_permission {
9379: my ($cnum,$cdom,$students) = @_;
9380: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9381: my ($outcome,$perm_reqd,$conditions) =
9382: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9383: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9384: return (undef,undef);
9385: }
1.706 raeburn 9386: return ($outcome,$perm_reqd,$conditions);
9387: }
9388:
9389: sub auto_checkphotos {
9390: my ($uname,$udom,$pid) = @_;
9391: my $homeserver = &homeserver($uname,$udom);
9392: my ($result,$resulttype);
9393: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9394: &escape($uname).':'.&escape($pid),
9395: $homeserver));
1.709 albertel 9396: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9397: return (undef,undef);
9398: }
1.706 raeburn 9399: if ($outcome) {
9400: ($result,$resulttype) = split(/:/,$outcome);
9401: }
9402: return ($result,$resulttype);
9403: }
9404:
9405: sub auto_photochoice {
9406: my ($cnum,$cdom) = @_;
9407: my $homeserver = &homeserver($cnum,$cdom);
9408: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9409: &escape($cdom),
9410: $homeserver)));
1.709 albertel 9411: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9412: return (undef,undef);
9413: }
1.706 raeburn 9414: return ($update,$comment);
9415: }
9416:
9417: sub auto_photoupdate {
9418: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9419: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9420: my $host=&hostname($homeserver);
1.706 raeburn 9421: my $cmd = '';
9422: my $maxtries = 1;
1.800 albertel 9423: foreach my $affiliate (keys(%{$affiliatesref})) {
9424: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9425: }
9426: $cmd =~ s/%%$//;
9427: $cmd = &escape($cmd);
9428: my $query = 'institutionalphotos';
9429: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9430: unless ($queryid=~/^\Q$host\E\_/) {
9431: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9432: return 'error: '.$queryid;
9433: }
9434: my $reply = &get_query_reply($queryid);
9435: my $tries = 1;
9436: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9437: $reply = &get_query_reply($queryid);
9438: $tries ++;
9439: }
9440: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9441: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9442: } else {
9443: my @responses = split(/:/,$reply);
9444: my $outcome = shift(@responses);
9445: foreach my $item (@responses) {
9446: my ($key,$value) = split(/=/,$item);
9447: $$photo{$key} = $value;
9448: }
9449: return $outcome;
9450: }
9451: return 'error';
9452: }
9453:
1.521 raeburn 9454: sub auto_instcode_format {
1.793 albertel 9455: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9456: $cat_order) = @_;
1.521 raeburn 9457: my $courses = '';
1.772 raeburn 9458: my @homeservers;
1.521 raeburn 9459: if ($caller eq 'global') {
1.841 albertel 9460: my %servers = &get_servers($codedom,'library');
9461: foreach my $tryserver (keys(%servers)) {
9462: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9463: push(@homeservers,$tryserver);
9464: }
1.584 raeburn 9465: }
1.1022 raeburn 9466: } elsif ($caller eq 'requests') {
9467: if ($codedom =~ /^$match_domain$/) {
9468: my $chome = &domain($codedom,'primary');
9469: unless ($chome eq 'no_host') {
9470: push(@homeservers,$chome);
9471: }
9472: }
1.521 raeburn 9473: } else {
1.772 raeburn 9474: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9475: }
1.793 albertel 9476: foreach my $code (keys(%{$instcodes})) {
9477: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9478: }
9479: chop($courses);
1.772 raeburn 9480: my $ok_response = 0;
9481: my $response;
9482: while (@homeservers > 0 && $ok_response == 0) {
9483: my $server = shift(@homeservers);
9484: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9485: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9486: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9487: split(/:/,$response);
1.772 raeburn 9488: %{$codes} = (%{$codes},&str2hash($codes_str));
9489: push(@{$codetitles},&str2array($codetitles_str));
9490: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9491: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9492: $ok_response = 1;
9493: }
9494: }
9495: if ($ok_response) {
1.521 raeburn 9496: return 'ok';
1.772 raeburn 9497: } else {
9498: return $response;
1.521 raeburn 9499: }
9500: }
9501:
1.792 raeburn 9502: sub auto_instcode_defaults {
9503: my ($domain,$returnhash,$code_order) = @_;
9504: my @homeservers;
1.841 albertel 9505:
9506: my %servers = &get_servers($domain,'library');
9507: foreach my $tryserver (keys(%servers)) {
9508: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9509: push(@homeservers,$tryserver);
9510: }
1.792 raeburn 9511: }
1.841 albertel 9512:
1.792 raeburn 9513: my $response;
1.841 albertel 9514: foreach my $server (@homeservers) {
1.792 raeburn 9515: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9516: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9517:
9518: foreach my $pair (split(/\&/,$response)) {
9519: my ($name,$value)=split(/\=/,$pair);
9520: if ($name eq 'code_order') {
9521: @{$code_order} = split(/\&/,&unescape($value));
9522: } else {
9523: $returnhash->{&unescape($name)}=&unescape($value);
9524: }
9525: }
9526: return 'ok';
1.792 raeburn 9527: }
1.841 albertel 9528:
9529: return $response;
1.1003 raeburn 9530: }
9531:
9532: sub auto_possible_instcodes {
1.1007 raeburn 9533: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9534: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9535: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9536: return;
9537: }
1.1003 raeburn 9538: my (@homeservers,$uhome);
9539: if (defined(&domain($domain,'primary'))) {
9540: $uhome=&domain($domain,'primary');
9541: push(@homeservers,&domain($domain,'primary'));
9542: } else {
9543: my %servers = &get_servers($domain,'library');
9544: foreach my $tryserver (keys(%servers)) {
9545: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9546: push(@homeservers,$tryserver);
9547: }
9548: }
9549: }
9550: my $response;
9551: foreach my $server (@homeservers) {
9552: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9553: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9554: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9555: split(':',$response);
9556: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9557: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9558: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9559: my ($name,$value)=split('=',$item);
9560: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9561: }
9562: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9563: my ($name,$value)=split('=',$item);
9564: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9565: }
9566: return 'ok';
9567: }
9568: return $response;
9569: }
1.792 raeburn 9570:
1.1010 raeburn 9571: sub auto_courserequest_checks {
9572: my ($dom) = @_;
1.1020 raeburn 9573: my ($homeserver,%validations);
9574: if ($dom =~ /^$match_domain$/) {
9575: $homeserver = &domain($dom,'primary');
9576: }
9577: unless ($homeserver eq 'no_host') {
9578: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9579: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9580: my @items = split(/&/,$response);
9581: foreach my $item (@items) {
9582: my ($key,$value) = split('=',$item);
9583: $validations{&unescape($key)} = &thaw_unescape($value);
9584: }
9585: }
9586: }
1.1010 raeburn 9587: return %validations;
9588: }
9589:
1.1020 raeburn 9590: sub auto_courserequest_validation {
1.1255 raeburn 9591: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9592: my ($homeserver,$response);
9593: if ($dom =~ /^$match_domain$/) {
9594: $homeserver = &domain($dom,'primary');
9595: }
1.1255 raeburn 9596: unless ($homeserver eq 'no_host') {
9597: my $customdata;
9598: if (ref($custominfo) eq 'HASH') {
9599: $customdata = &freeze_escape($custominfo);
9600: }
1.1020 raeburn 9601: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9602: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9603: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9604: $customdata,$homeserver));
1.1020 raeburn 9605: }
9606: return $response;
9607: }
9608:
1.777 albertel 9609: sub auto_validate_class_sec {
1.918 raeburn 9610: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9611: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9612: my $ownerlist;
9613: if (ref($owners) eq 'ARRAY') {
9614: $ownerlist = join(',',@{$owners});
9615: } else {
9616: $ownerlist = $owners;
9617: }
1.773 raeburn 9618: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9619: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9620: return $response;
9621: }
9622:
1.1367 raeburn 9623: sub auto_validate_instclasses {
9624: my ($cdom,$cnum,$owners,$classesref) = @_;
9625: my ($homeserver,%validations);
9626: $homeserver = &homeserver($cnum,$cdom);
9627: unless ($homeserver eq 'no_host') {
9628: my $ownerlist;
9629: if (ref($owners) eq 'ARRAY') {
9630: $ownerlist = join(',',@{$owners});
9631: } else {
9632: $ownerlist = $owners;
9633: }
9634: if (ref($classesref) eq 'HASH') {
9635: my $classes = &freeze_escape($classesref);
9636: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9637: ':'.$cdom.':'.$classes,$homeserver);
9638: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9639: my @items = split(/&/,$response);
9640: foreach my $item (@items) {
9641: my ($key,$value) = split('=',$item);
9642: $validations{&unescape($key)} = &thaw_unescape($value);
9643: }
9644: }
9645: }
9646: }
9647: return %validations;
9648: }
9649:
1.1248 raeburn 9650: sub auto_crsreq_update {
9651: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9652: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9653: my ($homeserver,%crsreqresponse);
9654: if ($cdom =~ /^$match_domain$/) {
9655: $homeserver = &domain($cdom,'primary');
9656: }
9657: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9658: my $info;
9659: if (ref($inbound) eq 'HASH') {
9660: $info = &freeze_escape($inbound);
9661: }
9662: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9663: ':'.&escape($action).':'.&escape($ownername).':'.
9664: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9665: &escape($title).':'.&escape($code).':'.
9666: &escape($accessstart).':'.&escape($accessend).':'.$info,
9667: $homeserver);
1.1248 raeburn 9668: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9669: my @items = split(/&/,$response);
9670: foreach my $item (@items) {
9671: my ($key,$value) = split('=',$item);
9672: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9673: }
9674: }
9675: }
9676: return \%crsreqresponse;
9677: }
9678:
1.1305 raeburn 9679: sub auto_export_grades {
1.1309 raeburn 9680: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9681: my ($homeserver,%exportresponse);
9682: if ($cdom =~ /^$match_domain$/) {
9683: $homeserver = &domain($cdom,'primary');
9684: }
9685: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9686: my $info;
9687: if (ref($inforef) eq 'HASH') {
9688: $info = &freeze_escape($inforef);
9689: }
9690: if (ref($gradesref) eq 'HASH') {
9691: my $grades = &freeze_escape($gradesref);
9692: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9693: $info.':'.$grades,$homeserver);
9694: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9695: my @items = split(/&/,$response);
9696: foreach my $item (@items) {
9697: my ($key,$value) = split('=',$item);
9698: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9699: }
9700: }
9701: }
9702: }
9703: return \%exportresponse;
1.1305 raeburn 9704: }
9705:
1.1287 raeburn 9706: sub check_instcode_cloning {
9707: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9708: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9709: return;
9710: }
9711: my $canclone;
9712: if (@{$code_order} > 0) {
9713: my $instcoderegexp ='^';
9714: my @clonecodes = split(/\&/,$cloner);
9715: foreach my $item (@{$code_order}) {
9716: if (grep(/^\Q$item\E=/,@clonecodes)) {
9717: foreach my $pair (@clonecodes) {
9718: my ($key,$val) = split(/\=/,$pair,2);
9719: $val = &unescape($val);
9720: if ($key eq $item) {
9721: $instcoderegexp .= '('.$val.')';
9722: last;
9723: }
9724: }
9725: } else {
9726: $instcoderegexp .= $codedefaults->{$item};
9727: }
9728: }
9729: $instcoderegexp .= '$';
9730: my (@from,@to);
9731: eval {
9732: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9733: (@to) = ($clonetocode =~ /$instcoderegexp/);
9734: };
9735: if ((@from > 0) && (@to > 0)) {
9736: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9737: if (!@diffs) {
9738: $canclone = 1;
9739: }
9740: }
9741: }
9742: return $canclone;
9743: }
9744:
9745: sub default_instcode_cloning {
9746: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9747: my (%codedefaults,@code_order,$canclone);
9748: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9749: %codedefaults = %{$codedefaultsref};
9750: @code_order = @{$codeorderref};
9751: } elsif ($clonedom) {
9752: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9753: }
9754: if (($domdefclone) && (@code_order)) {
9755: my @clonecodes = split(/\+/,$domdefclone);
9756: my $instcoderegexp ='^';
9757: foreach my $item (@code_order) {
9758: if (grep(/^\Q$item\E$/,@clonecodes)) {
9759: $instcoderegexp .= '('.$codedefaults{$item}.')';
9760: } else {
9761: $instcoderegexp .= $codedefaults{$item};
9762: }
9763: }
9764: $instcoderegexp .= '$';
9765: my (@from,@to);
9766: eval {
9767: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9768: (@to) = ($clonetocode =~ /$instcoderegexp/);
9769: };
9770: if ((@from > 0) && (@to > 0)) {
9771: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9772: if (!@diffs) {
9773: $canclone = 1;
9774: }
9775: }
9776: }
9777: return $canclone;
9778: }
9779:
1.679 raeburn 9780: # ------------------------------------------------------- Course Group routines
9781:
9782: sub get_coursegroups {
1.809 raeburn 9783: my ($cdom,$cnum,$group,$namespace) = @_;
9784: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9785: }
9786:
1.679 raeburn 9787: sub modify_coursegroup {
9788: my ($cdom,$cnum,$groupsettings) = @_;
9789: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9790: }
9791:
1.809 raeburn 9792: sub toggle_coursegroup_status {
9793: my ($cdom,$cnum,$group,$action) = @_;
9794: my ($from_namespace,$to_namespace);
9795: if ($action eq 'delete') {
9796: $from_namespace = 'coursegroups';
9797: $to_namespace = 'deleted_groups';
9798: } else {
9799: $from_namespace = 'deleted_groups';
9800: $to_namespace = 'coursegroups';
9801: }
9802: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9803: if (my $tmp = &error(%curr_group)) {
9804: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9805: return ('read error',$tmp);
9806: } else {
9807: my %savedsettings = %curr_group;
1.809 raeburn 9808: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9809: my $deloutcome;
9810: if ($result eq 'ok') {
1.809 raeburn 9811: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9812: } else {
9813: return ('write error',$result);
9814: }
9815: if ($deloutcome eq 'ok') {
9816: return 'ok';
9817: } else {
9818: return ('delete error',$deloutcome);
9819: }
9820: }
9821: }
9822:
1.679 raeburn 9823: sub modify_group_roles {
1.957 raeburn 9824: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9825: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9826: my $role = 'gr/'.&escape($userprivs);
9827: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9828: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9829: if ($result eq 'ok') {
9830: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9831: }
1.679 raeburn 9832: return $result;
9833: }
9834:
9835: sub modify_coursegroup_membership {
9836: my ($cdom,$cnum,$membership) = @_;
9837: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9838: return $result;
9839: }
9840:
1.682 raeburn 9841: sub get_active_groups {
9842: my ($udom,$uname,$cdom,$cnum) = @_;
9843: my $now = time;
9844: my %groups = ();
9845: foreach my $key (keys(%env)) {
1.811 albertel 9846: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9847: my ($start,$end) = split(/\./,$env{$key});
9848: if (($end!=0) && ($end<$now)) { next; }
9849: if (($start!=0) && ($start>$now)) { next; }
9850: if ($1 eq $cdom && $2 eq $cnum) {
9851: $groups{$3} = $env{$key} ;
9852: }
9853: }
9854: }
9855: return %groups;
9856: }
9857:
1.683 raeburn 9858: sub get_group_membership {
9859: my ($cdom,$cnum,$group) = @_;
9860: return(&dump('groupmembership',$cdom,$cnum,$group));
9861: }
9862:
9863: sub get_users_groups {
9864: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9865: my @usersgroups;
1.683 raeburn 9866: my $cachetime=1800;
9867:
9868: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9869: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9870: if (defined($cached)) {
1.734 albertel 9871: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9872: } else {
9873: $grouplist = '';
1.816 raeburn 9874: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9875: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9876: my $access_end = $env{'course.'.$courseid.
9877: '.default_enrollment_end_date'};
9878: my $now = time;
9879: foreach my $key (keys(%roleshash)) {
9880: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9881: my $group = $1;
9882: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9883: my $start = $2;
9884: my $end = $1;
9885: if ($start == -1) { next; } # deleted from group
9886: if (($start!=0) && ($start>$now)) { next; }
9887: if (($end!=0) && ($end<$now)) {
9888: if ($access_end && $access_end < $now) {
9889: if ($access_end - $end < 86400) {
9890: push(@usersgroups,$group);
1.733 raeburn 9891: }
9892: }
1.817 raeburn 9893: next;
1.733 raeburn 9894: }
1.817 raeburn 9895: push(@usersgroups,$group);
1.683 raeburn 9896: }
9897: }
9898: }
1.817 raeburn 9899: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9900: $grouplist = join(':',@usersgroups);
9901: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9902: }
1.733 raeburn 9903: return @usersgroups;
1.683 raeburn 9904: }
9905:
9906: sub devalidate_getgroups_cache {
9907: my ($udom,$uname,$cdom,$cnum)=@_;
9908: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9909:
1.683 raeburn 9910: my $hashid="$udom:$uname:$courseid";
9911: &devalidate_cache_new('getgroups',$hashid);
9912: }
9913:
1.12 www 9914: # ------------------------------------------------------------------ Plain Text
9915:
9916: sub plaintext {
1.988 raeburn 9917: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9918: if ($short =~ m{^cr/}) {
1.758 albertel 9919: return (split('/',$short))[-1];
9920: }
1.742 raeburn 9921: if (!defined($cid)) {
9922: $cid = $env{'request.course.id'};
9923: }
9924: my %rolenames = (
1.1008 raeburn 9925: Course => 'std',
9926: Community => 'alt1',
1.1305 raeburn 9927: Placement => 'std',
1.742 raeburn 9928: );
1.1037 raeburn 9929: if ($cid ne '') {
9930: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9931: unless ($forcedefault) {
9932: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9933: &Apache::lonlocal::mt_escape(\$roletext);
9934: return &Apache::lonlocal::mt($roletext);
9935: }
9936: }
9937: }
9938: if ((defined($type)) && (defined($rolenames{$type})) &&
9939: (defined($rolenames{$type})) &&
9940: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9941: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9942: } elsif ($cid ne '') {
9943: my $crstype = $env{'course.'.$cid.'.type'};
9944: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9945: (defined($prp{$short}{$rolenames{$crstype}}))) {
9946: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9947: }
1.742 raeburn 9948: }
1.1037 raeburn 9949: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9950: }
9951:
9952: # ----------------------------------------------------------------- Assign Role
9953:
9954: sub assignrole {
1.957 raeburn 9955: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9956: $context)=@_;
1.21 www 9957: my $mrole;
9958: if ($role =~ /^cr\//) {
1.393 www 9959: my $cwosec=$url;
1.811 albertel 9960: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9961: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9962: my $refused = 1;
9963: if ($context eq 'requestcourses') {
9964: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9965: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9966: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9967: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9968: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9969: if ($crsenv{'internal.courseowner'} eq
9970: $env{'user.name'}.':'.$env{'user.domain'}) {
9971: $refused = '';
9972: }
9973: }
9974: }
9975: }
9976: }
9977: if ($refused) {
9978: &logthis('Refused custom assignrole: '.
9979: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9980: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9981: return 'refused';
9982: }
1.104 www 9983: }
1.21 www 9984: $mrole='cr';
1.678 raeburn 9985: } elsif ($role =~ /^gr\//) {
9986: my $cwogrp=$url;
1.811 albertel 9987: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9988: unless (&allowed('mdg',$cwogrp)) {
9989: &logthis('Refused group assignrole: '.
9990: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9991: $env{'user.name'}.' at '.$env{'user.domain'});
9992: return 'refused';
9993: }
9994: $mrole='gr';
1.21 www 9995: } else {
1.82 www 9996: my $cwosec=$url;
1.811 albertel 9997: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9998: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9999: my $refused;
10000: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10001: if (!(&allowed('c'.$role,$url))) {
10002: $refused = 1;
10003: }
10004: } else {
10005: $refused = 1;
10006: }
1.947 raeburn 10007: if ($refused) {
1.1045 raeburn 10008: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10009: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10010: my %crsenv;
10011: if ($role eq 'cc' || $role eq 'co') {
10012: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10013: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10014: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10015: if ($crsenv{'internal.courseowner'} eq
10016: $env{'user.name'}.':'.$env{'user.domain'}) {
10017: $refused = '';
10018: }
10019: }
10020: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10021: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10022: if ($crsenv{'internal.courseowner'} eq
10023: $env{'user.name'}.':'.$env{'user.domain'}) {
10024: $refused = '';
10025: }
10026: }
10027: }
10028: }
1.1368 raeburn 10029: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10030: if ($role eq 'st') {
10031: $refused = '';
1.1377 raeburn 10032: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10033: $refused = '';
10034: }
1.1017 raeburn 10035: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10036: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10037: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10038: my $wrongcc;
10039: if ($cnum =~ /^$match_community$/) {
10040: $wrongcc = 1 if ($role eq 'cc');
10041: } else {
10042: $wrongcc = 1 if ($role eq 'co');
10043: }
10044: unless ($wrongcc) {
10045: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10046: if ($crsenv{'internal.courseowner'} eq
10047: $env{'user.name'}.':'.$env{'user.domain'}) {
10048: $refused = '';
10049: }
1.1017 raeburn 10050: }
10051: }
1.1183 raeburn 10052: } elsif ($context eq 'requestauthor') {
10053: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10054: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10055: if ($env{'environment.requestauthor'} eq 'automatic') {
10056: $refused = '';
10057: } else {
10058: my %domdefaults = &get_domain_defaults($udom);
10059: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10060: my $checkbystatus;
10061: if ($env{'user.adv'}) {
10062: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10063: if ($disposition eq 'automatic') {
10064: $refused = '';
10065: } elsif ($disposition eq '') {
10066: $checkbystatus = 1;
10067: }
10068: } else {
10069: $checkbystatus = 1;
10070: }
10071: if ($checkbystatus) {
10072: if ($env{'environment.inststatus'}) {
10073: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10074: foreach my $type (@inststatuses) {
10075: if (($type ne '') &&
10076: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10077: $refused = '';
10078: }
10079: }
10080: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10081: $refused = '';
10082: }
10083: }
10084: }
10085: }
10086: }
1.1017 raeburn 10087: }
10088: if ($refused) {
1.947 raeburn 10089: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10090: ' '.$role.' '.$end.' '.$start.' by '.
10091: $env{'user.name'}.' at '.$env{'user.domain'});
10092: return 'refused';
10093: }
1.932 raeburn 10094: }
1.1131 raeburn 10095: } elsif ($role eq 'au') {
10096: if ($url ne '/'.$udom.'/') {
10097: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10098: ' to assign author role for '.$uname.':'.$udom.
10099: ' in domain: '.$url.' refused (wrong domain).');
10100: return 'refused';
10101: }
1.104 www 10102: }
1.21 www 10103: $mrole=$role;
10104: }
1.620 albertel 10105: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10106: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10107: if ($end) { $command.='_'.$end; }
1.21 www 10108: if ($start) {
10109: if ($end) {
1.81 www 10110: $command.='_'.$start;
1.21 www 10111: } else {
1.81 www 10112: $command.='_0_'.$start;
1.21 www 10113: }
10114: }
1.739 raeburn 10115: my $origstart = $start;
10116: my $origend = $end;
1.957 raeburn 10117: my $delflag;
1.357 www 10118: # actually delete
10119: if ($deleteflag) {
1.373 www 10120: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10121: # modify command to delete the role
1.620 albertel 10122: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10123: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10124: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10125: # set start and finish to negative values for userrolelog
10126: $start=-1;
10127: $end=-1;
1.957 raeburn 10128: $delflag = 1;
1.357 www 10129: }
10130: }
10131: # send command
1.349 www 10132: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10133: # log new user role if status is ok
1.349 www 10134: if ($answer eq 'ok') {
1.663 raeburn 10135: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10136: if (($role eq 'cc') || ($role eq 'in') ||
10137: ($role eq 'ep') || ($role eq 'ad') ||
10138: ($role eq 'ta') || ($role eq 'st') ||
10139: ($role=~/^cr/) || ($role eq 'gr') ||
10140: ($role eq 'co')) {
1.1200 raeburn 10141: # for course roles, perform group memberships changes triggered by role change.
10142: unless ($role =~ /^gr/) {
10143: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10144: $origstart,$selfenroll,$context);
10145: }
1.1184 raeburn 10146: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10147: $selfenroll,$context);
10148: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10149: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10150: ($role eq 'da')) {
1.1184 raeburn 10151: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10152: $context);
10153: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10154: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10155: $context);
10156: }
1.1053 raeburn 10157: if ($role eq 'cc') {
10158: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10159: }
1.349 www 10160: }
10161: return $answer;
1.169 harris41 10162: }
10163:
1.1053 raeburn 10164: sub autoupdate_coowners {
10165: my ($url,$end,$start,$uname,$udom) = @_;
10166: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10167: if (($cdom ne '') && ($cnum ne '')) {
10168: my $now = time;
10169: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10170: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10171: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10172: my $instcode = $coursehash{'internal.coursecode'};
10173: if ($instcode ne '') {
1.1056 raeburn 10174: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10175: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10176: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10177: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10178: if ($result eq 'valid') {
10179: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10180: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10181: push(@newcoowners,$coowner);
10182: }
10183: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10184: push(@newcoowners,$uname.':'.$udom);
10185: }
10186: @newcoowners = sort(@newcoowners);
10187: } else {
10188: push(@newcoowners,$uname.':'.$udom);
10189: }
10190: } else {
10191: if ($coursehash{'internal.co-owners'}) {
10192: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10193: unless ($coowner eq $uname.':'.$udom) {
10194: push(@newcoowners,$coowner);
10195: }
10196: }
10197: unless (@newcoowners > 0) {
10198: $delcoowners = 1;
10199: $coowners = '';
10200: }
10201: }
10202: }
10203: if (@newcoowners || $delcoowners) {
10204: &store_coowners($cdom,$cnum,$coursehash{'home'},
10205: $delcoowners,@newcoowners);
10206: }
10207: }
10208: }
10209: }
10210: }
10211: }
10212: }
10213:
10214: sub store_coowners {
10215: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10216: my $cid = $cdom.'_'.$cnum;
10217: my ($coowners,$delresult,$putresult);
10218: if (@newcoowners) {
10219: $coowners = join(',',@newcoowners);
10220: my %coownershash = (
10221: 'internal.co-owners' => $coowners,
10222: );
10223: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10224: if ($putresult eq 'ok') {
10225: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10226: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10227: }
10228: }
10229: }
10230: if ($delcoowners) {
10231: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10232: if ($delresult eq 'ok') {
10233: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10234: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10235: }
10236: }
10237: }
10238: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10239: my %crsinfo =
10240: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10241: if (ref($crsinfo{$cid}) eq 'HASH') {
10242: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10243: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10244: }
10245: }
10246: }
10247:
1.169 harris41 10248: # -------------------------------------------------- Modify user authentication
1.197 www 10249: # Overrides without validation
10250:
1.169 harris41 10251: sub modifyuserauth {
10252: my ($udom,$uname,$umode,$upass)=@_;
10253: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10254: my $allowed;
10255: if (&allowed('mau',$udom)) {
10256: $allowed = 1;
10257: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10258: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10259: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10260: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10261: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10262: if (($cdom ne '') && ($cnum ne '')) {
10263: my $is_owner = &is_course_owner($cdom,$cnum);
10264: if ($is_owner) {
10265: $allowed = 1;
10266: }
10267: }
10268: }
10269: unless ($allowed) { return 'refused'; }
1.197 www 10270: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10271: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10272: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10273: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10274: &escape($upass),$uhome);
1.620 albertel 10275: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10276: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10277: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10278: &log($udom,,$uname,$uhome,
1.620 albertel 10279: 'Authentication changed by '.$env{'user.domain'}.', '.
10280: $env{'user.name'}.', '.$umode.
1.197 www 10281: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 10282: unless ($reply eq 'ok') {
1.197 www 10283: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10284: return 'error: '.$reply;
10285: }
1.170 harris41 10286: return 'ok';
1.80 www 10287: }
10288:
1.81 www 10289: # --------------------------------------------------------------- Modify a user
1.80 www 10290:
1.81 www 10291: sub modifyuser {
1.206 matthew 10292: my ($udom, $uname, $uid,
10293: $umode, $upass, $first,
10294: $middle, $last, $gene,
1.1058 raeburn 10295: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10296: $udom= &LONCAPA::clean_domain($udom);
10297: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10298: my $showcandelete = 'none';
10299: if (ref($candelete) eq 'ARRAY') {
10300: if (@{$candelete} > 0) {
10301: $showcandelete = join(', ',@{$candelete});
10302: }
10303: }
1.81 www 10304: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10305: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10306: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10307: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10308: ' desiredhome not specified').
1.620 albertel 10309: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10310: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10311: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10312: my $newuser;
10313: if ($uhome eq 'no_host') {
10314: $newuser = 1;
1.1368 raeburn 10315: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10316: ($umode eq 'lti')) {
10317: return 'error: more information needed to create new user';
10318: }
1.1075 raeburn 10319: }
1.80 www 10320: # ----------------------------------------------------------------- Create User
1.406 albertel 10321: if (($uhome eq 'no_host') &&
1.1368 raeburn 10322: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10323: my $unhome='';
1.844 albertel 10324: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10325: $unhome = $desiredhome;
1.620 albertel 10326: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10327: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10328: } else { # load balancing routine for determining $unhome
1.81 www 10329: my $loadm=10000000;
1.841 albertel 10330: my %servers = &get_servers($udom,'library');
10331: foreach my $tryserver (keys(%servers)) {
10332: my $answer=reply('load',$tryserver);
10333: if (($answer=~/\d+/) && ($answer<$loadm)) {
10334: $loadm=$answer;
10335: $unhome=$tryserver;
10336: }
1.80 www 10337: }
10338: }
10339: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10340: return 'error: unable to find a home server for '.$uname.
10341: ' in domain '.$udom;
1.80 www 10342: }
10343: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10344: &escape($upass),$unhome);
10345: unless ($reply eq 'ok') {
10346: return 'error: '.$reply;
10347: }
1.230 stredwic 10348: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10349: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10350: return 'error: unable verify users home machine.';
1.80 www 10351: }
1.209 matthew 10352: } # End of creation of new user
1.80 www 10353: # ---------------------------------------------------------------------- Add ID
10354: if ($uid) {
10355: $uid=~tr/A-Z/a-z/;
10356: my %uidhash=&idrget($udom,$uname);
1.196 www 10357: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10358: && (!$forceid)) {
1.80 www 10359: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10360: return 'error: user id "'.$uid.'" does not match '.
10361: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10362: }
10363: } else {
1.1300 raeburn 10364: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10365: }
10366: }
10367: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10368: my @tmp=&get('environment',
1.899 raeburn 10369: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10370: 'permanentemail','inststatus'],
1.134 albertel 10371: $udom,$uname);
1.1075 raeburn 10372: my (%names,%oldnames);
1.313 matthew 10373: if ($tmp[0] =~ m/^error:.*/) {
10374: %names=();
10375: } else {
10376: %names = @tmp;
1.1075 raeburn 10377: %oldnames = %names;
1.313 matthew 10378: }
1.388 www 10379: #
1.1058 raeburn 10380: # If name, email and/or uid are blank (e.g., because an uploaded file
10381: # of users did not contain them), do not overwrite existing values
10382: # unless field is in $candelete array ref.
10383: #
10384:
10385: my @fields = ('firstname','middlename','lastname','generation',
10386: 'permanentemail','id');
10387: my %newvalues;
10388: if (ref($candelete) eq 'ARRAY') {
10389: foreach my $field (@fields) {
10390: if (grep(/^\Q$field\E$/,@{$candelete})) {
10391: if ($field eq 'firstname') {
10392: $names{$field} = $first;
10393: } elsif ($field eq 'middlename') {
10394: $names{$field} = $middle;
10395: } elsif ($field eq 'lastname') {
10396: $names{$field} = $last;
10397: } elsif ($field eq 'generation') {
10398: $names{$field} = $gene;
10399: } elsif ($field eq 'permanentemail') {
10400: $names{$field} = $email;
10401: } elsif ($field eq 'id') {
10402: $names{$field} = $uid;
10403: }
10404: }
10405: }
10406: }
1.388 www 10407: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10408: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10409: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10410: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10411: if ($email) {
10412: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10413: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10414: }
1.899 raeburn 10415: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10416: if (defined($inststatus)) {
10417: $names{'inststatus'} = '';
10418: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10419: if (ref($usertypes) eq 'HASH') {
10420: my @okstatuses;
10421: foreach my $item (split(/:/,$inststatus)) {
10422: if (defined($usertypes->{$item})) {
10423: push(@okstatuses,$item);
10424: }
10425: }
10426: if (@okstatuses) {
10427: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10428: }
10429: }
10430: }
1.1075 raeburn 10431: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10432: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10433: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10434: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10435: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10436: } else {
10437: $logmsg .= ' during self creation';
10438: }
1.1075 raeburn 10439: my $changed;
10440: if ($newuser) {
10441: $changed = 1;
10442: } else {
10443: foreach my $field (@fields) {
10444: if ($names{$field} ne $oldnames{$field}) {
10445: $changed = 1;
10446: last;
10447: }
10448: }
10449: }
10450: unless ($changed) {
10451: $logmsg = 'No changes in user information needed for: '.$logmsg;
10452: &logthis($logmsg);
10453: return 'ok';
10454: }
10455: my $reply = &put('environment', \%names, $udom,$uname);
10456: if ($reply ne 'ok') {
10457: return 'error: '.$reply;
10458: }
1.1087 raeburn 10459: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10460: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10461: }
1.1075 raeburn 10462: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10463: &devalidate_cache_new('namescache',$uname.':'.$udom);
10464: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10465: &logthis($logmsg);
1.134 albertel 10466: return 'ok';
1.80 www 10467: }
10468:
1.81 www 10469: # -------------------------------------------------------------- Modify student
1.80 www 10470:
1.81 www 10471: sub modifystudent {
10472: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10473: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10474: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10475: if (!$cid) {
1.620 albertel 10476: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10477: return 'not_in_class';
10478: }
1.80 www 10479: }
10480: # --------------------------------------------------------------- Make the user
1.81 www 10481: my $reply=&modifyuser
1.209 matthew 10482: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10483: $desiredhome,$email,$inststatus);
1.80 www 10484: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10485: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10486: # student's environment
1.297 matthew 10487: $uid = undef if (!$forceid);
1.455 albertel 10488: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10489: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10490: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10491: return $reply;
10492: }
10493:
10494: sub modify_student_enrollment {
1.1216 raeburn 10495: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10496: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10497: my ($cdom,$cnum,$chome);
10498: if (!$cid) {
1.620 albertel 10499: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10500: return 'not_in_class';
10501: }
1.620 albertel 10502: $cdom=$env{'course.'.$cid.'.domain'};
10503: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10504: } else {
10505: ($cdom,$cnum)=split(/_/,$cid);
10506: }
1.620 albertel 10507: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10508: if (!$chome) {
1.457 raeburn 10509: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10510: }
1.455 albertel 10511: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10512: # Make sure the user exists
1.81 www 10513: my $uhome=&homeserver($uname,$udom);
10514: if (($uhome eq '') || ($uhome eq 'no_host')) {
10515: return 'error: no such user';
10516: }
1.297 matthew 10517: # Get student data if we were not given enough information
10518: if (!defined($first) || $first eq '' ||
10519: !defined($last) || $last eq '' ||
10520: !defined($uid) || $uid eq '' ||
10521: !defined($middle) || $middle eq '' ||
10522: !defined($gene) || $gene eq '') {
1.294 matthew 10523: # They did not supply us with enough data to enroll the student, so
10524: # we need to pick up more information.
1.297 matthew 10525: my %tmp = &get('environment',
1.294 matthew 10526: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10527: ,$udom,$uname);
10528:
1.800 albertel 10529: #foreach my $key (keys(%tmp)) {
10530: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10531: #}
1.294 matthew 10532: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10533: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10534: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10535: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10536: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10537: }
1.556 albertel 10538: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10539: my $user = "$uname:$udom";
10540: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10541: my $reply=cput('classlist',
1.1148 raeburn 10542: {$user =>
1.1314 raeburn 10543: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10544: $cdom,$cnum);
1.1148 raeburn 10545: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10546: &devalidate_getsection_cache($udom,$uname,$cid);
10547: } else {
1.81 www 10548: return 'error: '.$reply;
10549: }
1.297 matthew 10550: # Add student role to user
1.83 www 10551: my $uurl='/'.$cid;
1.81 www 10552: $uurl=~s/\_/\//g;
10553: if ($usec) {
10554: $uurl.='/'.$usec;
10555: }
1.1148 raeburn 10556: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10557: $selfenroll,$context);
10558: if ($result ne 'ok') {
10559: if ($old_entry{$user} ne '') {
10560: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10561: } else {
10562: $reply = &del('classlist',[$user],$cdom,$cnum);
10563: }
10564: }
10565: return $result;
1.21 www 10566: }
10567:
1.556 albertel 10568: sub format_name {
10569: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10570: my $name;
10571: if ($first ne 'lastname') {
10572: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10573: } else {
10574: if ($lastname=~/\S/) {
10575: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10576: $name=~s/\s+,/,/;
10577: } else {
10578: $name.= $firstname.' '.$middlename.' '.$generation;
10579: }
10580: }
10581: $name=~s/^\s+//;
10582: $name=~s/\s+$//;
10583: $name=~s/\s+/ /g;
10584: return $name;
10585: }
10586:
1.84 www 10587: # ------------------------------------------------- Write to course preferences
10588:
10589: sub writecoursepref {
10590: my ($courseid,%prefs)=@_;
10591: $courseid=~s/^\///;
10592: $courseid=~s/\_/\//g;
10593: my ($cdomain,$cnum)=split(/\//,$courseid);
10594: my $chome=homeserver($cnum,$cdomain);
10595: if (($chome eq '') || ($chome eq 'no_host')) {
10596: return 'error: no such course';
10597: }
10598: my $cstring='';
1.800 albertel 10599: foreach my $pref (keys(%prefs)) {
10600: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10601: }
1.84 www 10602: $cstring=~s/\&$//;
10603: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10604: }
10605:
10606: # ---------------------------------------------------------- Make/modify course
10607:
10608: sub createcourse {
1.741 raeburn 10609: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10610: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10611: $url=&declutter($url);
10612: my $cid='';
1.1028 raeburn 10613: if ($context eq 'requestcourses') {
10614: my $can_create = 0;
10615: my ($ownername,$ownerdom) = split(':',$course_owner);
10616: if ($udom eq $ownerdom) {
10617: if (&usertools_access($ownername,$ownerdom,$category,undef,
10618: $context)) {
10619: $can_create = 1;
10620: }
10621: } else {
10622: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10623: $category);
10624: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10625: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10626: if (@curr > 0) {
10627: my @options = qw(approval validate autolimit);
10628: my $optregex = join('|',@options);
10629: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10630: $can_create = 1;
10631: }
10632: }
10633: }
10634: }
10635: if ($can_create) {
10636: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10637: unless (&allowed('ccc',$udom)) {
10638: return 'refused';
10639: }
1.1017 raeburn 10640: }
10641: } else {
10642: return 'refused';
10643: }
1.1028 raeburn 10644: } elsif (!&allowed('ccc',$udom)) {
10645: return 'refused';
1.84 www 10646: }
1.1011 raeburn 10647: # --------------------------------------------------------------- Get Unique ID
10648: my $uname;
10649: if ($cnum =~ /^$match_courseid$/) {
10650: my $chome=&homeserver($cnum,$udom,'true');
10651: if (($chome eq '') || ($chome eq 'no_host')) {
10652: $uname = $cnum;
10653: } else {
1.1038 raeburn 10654: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10655: }
10656: } else {
1.1038 raeburn 10657: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10658: }
10659: return $uname if ($uname =~ /^error/);
10660: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10661: if (!defined($course_server)) {
10662: if (defined(&domain($udom,'primary'))) {
10663: $course_server = &domain($udom,'primary');
10664: } else {
10665: $course_server = $env{'user.home'};
10666: }
10667: }
10668: my %host_servers =
10669: &Apache::lonnet::get_servers($udom,'library');
10670: unless ($host_servers{$course_server}) {
10671: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10672: }
1.84 www 10673: # ------------------------------------------------------------- Make the course
10674: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10675: $course_server);
1.84 www 10676: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10677: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10678: if (($uhome eq '') || ($uhome eq 'no_host')) {
10679: return 'error: no such course';
10680: }
1.271 www 10681: # ----------------------------------------------------------------- Course made
1.516 raeburn 10682: # log existence
1.1029 raeburn 10683: my $now = time;
1.918 raeburn 10684: my $newcourse = {
10685: $udom.'_'.$uname => {
1.921 raeburn 10686: description => $description,
10687: inst_code => $inst_code,
10688: owner => $course_owner,
10689: type => $crstype,
1.1029 raeburn 10690: creator => $env{'user.name'}.':'.
10691: $env{'user.domain'},
10692: created => $now,
10693: context => $context,
1.918 raeburn 10694: },
10695: };
1.921 raeburn 10696: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10697: # set toplevel url
1.271 www 10698: my $topurl=$url;
10699: unless ($nonstandard) {
10700: # ------------------------------------------ For standard courses, make top url
10701: my $mapurl=&clutter($url);
1.278 www 10702: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10703: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10704: <map>
10705: <resource id="1" type="start"></resource>
10706: <resource id="2" src="$mapurl"></resource>
10707: <resource id="3" type="finish"></resource>
10708: <link index="1" from="1" to="2"></link>
10709: <link index="2" from="2" to="3"></link>
10710: </map>
10711: ENDINITMAP
10712: $topurl=&declutter(
1.638 albertel 10713: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10714: );
10715: }
10716: # ----------------------------------------------------------- Write preferences
1.84 www 10717: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10718: ('description' => $description,
10719: 'url' => $topurl,
10720: 'internal.creator' => $env{'user.name'}.':'.
10721: $env{'user.domain'},
10722: 'internal.created' => $now,
10723: 'internal.creationcontext' => $context)
10724: );
1.84 www 10725: return '/'.$udom.'/'.$uname;
10726: }
10727:
1.1011 raeburn 10728: # ------------------------------------------------------------------- Create ID
10729: sub generate_coursenum {
1.1038 raeburn 10730: my ($udom,$crstype) = @_;
1.1011 raeburn 10731: my $domdesc = &domain($udom);
10732: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10733: my $first;
10734: if ($crstype eq 'Community') {
10735: $first = '0';
10736: } else {
10737: $first = int(1+rand(9));
10738: }
10739: my $uname=$first.
1.1011 raeburn 10740: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10741: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10742: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10743: # ----------------------------------------------- Make sure that does not exist
10744: my $uhome=&homeserver($uname,$udom,'true');
10745: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10746: if ($crstype eq 'Community') {
10747: $first = '0';
10748: } else {
10749: $first = int(1+rand(9));
10750: }
10751: $uname=$first.
1.1011 raeburn 10752: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10753: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10754: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10755: $uhome=&homeserver($uname,$udom,'true');
10756: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10757: return 'error: unable to generate unique course-ID';
10758: }
10759: }
10760: return $uname;
10761: }
10762:
1.813 albertel 10763: sub is_course {
1.1167 droeschl 10764: my ($cdom, $cnum) = scalar(@_) == 1 ?
10765: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10766:
1.1381 raeburn 10767: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10768: my $uhome=&homeserver($cnum,$cdom);
10769: my $iscourse;
10770: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 10771: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 10772: } else {
10773: my $hashid = $cdom.':'.$cnum;
10774: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10775: unless (defined($cached)) {
10776: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10777: $cnum,undef,undef,'.');
10778: $iscourse = 0;
10779: if (exists($courses{$cdom.'_'.$cnum})) {
10780: $iscourse = 1;
10781: }
10782: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10783: }
10784: }
10785: return unless ($iscourse);
1.1167 droeschl 10786: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10787: }
10788:
1.1015 raeburn 10789: sub store_userdata {
10790: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10791: my $result;
1.1016 raeburn 10792: if ($datakey ne '') {
1.1013 raeburn 10793: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10794: if ($udom eq '' || $uname eq '') {
10795: $udom = $env{'user.domain'};
10796: $uname = $env{'user.name'};
10797: }
10798: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10799: if (($uhome eq '') || ($uhome eq 'no_host')) {
10800: $result = 'error: no_host';
10801: } else {
10802: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10803: $storehash->{'host'} = $perlvar{'lonHostID'};
10804:
10805: my $namevalue='';
10806: foreach my $key (keys(%{$storehash})) {
10807: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10808: }
10809: $namevalue=~s/\&$//;
1.1224 raeburn 10810: unless ($namespace eq 'courserequests') {
10811: $datakey = &escape($datakey);
10812: }
1.1105 raeburn 10813: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10814: $namevalue,$uhome);
1.1013 raeburn 10815: }
10816: } else {
10817: $result = 'error: data to store was not a hash reference';
10818: }
10819: } else {
10820: $result= 'error: invalid requestkey';
10821: }
10822: return $result;
10823: }
10824:
1.21 www 10825: # ---------------------------------------------------------- Assign Custom Role
10826:
10827: sub assigncustomrole {
1.957 raeburn 10828: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10829: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10830: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10831: }
10832:
10833: # ----------------------------------------------------------------- Revoke Role
10834:
10835: sub revokerole {
1.957 raeburn 10836: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10837: my $now=time;
1.965 raeburn 10838: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10839: }
10840:
10841: # ---------------------------------------------------------- Revoke Custom Role
10842:
10843: sub revokecustomrole {
1.957 raeburn 10844: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10845: my $now=time;
1.357 www 10846: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10847: $deleteflag,$selfenroll,$context);
1.17 www 10848: }
10849:
1.533 banghart 10850: # ------------------------------------------------------------ Disk usage
1.535 albertel 10851: sub diskusage {
1.955 raeburn 10852: my ($udom,$uname,$directorypath,$getpropath)=@_;
10853: $directorypath =~ s/\/$//;
10854: my $listing=&reply('du2:'.&escape($directorypath).':'
10855: .&escape($getpropath).':'.&escape($uname).':'
10856: .&escape($udom),homeserver($uname,$udom));
10857: if ($listing eq 'unknown_cmd') {
10858: if ($getpropath) {
10859: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10860: }
10861: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10862: }
1.514 albertel 10863: return $listing;
1.512 banghart 10864: }
10865:
1.566 banghart 10866: sub is_locked {
1.1096 raeburn 10867: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10868: my @check;
10869: my $is_locked;
1.1093 raeburn 10870: push (@check,$file_name);
1.613 albertel 10871: my %locked = &get('file_permissions',\@check,
1.620 albertel 10872: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10873: my ($tmp)=keys(%locked);
10874: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10875:
1.566 banghart 10876: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10877: $is_locked = 'false';
10878: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10879: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10880: $is_locked = 'true';
1.1096 raeburn 10881: if (ref($which) eq 'ARRAY') {
10882: push(@{$which},$entry);
10883: } else {
10884: last;
10885: }
1.745 raeburn 10886: }
10887: }
1.566 banghart 10888: } else {
10889: $is_locked = 'false';
10890: }
1.1093 raeburn 10891: return $is_locked;
1.566 banghart 10892: }
10893:
1.759 albertel 10894: sub declutter_portfile {
10895: my ($file) = @_;
1.833 albertel 10896: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10897: return $file;
10898: }
10899:
1.559 banghart 10900: # ------------------------------------------------------------- Mark as Read Only
10901:
10902: sub mark_as_readonly {
10903: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10904: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10905: my ($tmp)=keys(%current_permissions);
10906: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10907: foreach my $file (@{$files}) {
1.759 albertel 10908: $file = &declutter_portfile($file);
1.561 banghart 10909: push(@{$current_permissions{$file}},$what);
1.559 banghart 10910: }
1.613 albertel 10911: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10912: return;
10913: }
10914:
1.572 banghart 10915: # ------------------------------------------------------------Save Selected Files
10916:
10917: sub save_selected_files {
10918: my ($user, $path, @files) = @_;
10919: my $filename = $user."savedfiles";
1.573 banghart 10920: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 10921: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10922: foreach my $file (@files) {
1.620 albertel 10923: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10924: }
10925: foreach my $file (@other_files) {
1.574 banghart 10926: print (OUT $file."\n");
1.572 banghart 10927: }
1.574 banghart 10928: close (OUT);
1.572 banghart 10929: return 'ok';
10930: }
10931:
1.574 banghart 10932: sub clear_selected_files {
10933: my ($user) = @_;
10934: my $filename = $user."savedfiles";
1.1359 raeburn 10935: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10936: print (OUT undef);
10937: close (OUT);
10938: return ("ok");
10939: }
10940:
1.572 banghart 10941: sub files_in_path {
10942: my ($user, $path) = @_;
10943: my $filename = $user."savedfiles";
10944: my %return_files;
1.1359 raeburn 10945: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10946: while (my $line_in = <IN>) {
1.574 banghart 10947: chomp ($line_in);
10948: my @paths_and_file = split (m!/!, $line_in);
10949: my $file_part = pop (@paths_and_file);
10950: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10951: $path_part.='/';
10952: my $path_and_file = $path_part.$file_part;
10953: if ($path_part eq $path) {
10954: $return_files{$file_part}= 'selected';
10955: }
10956: }
1.574 banghart 10957: close (IN);
10958: return (\%return_files);
1.572 banghart 10959: }
10960:
10961: # called in portfolio select mode, to show files selected NOT in current directory
10962: sub files_not_in_path {
10963: my ($user, $path) = @_;
10964: my $filename = $user."savedfiles";
10965: my @return_files;
10966: my $path_part;
1.1359 raeburn 10967: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10968: while (my $line = <IN>) {
1.572 banghart 10969: #ok, I know it's clunky, but I want it to work
1.800 albertel 10970: my @paths_and_file = split(m|/|, $line);
10971: my $file_part = pop(@paths_and_file);
10972: chomp($file_part);
10973: my $path_part = join('/', @paths_and_file);
1.572 banghart 10974: $path_part .= '/';
10975: my $path_and_file = $path_part.$file_part;
10976: if ($path_part ne $path) {
1.800 albertel 10977: push(@return_files, ($path_and_file));
1.572 banghart 10978: }
10979: }
1.800 albertel 10980: close(OUT);
1.574 banghart 10981: return (@return_files);
1.572 banghart 10982: }
10983:
1.1273 raeburn 10984: #------------------------------Submitted/Handedback Portfolio Files Versioning
10985:
10986: sub portfiles_versioning {
10987: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10988: my $portfolio_root = '/userfiles/portfolio';
10989: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10990: foreach my $file (@{$portfiles}) {
10991: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10992: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10993: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10994: my $getpropath = 1;
10995: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10996: $stu_name,$getpropath);
10997: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10998: my $new_answer =
10999: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11000: if ($new_answer ne 'problem getting file') {
11001: push(@{$versioned_portfiles}, $directory.$new_answer);
11002: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11003: [$symb,$env{'request.course.id'},'graded']);
11004: }
11005: }
11006: }
11007:
11008: sub get_next_version {
11009: my ($answer_name, $answer_ext, $dir_list) = @_;
11010: my $version;
11011: if (ref($dir_list) eq 'ARRAY') {
11012: foreach my $row (@{$dir_list}) {
11013: my ($file) = split(/\&/,$row,2);
11014: my ($file_name,$file_version,$file_ext) =
11015: &file_name_version_ext($file);
11016: if (($file_name eq $answer_name) &&
11017: ($file_ext eq $answer_ext)) {
11018: # gets here if filename and extension match,
11019: # regardless of version
11020: if ($file_version ne '') {
11021: # a versioned file is found so save it for later
11022: if ($file_version > $version) {
11023: $version = $file_version;
11024: }
11025: }
11026: }
11027: }
11028: }
11029: $version ++;
11030: return($version);
11031: }
11032:
11033: sub version_selected_portfile {
11034: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11035: my ($answer_name,$answer_ver,$answer_ext) =
11036: &file_name_version_ext($file_name);
11037: my $new_answer;
11038: $env{'form.copy'} =
11039: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11040: if($env{'form.copy'} eq '-1') {
11041: $new_answer = 'problem getting file';
11042: } else {
11043: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11044: my $copy_result =
11045: &finishuserfileupload($stu_name,$domain,'copy',
11046: '/portfolio'.$directory.$new_answer);
11047: }
11048: undef($env{'form.copy'});
11049: return ($new_answer);
11050: }
11051:
11052: sub file_name_version_ext {
11053: my ($file)=@_;
11054: my @file_parts = split(/\./, $file);
11055: my ($name,$version,$ext);
11056: if (@file_parts > 1) {
11057: $ext=pop(@file_parts);
11058: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11059: $version=pop(@file_parts);
11060: }
11061: $name=join('.',@file_parts);
11062: } else {
11063: $name=join('.',@file_parts);
11064: }
11065: return($name,$version,$ext);
11066: }
11067:
1.745 raeburn 11068: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11069:
1.745 raeburn 11070: sub get_portfile_permissions {
11071: my ($domain,$user) = @_;
1.613 albertel 11072: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11073: my ($tmp)=keys(%current_permissions);
11074: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11075: return \%current_permissions;
11076: }
11077:
11078: #---------------------------------------------Get portfolio file access controls
11079:
1.749 raeburn 11080: sub get_access_controls {
1.745 raeburn 11081: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11082: my %access;
11083: my $real_file = $file;
11084: $file =~ s/\.meta$//;
1.745 raeburn 11085: if (defined($file)) {
1.749 raeburn 11086: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11087: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11088: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11089: }
11090: }
1.745 raeburn 11091: } else {
1.749 raeburn 11092: foreach my $key (keys(%{$current_permissions})) {
11093: if ($key =~ /\0accesscontrol$/) {
11094: if (defined($group)) {
11095: if ($key !~ m-^\Q$group\E/-) {
11096: next;
11097: }
11098: }
11099: my ($fullpath) = split(/\0/,$key);
11100: if (ref($$current_permissions{$key}) eq 'HASH') {
11101: foreach my $control (keys(%{$$current_permissions{$key}})) {
11102: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11103: }
11104: }
11105: }
11106: }
11107: }
11108: return %access;
11109: }
11110:
11111: sub modify_access_controls {
11112: my ($file_name,$changes,$domain,$user)=@_;
11113: my ($outcome,$deloutcome);
11114: my %store_permissions;
11115: my %new_values;
11116: my %new_control;
11117: my %translation;
11118: my @deletions = ();
11119: my $now = time;
11120: if (exists($$changes{'activate'})) {
11121: if (ref($$changes{'activate'}) eq 'HASH') {
11122: my @newitems = sort(keys(%{$$changes{'activate'}}));
11123: my $numnew = scalar(@newitems);
11124: for (my $i=0; $i<$numnew; $i++) {
11125: my $newkey = $newitems[$i];
11126: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11127: if ($newkey =~ /^\d+:/) {
11128: $newkey =~ s/^(\d+)/$newid/;
11129: $translation{$1} = $newid;
11130: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11131: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11132: $translation{$1} = $newid;
11133: }
1.749 raeburn 11134: $new_values{$file_name."\0".$newkey} =
11135: $$changes{'activate'}{$newitems[$i]};
11136: $new_control{$newkey} = $now;
11137: }
11138: }
11139: }
11140: my %todelete;
11141: my %changed_items;
11142: foreach my $action ('delete','update') {
11143: if (exists($$changes{$action})) {
11144: if (ref($$changes{$action}) eq 'HASH') {
11145: foreach my $key (keys(%{$$changes{$action}})) {
11146: my ($itemnum) = ($key =~ /^([^:]+):/);
11147: if ($action eq 'delete') {
11148: $todelete{$itemnum} = 1;
11149: } else {
11150: $changed_items{$itemnum} = $key;
11151: }
11152: }
1.745 raeburn 11153: }
11154: }
1.749 raeburn 11155: }
11156: # get lock on access controls for file.
11157: my $lockhash = {
11158: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11159: ':'.$env{'user.domain'},
11160: };
11161: my $tries = 0;
11162: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11163:
1.1288 damieng 11164: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11165: $tries ++;
1.1289 damieng 11166: sleep(0.1);
1.749 raeburn 11167: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11168: }
11169: if ($gotlock eq 'ok') {
11170: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11171: my ($tmp)=keys(%curr_permissions);
11172: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11173: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11174: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11175: if (ref($curr_controls) eq 'HASH') {
11176: foreach my $control_item (keys(%{$curr_controls})) {
11177: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11178: if (defined($todelete{$itemnum})) {
11179: push(@deletions,$file_name."\0".$control_item);
11180: } else {
11181: if (defined($changed_items{$itemnum})) {
11182: $new_control{$changed_items{$itemnum}} = $now;
11183: push(@deletions,$file_name."\0".$control_item);
11184: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11185: } else {
11186: $new_control{$control_item} = $$curr_controls{$control_item};
11187: }
11188: }
1.745 raeburn 11189: }
11190: }
11191: }
1.970 raeburn 11192: my ($group);
11193: if (&is_course($domain,$user)) {
11194: ($group,my $file) = split(/\//,$file_name,2);
11195: }
1.749 raeburn 11196: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11197: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11198: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11199: # remove lock
11200: my @del_lock = ($file_name."\0".'locked_access_records');
11201: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11202: my $sqlresult =
1.970 raeburn 11203: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11204: $group);
1.749 raeburn 11205: } else {
11206: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11207: }
1.749 raeburn 11208: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11209: }
11210:
1.827 raeburn 11211: sub make_public_indefinitely {
1.1271 raeburn 11212: my (@requrl) = @_;
11213: return &automated_portfile_access('public',\@requrl);
11214: }
11215:
11216: sub automated_portfile_access {
11217: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11218: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11219: return 'invalid';
11220: }
1.1271 raeburn 11221: my %urls;
11222: if (ref($addsref) eq 'ARRAY') {
11223: foreach my $requrl (@{$addsref}) {
11224: if (&is_portfolio_url($requrl)) {
11225: unless (exists($urls{$requrl})) {
11226: $urls{$requrl} = 'add';
11227: }
11228: }
11229: }
11230: }
11231: if (ref($delsref) eq 'ARRAY') {
11232: foreach my $requrl (@{$delsref}) {
11233: if (&is_portfolio_url($requrl)) {
11234: unless (exists($urls{$requrl})) {
11235: $urls{$requrl} = 'delete';
11236: }
11237: }
11238: }
11239: }
11240: unless (keys(%urls)) {
11241: return 'invalid';
11242: }
11243: my $ip;
11244: if ($accesstype eq 'ip') {
11245: if (ref($info) eq 'HASH') {
11246: if ($info->{'ip'} ne '') {
11247: $ip = $info->{'ip'};
11248: }
11249: }
11250: if ($ip eq '') {
11251: return 'invalid';
11252: }
11253: }
11254: my $errors;
1.827 raeburn 11255: my $now = time;
1.1271 raeburn 11256: my %current_perms;
11257: foreach my $requrl (sort(keys(%urls))) {
11258: my $action;
11259: if ($urls{$requrl} eq 'add') {
11260: $action = 'activate';
11261: } else {
11262: $action = 'none';
11263: }
11264: my $aclnum = 0;
1.827 raeburn 11265: my (undef,$udom,$unum,$file_name,$group) =
11266: &parse_portfolio_url($requrl);
1.1271 raeburn 11267: unless (exists($current_perms{$unum.':'.$udom})) {
11268: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11269: }
11270: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11271: $group,$file_name);
11272: foreach my $key (keys(%{$access_controls{$file_name}})) {
11273: my ($num,$scope,$end,$start) =
11274: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11275: if ($scope eq $accesstype) {
11276: if (($start <= $now) && ($end == 0)) {
11277: if ($accesstype eq 'ip') {
11278: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11279: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11280: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11281: if ($urls{$requrl} eq 'add') {
11282: $action = 'none';
11283: last;
11284: } else {
11285: $action = 'delete';
11286: $aclnum = $num;
11287: last;
11288: }
11289: }
11290: }
11291: }
11292: } elsif ($accesstype eq 'public') {
11293: if ($urls{$requrl} eq 'add') {
11294: $action = 'none';
11295: last;
11296: } else {
11297: $action = 'delete';
11298: $aclnum = $num;
11299: last;
11300: }
11301: }
11302: } elsif ($accesstype eq 'public') {
1.827 raeburn 11303: $action = 'update';
11304: $aclnum = $num;
1.1271 raeburn 11305: last;
1.827 raeburn 11306: }
11307: }
11308: }
11309: if ($action eq 'none') {
1.1271 raeburn 11310: next;
1.827 raeburn 11311: } else {
11312: my %changes;
11313: my $newend = 0;
11314: my $newstart = $now;
1.1271 raeburn 11315: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11316: $changes{$action}{$newkey} = {
1.1271 raeburn 11317: type => $accesstype,
1.827 raeburn 11318: time => {
11319: start => $newstart,
11320: end => $newend,
11321: },
11322: };
1.1271 raeburn 11323: if ($accesstype eq 'ip') {
11324: $changes{$action}{$newkey}{'ip'} = [$ip];
11325: }
1.827 raeburn 11326: my ($outcome,$deloutcome,$new_values,$translation) =
11327: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11328: unless ($outcome eq 'ok') {
11329: $errors .= $outcome.' ';
11330: }
1.827 raeburn 11331: }
1.1271 raeburn 11332: }
11333: if ($errors) {
11334: $errors =~ s/\s$//;
11335: return $errors;
1.827 raeburn 11336: } else {
1.1271 raeburn 11337: return 'ok';
1.827 raeburn 11338: }
11339: }
11340:
1.745 raeburn 11341: #------------------------------------------------------Get Marked as Read Only
11342:
11343: sub get_marked_as_readonly {
11344: my ($domain,$user,$what,$group) = @_;
11345: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11346: my @readonly_files;
1.629 banghart 11347: my $cmp1=$what;
11348: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11349: while (my ($file_name,$value) = each(%{$current_permissions})) {
11350: if (defined($group)) {
11351: if ($file_name !~ m-^\Q$group\E/-) {
11352: next;
11353: }
11354: }
1.561 banghart 11355: if (ref($value) eq "ARRAY"){
11356: foreach my $stored_what (@{$value}) {
1.629 banghart 11357: my $cmp2=$stored_what;
1.759 albertel 11358: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11359: $cmp2=join('',@{$stored_what});
1.745 raeburn 11360: }
1.629 banghart 11361: if ($cmp1 eq $cmp2) {
1.561 banghart 11362: push(@readonly_files, $file_name);
1.745 raeburn 11363: last;
1.563 banghart 11364: } elsif (!defined($what)) {
11365: push(@readonly_files, $file_name);
1.745 raeburn 11366: last;
1.561 banghart 11367: }
11368: }
1.745 raeburn 11369: }
1.561 banghart 11370: }
11371: return @readonly_files;
11372: }
1.577 banghart 11373: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11374:
1.577 banghart 11375: sub get_marked_as_readonly_hash {
1.745 raeburn 11376: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11377: my %readonly_files;
1.745 raeburn 11378: while (my ($file_name,$value) = each(%{$current_permissions})) {
11379: if (defined($group)) {
11380: if ($file_name !~ m-^\Q$group\E/-) {
11381: next;
11382: }
11383: }
1.577 banghart 11384: if (ref($value) eq "ARRAY"){
11385: foreach my $stored_what (@{$value}) {
1.745 raeburn 11386: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11387: foreach my $lock_descriptor(@{$stored_what}) {
11388: if ($lock_descriptor eq 'graded') {
11389: $readonly_files{$file_name} = 'graded';
11390: } elsif ($lock_descriptor eq 'handback') {
11391: $readonly_files{$file_name} = 'handback';
11392: } else {
11393: if (!exists($readonly_files{$file_name})) {
11394: $readonly_files{$file_name} = 'locked';
11395: }
11396: }
1.745 raeburn 11397: }
1.750 banghart 11398: }
1.577 banghart 11399: }
11400: }
11401: }
11402: return %readonly_files;
11403: }
1.559 banghart 11404: # ------------------------------------------------------------ Unmark as Read Only
11405:
11406: sub unmark_as_readonly {
1.629 banghart 11407: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11408: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11409: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11410: $file_name = &declutter_portfile($file_name);
1.634 albertel 11411: my $symb_crs = $what;
11412: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11413: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11414: my ($tmp)=keys(%current_permissions);
11415: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11416: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11417: foreach my $file (@readonly_files) {
1.759 albertel 11418: my $clean_file = &declutter_portfile($file);
11419: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11420: my $current_locks = $current_permissions{$file};
1.563 banghart 11421: my @new_locks;
11422: my @del_keys;
11423: if (ref($current_locks) eq "ARRAY"){
11424: foreach my $locker (@{$current_locks}) {
1.632 albertel 11425: my $compare=$locker;
1.749 raeburn 11426: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11427: $compare=join('',@{$locker});
1.746 raeburn 11428: if ($compare ne $symb_crs) {
11429: push(@new_locks, $locker);
11430: }
1.563 banghart 11431: }
11432: }
1.650 albertel 11433: if (scalar(@new_locks) > 0) {
1.563 banghart 11434: $current_permissions{$file} = \@new_locks;
11435: } else {
11436: push(@del_keys, $file);
1.613 albertel 11437: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11438: delete($current_permissions{$file});
1.563 banghart 11439: }
11440: }
1.561 banghart 11441: }
1.613 albertel 11442: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11443: return;
11444: }
1.512 banghart 11445:
1.17 www 11446: # ------------------------------------------------------------ Directory lister
11447:
11448: sub dirlist {
1.955 raeburn 11449: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11450: $uri=~s/^\///;
11451: $uri=~s/\/$//;
1.253 stredwic 11452: my ($udom, $uname);
1.955 raeburn 11453: if ($getuserdir) {
1.253 stredwic 11454: $udom = $userdomain;
11455: $uname = $username;
1.955 raeburn 11456: } else {
11457: (undef,$udom,$uname)=split(/\//,$uri);
11458: if(defined($userdomain)) {
11459: $udom = $userdomain;
11460: }
11461: if(defined($username)) {
11462: $uname = $username;
11463: }
1.253 stredwic 11464: }
1.955 raeburn 11465: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11466:
1.955 raeburn 11467: $dirRoot = $perlvar{'lonDocRoot'};
11468: if (defined($getpropath)) {
11469: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11470: $dirRoot =~ s/\/$//;
1.955 raeburn 11471: } elsif (defined($getuserdir)) {
11472: my $subdir=$uname.'__';
11473: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11474: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11475: ."/$udom/$subdir/$uname";
11476: } elsif (defined($alternateRoot)) {
11477: $dirRoot = $alternateRoot;
1.751 banghart 11478: }
1.253 stredwic 11479:
11480: if($udom) {
11481: if($uname) {
1.1135 raeburn 11482: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11483: if ($uhome eq 'no_host') {
11484: return ([],'no_host');
11485: }
1.955 raeburn 11486: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11487: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11488: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11489: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11490: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11491: } else {
11492: @listing_results = map { &unescape($_); } split(/:/,$listing);
11493: }
1.605 matthew 11494: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11495: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11496: @listing_results = split(/:/,$listing);
11497: } else {
11498: @listing_results = map { &unescape($_); } split(/:/,$listing);
11499: }
1.1135 raeburn 11500: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11501: ($listing eq 'rejected') || ($listing eq 'refused') ||
11502: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11503: return ([],$listing);
11504: } else {
11505: return (\@listing_results);
1.1135 raeburn 11506: }
1.955 raeburn 11507: } elsif(!$alternateRoot) {
1.1136 raeburn 11508: my (%allusers,%listerror);
1.841 albertel 11509: my %servers = &get_servers($udom,'library');
1.955 raeburn 11510: foreach my $tryserver (keys(%servers)) {
11511: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11512: &escape($udom),$tryserver);
11513: if ($listing eq 'unknown_cmd') {
11514: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11515: $udom, $tryserver);
11516: } else {
11517: @listing_results = map { &unescape($_); } split(/:/,$listing);
11518: }
1.841 albertel 11519: if ($listing eq 'unknown_cmd') {
11520: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11521: $udom, $tryserver);
11522: @listing_results = split(/:/,$listing);
11523: } else {
11524: @listing_results =
11525: map { &unescape($_); } split(/:/,$listing);
11526: }
1.1136 raeburn 11527: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11528: ($listing eq 'rejected') || ($listing eq 'refused') ||
11529: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11530: $listerror{$tryserver} = $listing;
11531: } else {
1.841 albertel 11532: foreach my $line (@listing_results) {
11533: my ($entry) = split(/&/,$line,2);
11534: $allusers{$entry} = 1;
11535: }
11536: }
1.253 stredwic 11537: }
1.1136 raeburn 11538: my @alluserslist=();
1.800 albertel 11539: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11540: push(@alluserslist,$user.'&user');
1.253 stredwic 11541: }
1.1318 droeschl 11542:
11543: if (!%listerror) {
11544: # no errors
11545: return (\@alluserslist);
11546: } elsif (scalar(keys(%servers)) == 1) {
11547: # one library server, one error
11548: my ($key) = keys(%listerror);
11549: return (\@alluserslist, $listerror{$key});
11550: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11551: # con_lost indicates that we might miss data from at least one
11552: # library server
11553: return (\@alluserslist, 'con_lost');
11554: } else {
11555: # multiple library servers and no con_lost -> data should be
11556: # complete.
11557: return (\@alluserslist);
11558: }
11559:
1.253 stredwic 11560: } else {
1.1136 raeburn 11561: return ([],'missing username');
1.253 stredwic 11562: }
1.955 raeburn 11563: } elsif(!defined($getpropath)) {
1.1136 raeburn 11564: my $path = $perlvar{'lonDocRoot'}.'/res/';
11565: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11566: return (\@all_domains);
1.955 raeburn 11567: } else {
1.1136 raeburn 11568: return ([],'missing domain');
1.275 stredwic 11569: }
11570: }
11571:
11572: # --------------------------------------------- GetFileTimestamp
11573: # This function utilizes dirlist and returns the date stamp for
11574: # when it was last modified. It will also return an error of -1
11575: # if an error occurs
11576:
11577: sub GetFileTimestamp {
1.955 raeburn 11578: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11579: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11580: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11581: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11582: undef,$getuserdir);
11583: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11584: return -1;
11585: }
11586: if (ref($fileref) eq 'ARRAY') {
11587: my @stats = split('&',$fileref->[0]);
1.375 matthew 11588: # @stats contains first the filename, then the stat output
11589: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11590: } else {
11591: return -1;
1.253 stredwic 11592: }
1.26 www 11593: }
11594:
1.712 albertel 11595: sub stat_file {
11596: my ($uri) = @_;
1.787 albertel 11597: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11598:
1.955 raeburn 11599: my ($udom,$uname,$file);
1.712 albertel 11600: if ($uri =~ m-^/(uploaded|editupload)/-) {
11601: ($udom,$uname,$file) =
1.811 albertel 11602: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11603: $file = 'userfiles/'.$file;
11604: }
11605: if ($uri =~ m-^/res/-) {
11606: ($udom,$uname) =
1.807 albertel 11607: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11608: $file = $uri;
11609: }
11610:
11611: if (!$udom || !$uname || !$file) {
11612: # unable to handle the uri
11613: return ();
11614: }
1.956 raeburn 11615: my $getpropath;
11616: if ($file =~ /^userfiles\//) {
11617: $getpropath = 1;
11618: }
1.1136 raeburn 11619: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11620: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11621: return ();
11622: } else {
11623: if (ref($listref) eq 'ARRAY') {
11624: my @stats = split('&',$listref->[0]);
11625: shift(@stats); #filename is first
11626: return @stats;
11627: }
1.712 albertel 11628: }
11629: return ();
11630: }
11631:
1.1313 raeburn 11632: # --------------------------------------------------------- recursedirs
11633: # Recursive function to traverse either a specific user's Authoring Space
11634: # or corresponding Published Resource Space, and populate the hash ref:
11635: # $dirhashref with URLs of all directories, and if $filehashref hash
11636: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11637: # or .rights files in resource space, and .meta, .save, .log, and .bak
11638: # files in Authoring Space.
11639: #
11640: # Inputs:
11641: #
11642: # $is_home - true if current server is home server for user's space
11643: # $context - either: priv, or res respectively for Authoring or Resource Space.
11644: # $docroot - Document root (i.e., /home/httpd/html
11645: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11646: # $relpath - Current path (relative to top level).
11647: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11648: # $filehashref - reference to hash to populate with URLs of files (Optional)
11649: #
11650: # Returns: nothing
11651: #
11652: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11653: #
11654: # Currently used by interface/londocs.pm to create linked select boxes for
11655: # directory and filename to import a Course "Author" resource into a course, and
11656: # also to create linked select boxes for Authoring Space and Directory to choose
11657: # save location for creation of a new "standard" problem from the Course Editor.
11658: #
11659:
11660: sub recursedirs {
11661: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11662: return unless (ref($dirhashref) eq 'HASH');
11663: my $currpath = $docroot.$toppath;
11664: if ($relpath) {
11665: $currpath .= "/$relpath";
11666: }
11667: my $savefile;
11668: if (ref($filehashref)) {
11669: $savefile = 1;
11670: }
11671: if ($is_home) {
11672: if (opendir(my $dirh,$currpath)) {
11673: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11674: next if ($item eq '');
11675: if (-d "$currpath/$item") {
11676: my $newpath;
11677: if ($relpath) {
11678: $newpath = "$relpath/$item";
11679: } else {
11680: $newpath = $item;
11681: }
11682: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11683: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11684: } elsif ($savefile) {
11685: if ($context eq 'priv') {
11686: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11687: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11688: }
11689: } else {
11690: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11691: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11692: }
11693: }
11694: }
11695: }
11696: closedir($dirh);
11697: }
11698: } else {
11699: my ($dirlistref,$listerror) =
11700: &dirlist($toppath.$relpath);
11701: my @dir_lines;
11702: my $dirptr=16384;
11703: if (ref($dirlistref) eq 'ARRAY') {
11704: foreach my $dir_line (sort
11705: {
11706: my ($afile)=split('&',$a,2);
11707: my ($bfile)=split('&',$b,2);
11708: return (lc($afile) cmp lc($bfile));
11709: } (@{$dirlistref})) {
11710: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11711: split(/\&/,$dir_line,16);
11712: $item =~ s/\s+$//;
11713: next if (($item =~ /^\.\.?$/) || ($obs));
11714: if ($dirptr&$testdir) {
11715: my $newpath;
11716: if ($relpath) {
11717: $newpath = "$relpath/$item";
11718: } else {
11719: $relpath = '/';
11720: $newpath = $item;
11721: }
11722: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11723: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11724: } elsif ($savefile) {
11725: if ($context eq 'priv') {
11726: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11727: $filehashref->{$relpath}{$item} = 1;
11728: }
11729: } else {
11730: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11731: $filehashref->{$relpath}{$item} = 1;
11732: }
11733: }
11734: }
11735: }
11736: }
11737: }
11738: return;
11739: }
11740:
1.26 www 11741: # -------------------------------------------------------- Value of a Condition
11742:
1.713 albertel 11743: # gets the value of a specific preevaluated condition
11744: # stored in the string $env{user.state.<cid>}
11745: # or looks up a condition reference in the bighash and if if hasn't
11746: # already been evaluated recurses into docondval to get the value of
11747: # the condition, then memoizing it to
11748: # $env{user.state.<cid>.<condition>}
1.40 www 11749: sub directcondval {
11750: my $number=shift;
1.620 albertel 11751: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11752: &Apache::lonuserstate::evalstate();
11753: }
1.713 albertel 11754: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11755: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11756: } elsif ($number =~ /^_/) {
11757: my $sub_condition;
11758: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11759: &GDBM_READER(),0640)) {
11760: $sub_condition=$bighash{'conditions'.$number};
11761: untie(%bighash);
11762: }
11763: my $value = &docondval($sub_condition);
1.949 raeburn 11764: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11765: return $value;
11766: }
1.620 albertel 11767: if ($env{'user.state.'.$env{'request.course.id'}}) {
11768: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11769: } else {
11770: return 2;
11771: }
11772: }
11773:
1.713 albertel 11774: # get the collection of conditions for this resource
1.26 www 11775: sub condval {
11776: my $condidx=shift;
1.54 www 11777: my $allpathcond='';
1.713 albertel 11778: foreach my $cond (split(/\|/,$condidx)) {
11779: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11780: $allpathcond.=
11781: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11782: }
1.191 harris41 11783: }
1.54 www 11784: $allpathcond=~s/\|$//;
1.713 albertel 11785: return &docondval($allpathcond);
11786: }
11787:
11788: #evaluates an expression of conditions
11789: sub docondval {
11790: my ($allpathcond) = @_;
11791: my $result=0;
11792: if ($env{'request.course.id'}
11793: && defined($allpathcond)) {
11794: my $operand='|';
11795: my @stack;
11796: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11797: if ($chunk eq '(') {
11798: push @stack,($operand,$result);
11799: } elsif ($chunk eq ')') {
11800: my $before=pop @stack;
11801: if (pop @stack eq '&') {
11802: $result=$result>$before?$before:$result;
11803: } else {
11804: $result=$result>$before?$result:$before;
11805: }
11806: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11807: $operand=$chunk;
11808: } else {
11809: my $new=directcondval($chunk);
11810: if ($operand eq '&') {
11811: $result=$result>$new?$new:$result;
11812: } else {
11813: $result=$result>$new?$result:$new;
11814: }
11815: }
11816: }
1.26 www 11817: }
11818: return $result;
1.421 albertel 11819: }
11820:
11821: # ---------------------------------------------------- Devalidate courseresdata
11822:
11823: sub devalidatecourseresdata {
11824: my ($coursenum,$coursedomain)=@_;
11825: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11826: &devalidate_cache_new('courseres',$hashid);
1.28 www 11827: }
11828:
1.763 www 11829:
1.200 www 11830: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11831: #
11832: # Parameters:
11833: # $coursenum - Number of the course.
11834: # $coursedomain - Domain at which the course was created.
11835: # Returns:
11836: # A hash of the course parameters along (I think) with timestamps
11837: # and version info.
1.877 foxr 11838:
1.624 albertel 11839: sub get_courseresdata {
11840: my ($coursenum,$coursedomain)=@_;
1.200 www 11841: my $coursehom=&homeserver($coursenum,$coursedomain);
11842: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11843: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11844: my %dumpreply;
1.417 albertel 11845: unless (defined($cached)) {
1.624 albertel 11846: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11847: $result=\%dumpreply;
1.251 albertel 11848: my ($tmp) = keys(%dumpreply);
11849: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11850: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11851: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11852: return $tmp;
1.416 albertel 11853: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11854: $result=undef;
1.599 albertel 11855: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11856: }
11857: }
1.624 albertel 11858: return $result;
11859: }
11860:
1.633 albertel 11861: sub devalidateuserresdata {
11862: my ($uname,$udom)=@_;
11863: my $hashid="$udom:$uname";
11864: &devalidate_cache_new('userres',$hashid);
11865: }
11866:
1.624 albertel 11867: sub get_userresdata {
11868: my ($uname,$udom)=@_;
11869: #most student don\'t have any data set, check if there is some data
11870: if (&EXT_cache_status($udom,$uname)) { return undef; }
11871:
11872: my $hashid="$udom:$uname";
11873: my ($result,$cached)=&is_cached_new('userres',$hashid);
11874: if (!defined($cached)) {
11875: my %resourcedata=&dump('resourcedata',$udom,$uname);
11876: $result=\%resourcedata;
11877: &do_cache_new('userres',$hashid,$result,600);
11878: }
11879: my ($tmp)=keys(%$result);
11880: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11881: return $result;
11882: }
11883: #error 2 occurs when the .db doesn't exist
11884: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11885: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11886: &logthis("<font color=\"blue\">WARNING:".
11887: " Trying to get resource data for ".
11888: $uname." at ".$udom.": ".
11889: $tmp."</font>");
11890: }
1.624 albertel 11891: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11892: #&EXT_cache_set($udom,$uname);
11893: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11894: undef($tmp); # not really an error so don't send it back
1.624 albertel 11895: }
11896: return $tmp;
11897: }
1.879 foxr 11898: #----------------------------------------------- resdata - return resource data
11899: # Purpose:
11900: # Return resource data for either users or for a course.
11901: # Parameters:
11902: # $name - Course/user name.
11903: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11904: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11905: # $mapp - decluttered URL of enclosing map
11906: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11907: # $recurseup - Ref to array of map URLs, starting with map containing
11908: # $mapp up through hierarchy of nested maps to top level map.
11909: # $courseid - CourseID (first part of param identifier).
11910: # $modifier - Middle part of param identifier.
11911: # $what - Last part of param identifier.
1.879 foxr 11912: # @which - Array of names of resources desired.
11913: # Returns:
11914: # The value of the first reasource in @which that is found in the
11915: # resource hash.
11916: # Exceptional Conditions:
11917: # If the $type passed in is not valid (not the string 'course' or
11918: # 'user', an undefined reference is returned.
11919: # If none of the resources are found, an undef is returned
1.624 albertel 11920: sub resdata {
1.1301 raeburn 11921: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11922: $modifier,$what,@which)=@_;
1.624 albertel 11923: my $result;
11924: if ($type eq 'course') {
11925: $result=&get_courseresdata($name,$domain);
11926: } elsif ($type eq 'user') {
11927: $result=&get_userresdata($name,$domain);
11928: }
11929: if (!ref($result)) { return $result; }
1.251 albertel 11930: foreach my $item (@which) {
1.1301 raeburn 11931: if ($item->[1] eq 'course') {
11932: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11933: unless ($$recursed) {
1.1302 raeburn 11934: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11935: $$recursed = 1;
11936: }
11937: foreach my $item (@${recurseup}) {
11938: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11939: last if (defined($result->{$norecursechk}));
11940: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11941: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11942: }
11943: }
11944: }
11945: if (defined($result->{$item->[0]})) {
1.927 albertel 11946: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11947: }
1.250 albertel 11948: }
1.291 albertel 11949: return undef;
1.200 www 11950: }
11951:
1.1360 raeburn 11952: sub get_domain_lti {
11953: my ($cdom,$context) = @_;
11954: my ($name,%lti);
11955: if ($context eq 'consumer') {
11956: $name = 'ltitools';
11957: } elsif ($context eq 'provider') {
11958: $name = 'lti';
11959: } else {
11960: return %lti;
11961: }
11962: my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298 raeburn 11963: if (defined($cached)) {
11964: if (ref($result) eq 'HASH') {
1.1360 raeburn 11965: %lti = %{$result};
1.1298 raeburn 11966: }
11967: } else {
1.1360 raeburn 11968: my %domconfig = &get_dom('configuration',[$name],$cdom);
11969: if (ref($domconfig{$name}) eq 'HASH') {
11970: %lti = %{$domconfig{$name}};
11971: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11972: if (ref($encdomconfig{$name}) eq 'HASH') {
11973: foreach my $id (keys(%lti)) {
11974: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344 raeburn 11975: foreach my $item ('key','secret') {
1.1360 raeburn 11976: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344 raeburn 11977: }
11978: }
11979: }
11980: }
1.1298 raeburn 11981: }
11982: my $cachetime = 24*60*60;
1.1360 raeburn 11983: &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298 raeburn 11984: }
1.1360 raeburn 11985: return %lti;
1.1298 raeburn 11986: }
11987:
1.1236 raeburn 11988: sub get_numsuppfiles {
11989: my ($cnum,$cdom,$ignorecache)=@_;
11990: my $hashid=$cnum.':'.$cdom;
11991: my ($suppcount,$cached);
11992: unless ($ignorecache) {
11993: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11994: }
11995: unless (defined($cached)) {
11996: my $chome=&homeserver($cnum,$cdom);
11997: unless ($chome eq 'no_host') {
1.1366 raeburn 11998: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 11999: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 12000: ($suppcount,$supptools,$errors) =
12001: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12002: $supptools,$errors);
1.1236 raeburn 12003: }
12004: &do_cache_new('suppcount',$hashid,$suppcount,600);
12005: }
12006: return $suppcount;
12007: }
12008:
1.379 matthew 12009: #
12010: # EXT resource caching routines
12011: #
12012:
1.1302 raeburn 12013: {
12014: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12015: #
12016: # The course for which we cache
12017: my $cachedmapkey='';
12018: # The cached recursive maps for this course
12019: my %cachedmaps=();
12020: # When this was last done
12021: my $cachedmaptime='';
12022:
1.379 matthew 12023: sub clear_EXT_cache_status {
1.383 albertel 12024: &delenv('cache.EXT.');
1.379 matthew 12025: }
12026:
12027: sub EXT_cache_status {
12028: my ($target_domain,$target_user) = @_;
1.383 albertel 12029: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12030: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12031: # We know already the user has no data
12032: return 1;
12033: } else {
12034: return 0;
12035: }
12036: }
12037:
12038: sub EXT_cache_set {
12039: my ($target_domain,$target_user) = @_;
1.383 albertel 12040: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12041: #&appenv({$cachename => time});
1.379 matthew 12042: }
12043:
1.28 www 12044: # --------------------------------------------------------- Value of a Variable
1.58 www 12045: sub EXT {
1.715 albertel 12046:
1.1228 raeburn 12047: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 12048: unless ($varname) { return ''; }
1.218 albertel 12049: #get real user name/domain, courseid and symb
12050: my $courseid;
1.359 albertel 12051: my $publicuser;
1.427 www 12052: if ($symbparm) {
12053: $symbparm=&get_symb_from_alias($symbparm);
12054: }
1.218 albertel 12055: if (!($uname && $udom)) {
1.790 albertel 12056: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12057: if (!$symbparm) { $symbparm=$cursymb; }
12058: } else {
1.620 albertel 12059: $courseid=$env{'request.course.id'};
1.218 albertel 12060: }
1.48 www 12061: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12062: my $rest;
1.320 albertel 12063: if (defined($therest[0])) {
1.48 www 12064: $rest=join('.',@therest);
12065: } else {
12066: $rest='';
12067: }
1.320 albertel 12068:
1.57 www 12069: my $qualifierrest=$qualifier;
12070: if ($rest) { $qualifierrest.='.'.$rest; }
12071: my $spacequalifierrest=$space;
12072: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12073: if ($realm eq 'user') {
1.48 www 12074: # --------------------------------------------------------------- user.resource
12075: if ($space eq 'resource') {
1.651 albertel 12076: if ( (defined($Apache::lonhomework::parsing_a_problem)
12077: || defined($Apache::lonhomework::parsing_a_task))
12078: &&
1.744 albertel 12079: ($symbparm eq &symbread()) ) {
12080: # if we are in the middle of processing the resource the
12081: # get the value we are planning on committing
12082: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12083: return $Apache::lonhomework::results{$qualifierrest};
12084: } else {
12085: return $Apache::lonhomework::history{$qualifierrest};
12086: }
1.335 albertel 12087: } else {
1.359 albertel 12088: my %restored;
1.620 albertel 12089: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12090: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12091: } else {
12092: %restored=&restore($symbparm,$courseid,$udom,$uname);
12093: }
1.335 albertel 12094: return $restored{$qualifierrest};
12095: }
1.48 www 12096: # ----------------------------------------------------------------- user.access
12097: } elsif ($space eq 'access') {
1.218 albertel 12098: # FIXME - not supporting calls for a specific user
1.48 www 12099: return &allowed($qualifier,$rest);
12100: # ------------------------------------------ user.preferences, user.environment
12101: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12102: if (($uname eq $env{'user.name'}) &&
12103: ($udom eq $env{'user.domain'})) {
12104: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12105: } else {
1.359 albertel 12106: my %returnhash;
12107: if (!$publicuser) {
12108: %returnhash=&userenvironment($udom,$uname,
12109: $qualifierrest);
12110: }
1.218 albertel 12111: return $returnhash{$qualifierrest};
12112: }
1.48 www 12113: # ----------------------------------------------------------------- user.course
12114: } elsif ($space eq 'course') {
1.218 albertel 12115: # FIXME - not supporting calls for a specific user
1.620 albertel 12116: return $env{join('.',('request.course',$qualifier))};
1.48 www 12117: # ------------------------------------------------------------------- user.role
12118: } elsif ($space eq 'role') {
1.218 albertel 12119: # FIXME - not supporting calls for a specific user
1.620 albertel 12120: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12121: if ($qualifier eq 'value') {
12122: return $role;
12123: } elsif ($qualifier eq 'extent') {
12124: return $where;
12125: }
12126: # ----------------------------------------------------------------- user.domain
12127: } elsif ($space eq 'domain') {
1.218 albertel 12128: return $udom;
1.48 www 12129: # ------------------------------------------------------------------- user.name
12130: } elsif ($space eq 'name') {
1.218 albertel 12131: return $uname;
1.48 www 12132: # ---------------------------------------------------- Any other user namespace
1.29 www 12133: } else {
1.359 albertel 12134: my %reply;
12135: if (!$publicuser) {
12136: %reply=&get($space,[$qualifierrest],$udom,$uname);
12137: }
12138: return $reply{$qualifierrest};
1.48 www 12139: }
1.236 www 12140: } elsif ($realm eq 'query') {
12141: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12142: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12143: [$spacequalifierrest]);
1.620 albertel 12144: return $env{'form.'.$spacequalifierrest};
1.236 www 12145: } elsif ($realm eq 'request') {
1.48 www 12146: # ------------------------------------------------------------- request.browser
12147: if ($space eq 'browser') {
1.1145 bisitz 12148: return $env{'browser.'.$qualifier};
1.57 www 12149: # ------------------------------------------------------------ request.filename
12150: } else {
1.620 albertel 12151: return $env{'request.'.$spacequalifierrest};
1.29 www 12152: }
1.28 www 12153: } elsif ($realm eq 'course') {
1.48 www 12154: # ---------------------------------------------------------- course.description
1.620 albertel 12155: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12156: } elsif ($realm eq 'resource') {
1.165 www 12157:
1.620 albertel 12158: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12159: if (!$symbparm) { $symbparm=&symbread(); }
12160: }
1.693 albertel 12161:
1.1232 raeburn 12162: if ($qualifier eq '') {
12163: if ($space eq 'title') {
12164: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12165: return &gettitle($symbparm);
12166: }
1.693 albertel 12167:
1.1232 raeburn 12168: if ($space eq 'map') {
12169: my ($map) = &decode_symb($symbparm);
12170: return &symbread($map);
12171: }
12172: if ($space eq 'maptitle') {
12173: my ($map) = &decode_symb($symbparm);
12174: return &gettitle($map);
12175: }
12176: if ($space eq 'filename') {
12177: if ($symbparm) {
12178: return &clutter((&decode_symb($symbparm))[2]);
12179: }
12180: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12181: }
1.1232 raeburn 12182:
1.1233 raeburn 12183: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12184: if ($space eq 'visibleparts') {
12185: my $navmap = Apache::lonnavmaps::navmap->new();
12186: my $item;
12187: if (ref($navmap)) {
12188: my $res = $navmap->getBySymb($symbparm);
12189: my $parts = $res->parts();
12190: if (ref($parts) eq 'ARRAY') {
12191: $item = join(',',@{$parts});
12192: }
12193: undef($navmap);
1.1232 raeburn 12194: }
1.1233 raeburn 12195: return $item;
1.1232 raeburn 12196: }
12197: }
12198: }
1.693 albertel 12199:
1.1301 raeburn 12200: my ($section, $group, @groups, @recurseup, $recursed);
12201: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12202: if (($courseid eq '') && ($cid)) {
12203: $courseid = $cid;
12204: }
12205: if (($symbparm && $courseid) &&
12206: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12207:
1.218 albertel 12208: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12209:
1.60 www 12210: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12211: my $symbp=$symbparm;
1.1301 raeburn 12212: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12213: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12214: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12215: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12216: if (($env{'user.name'} eq $uname) &&
12217: ($env{'user.domain'} eq $udom)) {
12218: $section=$env{'request.course.sec'};
1.733 raeburn 12219: @groups = split(/:/,$env{'request.course.groups'});
12220: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12221: } else {
1.539 albertel 12222: if (! defined($usection)) {
1.551 albertel 12223: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12224: } else {
12225: $section = $usection;
12226: }
1.733 raeburn 12227: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12228: }
12229:
12230: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12231: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12232: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12233: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12234:
1.593 albertel 12235: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12236: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12237: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12238: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12239:
1.60 www 12240: # ----------------------------------------------------------- first, check user
1.624 albertel 12241:
1.1301 raeburn 12242: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12243: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12244: ([$courselevelr,'resource'],
12245: [$courselevelm,'map' ],
1.1301 raeburn 12246: [$courseleveli,'map' ],
1.927 albertel 12247: [$courselevel, 'course' ]));
1.931 albertel 12248: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12249:
1.594 albertel 12250: # ------------------------------------------------ second, check some of course
1.684 raeburn 12251: my $coursereply;
1.691 raeburn 12252: if (@groups > 0) {
12253: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12254: $recurseparm,$mapparm,$spacequalifierrest,
12255: $mapp,\$recursed,\@recurseup);
12256: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12257: }
1.96 www 12258:
1.684 raeburn 12259: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12260: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12261: 'course',$mapp,\$recursed,\@recurseup,
12262: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12263: ([$seclevelr, 'resource'],
12264: [$seclevelm, 'map' ],
1.1301 raeburn 12265: [$secleveli, 'map' ],
1.927 albertel 12266: [$seclevel, 'course' ],
12267: [$courselevelr,'resource']));
12268: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12269:
1.60 www 12270: # ------------------------------------------------------ third, check map parms
1.218 albertel 12271: my %parmhash=();
12272: my $thisparm='';
12273: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12274: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12275: &GDBM_READER(),0640)) {
1.218 albertel 12276: $thisparm=$parmhash{$symbparm};
12277: untie(%parmhash);
12278: }
1.927 albertel 12279: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12280: }
1.594 albertel 12281: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12282:
12283: my $what = $spacequalifierrest;
12284: $what=~s/\./\_/;
1.282 albertel 12285: my $filename;
12286: if (!$symbparm) { $symbparm=&symbread(); }
12287: if ($symbparm) {
1.409 www 12288: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12289: } else {
1.620 albertel 12290: $filename=$env{'request.filename'};
1.282 albertel 12291: }
1.1362 raeburn 12292: my $toolsymb;
12293: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12294: $toolsymb = $symbparm;
12295: }
12296: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12297: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12298: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12299: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12300:
1.1301 raeburn 12301: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12302: if ($symbparm && defined($courseid) &&
1.620 albertel 12303: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12304: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12305: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12306: 'course',$mapp,\$recursed,\@recurseup,
12307: $courseid,'.',$spacequalifierrest,
1.927 albertel 12308: ([$courselevelm,'map' ],
1.1301 raeburn 12309: [$courseleveli,'map' ],
1.927 albertel 12310: [$courselevel, 'course']));
12311: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12312: }
1.145 www 12313: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12314: unless ($space eq '0') {
1.336 albertel 12315: my @parts=split(/_/,$space);
12316: my $id=pop(@parts);
12317: my $part=join('_',@parts);
12318: if ($part eq '') { $part='0'; }
1.927 albertel 12319: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12320: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12321: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12322: }
1.395 albertel 12323: if ($recurse) { return undef; }
1.1362 raeburn 12324: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12325: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12326: # ---------------------------------------------------- Any other user namespace
12327: } elsif ($realm eq 'environment') {
12328: # ----------------------------------------------------------------- environment
1.620 albertel 12329: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12330: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12331: } else {
1.770 albertel 12332: if ($uname eq 'anonymous' && $udom eq '') {
12333: return '';
12334: }
1.219 albertel 12335: my %returnhash=&userenvironment($udom,$uname,
12336: $spacequalifierrest);
12337: return $returnhash{$spacequalifierrest};
12338: }
1.28 www 12339: } elsif ($realm eq 'system') {
1.48 www 12340: # ----------------------------------------------------------------- system.time
12341: if ($space eq 'time') {
12342: return time;
12343: }
1.696 albertel 12344: } elsif ($realm eq 'server') {
12345: # ----------------------------------------------------------------- system.time
12346: if ($space eq 'name') {
12347: return $ENV{'SERVER_NAME'};
12348: }
1.1415 raeburn 12349: } elsif ($realm eq 'client') {
12350: if ($space eq 'remote_addr') {
12351: return $ENV{'REMOTE_ADDR'};
12352: }
1.28 www 12353: }
1.48 www 12354: return '';
1.61 www 12355: }
12356:
1.927 albertel 12357: sub get_reply {
12358: my ($reply_value) = @_;
1.940 raeburn 12359: if (ref($reply_value) eq 'ARRAY') {
12360: if (wantarray) {
12361: return @$reply_value;
12362: }
12363: return $reply_value->[0];
12364: } else {
12365: return $reply_value;
1.927 albertel 12366: }
12367: }
12368:
1.691 raeburn 12369: sub check_group_parms {
1.1301 raeburn 12370: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12371: $recursed,$recurseupref) = @_;
12372: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12373: [$what,'course']);
12374: my $coursereply;
1.691 raeburn 12375: foreach my $group (@{$groups}) {
1.1301 raeburn 12376: my @groupitems = ();
1.691 raeburn 12377: foreach my $level (@levels) {
1.927 albertel 12378: my $item = $courseid.'.['.$group.'].'.$level->[0];
12379: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12380: }
1.1301 raeburn 12381: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12382: $env{'course.'.$courseid.'.domain'},
12383: 'course',$mapp,$recursed,$recurseupref,
12384: $courseid,'.['.$group.'].',$what,
12385: @groupitems);
12386: last if (defined($coursereply));
1.691 raeburn 12387: }
12388: return $coursereply;
12389: }
12390:
1.1301 raeburn 12391: sub get_map_hierarchy {
1.1302 raeburn 12392: my ($mapname,$courseid) = @_;
12393: my @recurseup = ();
1.1301 raeburn 12394: if ($mapname) {
1.1302 raeburn 12395: if (($cachedmapkey eq $courseid) &&
12396: (abs($cachedmaptime-time)<5)) {
12397: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12398: return @{$cachedmaps{$mapname}};
12399: }
12400: }
1.1301 raeburn 12401: my $navmap = Apache::lonnavmaps::navmap->new();
12402: if (ref($navmap)) {
12403: @recurseup = $navmap->recurseup_maps($mapname);
12404: undef($navmap);
1.1302 raeburn 12405: $cachedmaps{$mapname} = \@recurseup;
12406: $cachedmaptime=time;
12407: $cachedmapkey=$courseid;
1.1301 raeburn 12408: }
12409: }
12410: return @recurseup;
12411: }
12412:
1.1302 raeburn 12413: }
12414:
1.691 raeburn 12415: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12416: my ($courseid,@groups) = @_;
12417: @groups = sort(@groups);
1.691 raeburn 12418: return @groups;
12419: }
12420:
1.395 albertel 12421: sub packages_tab_default {
1.1362 raeburn 12422: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12423: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12424:
12425: my (@extension,@specifics,$do_default);
1.1362 raeburn 12426: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12427: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12428: if ($pack_type eq 'default') {
12429: $do_default=1;
12430: } elsif ($pack_type eq 'extension') {
12431: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12432: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12433: # only look at packages defaults for packages that this id is
1.738 albertel 12434: push(@specifics,[$package,$pack_type,$pack_part]);
12435: }
12436: }
12437: # first look for a package that matches the requested part id
12438: foreach my $package (@specifics) {
12439: my (undef,$pack_type,$pack_part)=@{$package};
12440: next if ($pack_part ne $part);
12441: if (defined($packagetab{"$pack_type&$name&default"})) {
12442: return $packagetab{"$pack_type&$name&default"};
12443: }
12444: }
12445: # look for any possible matching non extension_ package
12446: foreach my $package (@specifics) {
12447: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12448: if (defined($packagetab{"$pack_type&$name&default"})) {
12449: return $packagetab{"$pack_type&$name&default"};
12450: }
1.585 albertel 12451: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12452: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12453: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12454: }
12455: }
1.738 albertel 12456: # look for any posible extension_ match
12457: foreach my $package (@extension) {
12458: my ($package,$pack_type)=@{$package};
12459: if (defined($packagetab{"$pack_type&$name&default"})) {
12460: return $packagetab{"$pack_type&$name&default"};
12461: }
12462: if (defined($packagetab{$package."&$name&default"})) {
12463: return $packagetab{$package."&$name&default"};
12464: }
12465: }
12466: # look for a global default setting
12467: if ($do_default && defined($packagetab{"default&$name&default"})) {
12468: return $packagetab{"default&$name&default"};
12469: }
1.395 albertel 12470: return undef;
12471: }
12472:
1.334 albertel 12473: sub add_prefix_and_part {
12474: my ($prefix,$part)=@_;
12475: my $keyroot;
12476: if (defined($prefix) && $prefix !~ /^__/) {
12477: # prefix that has a part already
12478: $keyroot=$prefix;
12479: } elsif (defined($prefix)) {
12480: # prefix that is missing a part
12481: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12482: } else {
12483: # no prefix at all
12484: if (defined($part)) { $keyroot='_'.$part; }
12485: }
12486: return $keyroot;
12487: }
12488:
1.71 www 12489: # ---------------------------------------------------------------- Get metadata
12490:
1.599 albertel 12491: my %metaentry;
1.1070 www 12492: my %importedpartids;
1.1369 raeburn 12493: my %importedrespids;
1.71 www 12494: sub metadata {
1.1362 raeburn 12495: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12496: $uri=&declutter($uri);
1.288 albertel 12497: # if it is a non metadata possible uri return quickly
1.529 albertel 12498: if (($uri eq '') ||
12499: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12500: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12501: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12502: return undef;
12503: }
1.1261 raeburn 12504: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12505: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12506: return undef;
1.288 albertel 12507: }
1.73 www 12508: my $filename=$uri;
12509: $uri=~s/\.meta$//;
1.172 www 12510: #
12511: # Is the metadata already cached?
1.177 www 12512: # Look at timestamp of caching
1.172 www 12513: # Everything is cached by the main uri, libraries are never directly cached
12514: #
1.428 albertel 12515: if (!defined($liburi)) {
1.599 albertel 12516: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12517: if (defined($cached)) { return $result->{':'.$what}; }
12518: }
1.1362 raeburn 12519:
12520: #
12521: # If the uri is for an external tool the file from
12522: # which metadata should be retrieved depends on whether
12523: # the tool had been configured to be gradable (set in the Course
12524: # Editor or Resource Editor).
12525: #
12526: # If a valid symb has been included as the third arg in the call
12527: # to &metadata() that can be used to retrieve the value of
12528: # parameter_0_gradable set for the resource, and included in the
12529: # uploaded map containing the tool. The value is retrieved via
12530: # &EXT(), if a valid symb is available. Otherwise the value of
12531: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12532: # is retrieved via &get().
12533: #
12534: # When lonuserstate::traceroute() calls lonnet::EXT() for
12535: # hiddenresource and encrypturl (during course initialization)
12536: # the map-level parameter for resource.0.gradable included in the
12537: # uploaded map containing the tool will not yet have been stored
12538: # in the user_course_parms.db file for the user's session, so in
12539: # this case fall back to retrieving gradable status from the
12540: # exttool_$marker.db file.
1.1362 raeburn 12541: #
12542: # In order to avoid an infinite loop, &metadata() will return
12543: # before a call to &EXT(), if the uri is for an external tool
12544: # and the $what for which metadata is being requested is
12545: # parameter_0_gradable or 0_gradable.
12546: #
12547:
12548: if ($uri =~ /ext\.tool$/) {
12549: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12550: return;
12551: } else {
12552: my ($checked,$use_passback);
12553: if ($toolsymb ne '') {
12554: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12555: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12556: $checked = 1;
12557: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12558: $use_passback = 1;
12559: }
12560: }
12561: }
12562: unless ($checked) {
12563: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12564: $marker=~s/\D//g;
1.1363 raeburn 12565: if ($marker) {
1.1362 raeburn 12566: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12567: $use_passback = $toolsettings{'gradable'};
12568: }
12569: }
12570: if ($use_passback) {
12571: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12572: } else {
12573: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12574: }
12575: }
12576: }
12577:
1.428 albertel 12578: {
1.1069 www 12579: # Imported parts would go here
1.1369 raeburn 12580: my @origfiletagids=();
1.1069 www 12581: my $importedparts=0;
1.1369 raeburn 12582:
12583: # Imported responseids would go here
12584: my $importedresponses=0;
1.172 www 12585: #
12586: # Is this a recursive call for a library?
12587: #
1.599 albertel 12588: # if (! exists($metacache{$uri})) {
12589: # $metacache{$uri}={};
12590: # }
1.924 albertel 12591: my $cachetime = 60*60;
1.171 www 12592: if ($liburi) {
12593: $liburi=&declutter($liburi);
12594: $filename=$liburi;
1.401 bowersj2 12595: } else {
1.599 albertel 12596: &devalidate_cache_new('meta',$uri);
12597: undef(%metaentry);
1.401 bowersj2 12598: }
1.140 www 12599: my %metathesekeys=();
1.73 www 12600: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12601: my $metastring;
1.1140 www 12602: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12603: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12604: $metastring =
1.929 albertel 12605: &Apache::lonnet::ssi_body($which,
1.924 albertel 12606: ('grade_target' => 'meta'));
12607: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12608: } elsif (($uri !~ m -^(editupload)/-) &&
12609: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12610: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12611: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12612: $metastring=&getfile($file);
1.489 albertel 12613: }
1.208 albertel 12614: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12615: my $token;
1.140 www 12616: undef %metathesekeys;
1.71 www 12617: while ($token=$parser->get_token) {
1.339 albertel 12618: if ($token->[0] eq 'S') {
12619: if (defined($token->[2]->{'package'})) {
1.172 www 12620: #
12621: # This is a package - get package info
12622: #
1.339 albertel 12623: my $package=$token->[2]->{'package'};
12624: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12625: if (defined($token->[2]->{'id'})) {
12626: $keyroot.='_'.$token->[2]->{'id'};
12627: }
1.599 albertel 12628: if ($metaentry{':packages'}) {
12629: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12630: } else {
1.599 albertel 12631: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12632: }
1.736 albertel 12633: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12634: my $part=$keyroot;
12635: $part=~s/^\_//;
1.736 albertel 12636: if ($pack_entry=~/^\Q$package\E\&/ ||
12637: $pack_entry=~/^\Q$package\E_0\&/) {
12638: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12639: # ignore package.tab specified default values
12640: # here &package_tab_default() will fetch those
12641: if ($subp eq 'default') { next; }
1.736 albertel 12642: my $value=$packagetab{$pack_entry};
1.432 albertel 12643: my $unikey;
12644: if ($pack =~ /_0$/) {
12645: $unikey='parameter_0_'.$name;
12646: $part=0;
12647: } else {
12648: $unikey='parameter'.$keyroot.'_'.$name;
12649: }
1.339 albertel 12650: if ($subp eq 'display') {
12651: $value.=' [Part: '.$part.']';
12652: }
1.599 albertel 12653: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12654: $metathesekeys{$unikey}=1;
1.599 albertel 12655: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12656: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12657: }
1.599 albertel 12658: if (defined($metaentry{':'.$unikey.'.default'})) {
12659: $metaentry{':'.$unikey}=
12660: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12661: }
1.339 albertel 12662: }
12663: }
12664: } else {
1.172 www 12665: #
12666: # This is not a package - some other kind of start tag
1.339 albertel 12667: #
12668: my $entry=$token->[1];
1.1068 www 12669: my $unikey='';
1.175 www 12670:
1.339 albertel 12671: if ($entry eq 'import') {
1.175 www 12672: #
12673: # Importing a library here
1.339 albertel 12674: #
1.1067 www 12675: my $location=$parser->get_text('/import');
12676: my $dir=$filename;
12677: $dir=~s|[^/]*$||;
12678: $location=&filelocation($dir,$location);
1.1369 raeburn 12679:
12680: my $importid=$token->[2]->{'id'};
1.1068 www 12681: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 12682: #
12683: # Check metadata for imported file to
12684: # see if it contained response items
12685: #
1.1372 raeburn 12686: my ($origfile,@libfilekeys);
1.1370 raeburn 12687: my %currmetaentry = %metaentry;
1.1372 raeburn 12688: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12689: $depthcount+1));
12690: if (grep(/^responseorder$/,@libfilekeys)) {
12691: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12692: undef,$depthcount+1);
12693: if ($libresponseorder ne '') {
12694: if ($#origfiletagids<0) {
12695: undef(%importedrespids);
12696: undef(%importedpartids);
12697: }
1.1373 raeburn 12698: my @respids = split(/\s*,\s*/,$libresponseorder);
12699: if (@respids) {
12700: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12701: }
12702: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 12703: $importedresponses = 1;
1.1369 raeburn 12704: # We need to get the original file and the imported file to get the response order correct
12705: # Load and inspect original file
1.1372 raeburn 12706: if ($#origfiletagids<0) {
12707: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12708: $origfile=&getfile($origfilelocation);
12709: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12710: }
1.1369 raeburn 12711: }
12712: }
12713: }
1.1370 raeburn 12714: # Do not overwrite contents of %metaentry hash for resource itself with
12715: # hash populated for imported library file
12716: %metaentry = %currmetaentry;
12717: undef(%currmetaentry);
1.1374 raeburn 12718: if ($importmode eq 'part') {
1.1068 www 12719: # Import as part(s)
1.1069 www 12720: $importedparts=1;
12721: # We need to get the original file and the imported file to get the part order correct
12722: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 12723: # Load and inspect original file if we didn't do that already
12724: if ($#origfiletagids<0) {
12725: undef(%importedrespids);
12726: undef(%importedpartids);
12727: if ($origfile eq '') {
12728: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12729: $origfile=&getfile($origfilelocation);
12730: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12731: }
1.1070 www 12732: }
1.1372 raeburn 12733: my @impfilepartids;
12734: # If <partorder> tag is included in metadata for the imported file
12735: # get the parts in the imported file from that.
12736: if (grep(/^partorder$/,@libfilekeys)) {
12737: %currmetaentry = %metaentry;
12738: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12739: $depthcount+1);
12740: %metaentry = %currmetaentry;
12741: undef(%currmetaentry);
12742: if ($libpartorder ne '') {
12743: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12744: }
12745: } else {
12746: # If no <partorder> tag available, load and inspect imported file
12747: my $impfile=&getfile($location);
12748: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12749: }
1.1069 www 12750: if ($#impfilepartids>=0) {
12751: # This problem had parts
1.1070 www 12752: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12753: } else {
12754: # Importing by turning a single problem into a problem part
12755: # It gets the import-tags ID as part-ID
12756: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12757: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12758: }
1.1068 www 12759: } else {
1.1374 raeburn 12760: # Import as problem or as normal import
12761: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12762: unless ($importmode eq 'problem') {
1.1068 www 12763: # Normal import
1.1374 raeburn 12764: if (defined($token->[2]->{'id'})) {
12765: $unikey.='_'.$token->[2]->{'id'};
12766: }
12767: }
12768: # Check metadata for imported file to
12769: # see if it contained parts
12770: if (grep(/^partorder$/,@libfilekeys)) {
12771: %currmetaentry = %metaentry;
12772: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12773: $depthcount+1);
12774: %metaentry = %currmetaentry;
12775: undef(%currmetaentry);
12776: if ($libpartorder ne '') {
12777: $importedparts = 1;
12778: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12779: }
12780: }
1.1067 www 12781: }
1.339 albertel 12782: if ($depthcount<20) {
1.736 albertel 12783: my $metadata =
1.1362 raeburn 12784: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 12785: $depthcount+1);
12786: foreach my $meta (split(',',$metadata)) {
12787: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12788: $metathesekeys{$meta}=1;
1.339 albertel 12789: }
1.1068 www 12790: }
1.1067 www 12791: } else {
12792: #
12793: # Not importing, some other kind of non-package, non-library start tag
12794: #
12795: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12796: if (defined($token->[2]->{'id'})) {
12797: $unikey.='_'.$token->[2]->{'id'};
12798: }
1.339 albertel 12799: if (defined($token->[2]->{'name'})) {
12800: $unikey.='_'.$token->[2]->{'name'};
12801: }
12802: $metathesekeys{$unikey}=1;
1.736 albertel 12803: foreach my $param (@{$token->[3]}) {
12804: $metaentry{':'.$unikey.'.'.$param} =
12805: $token->[2]->{$param};
1.339 albertel 12806: }
12807: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12808: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12809: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12810: # only ws inside the tag, and not in default, so use default
12811: # as value
1.599 albertel 12812: $metaentry{':'.$unikey}=$default;
1.908 albertel 12813: } elsif ( $internaltext =~ /\S/ ) {
12814: # something interesting inside the tag
12815: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12816: } else {
1.908 albertel 12817: # no interesting values, don't set a default
1.339 albertel 12818: }
1.172 www 12819: # end of not-a-package not-a-library import
1.339 albertel 12820: }
1.172 www 12821: # end of not-a-package start tag
1.339 albertel 12822: }
1.172 www 12823: # the next is the end of "start tag"
1.339 albertel 12824: }
12825: }
1.483 albertel 12826: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12827: $extension = lc($extension);
12828: if ($extension eq 'htm') { $extension='html'; }
12829:
1.737 albertel 12830: foreach my $key (keys(%packagetab)) {
1.483 albertel 12831: #no specific packages #how's our extension
12832: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12833: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12834: \%metathesekeys);
12835: }
1.883 albertel 12836:
12837: if (!exists($metaentry{':packages'})
12838: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12839: foreach my $key (keys(%packagetab)) {
1.483 albertel 12840: #no specific packages well let's get default then
12841: if ($key!~/^default&/) { next; }
1.488 albertel 12842: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12843: \%metathesekeys);
12844: }
12845: }
1.338 www 12846: # are there custom rights to evaluate
1.599 albertel 12847: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12848:
1.338 www 12849: #
12850: # Importing a rights file here
1.339 albertel 12851: #
12852: unless ($depthcount) {
1.599 albertel 12853: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12854: my $dir=$filename;
12855: $dir=~s|[^/]*$||;
12856: $location=&filelocation($dir,$location);
1.736 albertel 12857: my $rights_metadata =
1.1362 raeburn 12858: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 12859: $depthcount+1);
12860: foreach my $rights (split(',',$rights_metadata)) {
12861: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12862: $metathesekeys{$rights}=1;
1.339 albertel 12863: }
12864: }
12865: }
1.737 albertel 12866: # uniqifiy package listing
12867: my %seen;
12868: my @uniq_packages =
12869: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12870: $metaentry{':packages'} = join(',',@uniq_packages);
12871:
1.1369 raeburn 12872: if (($importedresponses) || ($importedparts)) {
12873: if ($importedparts) {
1.1070 www 12874: # We had imported parts and need to rebuild partorder
1.1369 raeburn 12875: $metaentry{':partorder'}='';
12876: $metathesekeys{'partorder'}=1;
12877: }
12878: if ($importedresponses) {
12879: # We had imported responses and need to rebuil responseorder
12880: $metaentry{':responseorder'}='';
12881: $metathesekeys{'responseorder'}=1;
12882: }
12883: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12884: my $origid = $origfiletagids[$index+1];
12885: if ($origfiletagids[$index] eq 'part') {
12886: # Original part, part of the problem
12887: if ($importedparts) {
12888: $metaentry{':partorder'}.=','.$origid;
12889: }
12890: } elsif ($origfiletagids[$index] eq 'import') {
12891: if ($importedparts) {
12892: # We have imported parts at this position
1.1373 raeburn 12893: if ($importedpartids{$origid} ne '') {
12894: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12895: }
1.1369 raeburn 12896: }
12897: if ($importedresponses) {
12898: # We have imported responses at this position
1.1373 raeburn 12899: if ($importedrespids{$origid} ne '') {
12900: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 12901: }
12902: }
12903: } else {
12904: # Original response item, part of the problem
12905: if ($importedresponses) {
12906: $metaentry{':responseorder'}.=','.$origid;
12907: }
12908: }
12909: }
12910: if ($importedparts) {
12911: $metaentry{':partorder'}=~s/^\,//;
12912: }
12913: if ($importedresponses) {
12914: $metaentry{':responseorder'}=~s/^\,//;
12915: }
1.1070 www 12916: }
1.737 albertel 12917: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12918: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 12919: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 12920: unless ($liburi) {
12921: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12922: }
1.177 www 12923: # this is the end of "was not already recently cached
1.71 www 12924: }
1.599 albertel 12925: return $metaentry{':'.$what};
1.261 albertel 12926: }
12927:
1.488 albertel 12928: sub metadata_create_package_def {
1.483 albertel 12929: my ($uri,$key,$package,$metathesekeys)=@_;
12930: my ($pack,$name,$subp)=split(/\&/,$key);
12931: if ($subp eq 'default') { next; }
12932:
1.599 albertel 12933: if (defined($metaentry{':packages'})) {
12934: $metaentry{':packages'}.=','.$package;
1.483 albertel 12935: } else {
1.599 albertel 12936: $metaentry{':packages'}=$package;
1.483 albertel 12937: }
12938: my $value=$packagetab{$key};
12939: my $unikey;
12940: $unikey='parameter_0_'.$name;
1.599 albertel 12941: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12942: $$metathesekeys{$unikey}=1;
1.599 albertel 12943: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12944: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12945: }
1.599 albertel 12946: if (defined($metaentry{':'.$unikey.'.default'})) {
12947: $metaentry{':'.$unikey}=
12948: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12949: }
12950: }
12951:
1.261 albertel 12952: sub metadata_generate_part0 {
12953: my ($metadata,$metacache,$uri) = @_;
12954: my %allnames;
1.737 albertel 12955: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12956: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12957: my $part=$$metacache{':'.$metakey.'.part'};
12958: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12959: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12960: $allnames{$name}=$part;
12961: }
12962: }
12963: }
12964: foreach my $name (keys(%allnames)) {
12965: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12966: my $key=":parameter_0_$name";
1.261 albertel 12967: $$metacache{"$key.part"}='0';
12968: $$metacache{"$key.name"}=$name;
1.428 albertel 12969: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12970: $allnames{$name}.'_'.$name.
12971: '.type'};
1.428 albertel 12972: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12973: '.display'};
1.644 www 12974: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12975: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12976: $$metacache{"$key.display"}=$olddis;
12977: }
1.71 www 12978: }
12979:
1.764 albertel 12980: # ------------------------------------------------------ Devalidate title cache
12981:
12982: sub devalidate_title_cache {
12983: my ($url)=@_;
12984: if (!$env{'request.course.id'}) { return; }
12985: my $symb=&symbread($url);
12986: if (!$symb) { return; }
12987: my $key=$env{'request.course.id'}."\0".$symb;
12988: &devalidate_cache_new('title',$key);
12989: }
12990:
1.1014 droeschl 12991: # ------------------------------------------------- Get the title of a course
12992:
12993: sub current_course_title {
12994: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12995: }
1.301 www 12996: # ------------------------------------------------- Get the title of a resource
12997:
12998: sub gettitle {
12999: my $urlsymb=shift;
13000: my $symb=&symbread($urlsymb);
1.534 albertel 13001: if ($symb) {
1.620 albertel 13002: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13003: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13004: if (defined($cached)) {
13005: return $result;
13006: }
1.534 albertel 13007: my ($map,$resid,$url)=&decode_symb($symb);
13008: my $title='';
1.907 albertel 13009: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13010: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13011: } else {
13012: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13013: &GDBM_READER(),0640)) {
13014: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13015: $title=$bighash{'title_'.$mapid.'.'.$resid};
13016: untie(%bighash);
13017: }
1.534 albertel 13018: }
13019: $title=~s/\&colon\;/\:/gs;
13020: if ($title) {
1.1159 www 13021: # Remember both $symb and $title for dynamic metadata
13022: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13023: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13024: # Cache this title and then return it
1.599 albertel 13025: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13026: }
13027: $urlsymb=$url;
13028: }
13029: my $title=&metadata($urlsymb,'title');
13030: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13031: return $title;
1.301 www 13032: }
1.613 albertel 13033:
1.614 albertel 13034: sub get_slot {
13035: my ($which,$cnum,$cdom)=@_;
13036: if (!$cnum || !$cdom) {
1.790 albertel 13037: (undef,my $courseid)=&whichuser();
1.620 albertel 13038: $cdom=$env{'course.'.$courseid.'.domain'};
13039: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13040: }
1.703 albertel 13041: my $key=join("\0",'slots',$cdom,$cnum,$which);
13042: my %slotinfo;
13043: if (exists($remembered{$key})) {
13044: $slotinfo{$which} = $remembered{$key};
13045: } else {
13046: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13047: &Apache::lonhomework::showhash(%slotinfo);
13048: my ($tmp)=keys(%slotinfo);
13049: if ($tmp=~/^error:/) { return (); }
13050: $remembered{$key} = $slotinfo{$which};
13051: }
1.616 albertel 13052: if (ref($slotinfo{$which}) eq 'HASH') {
13053: return %{$slotinfo{$which}};
13054: }
13055: return $slotinfo{$which};
1.614 albertel 13056: }
1.1150 raeburn 13057:
13058: sub get_reservable_slots {
13059: my ($cnum,$cdom,$uname,$udom) = @_;
13060: my $now = time;
13061: my $reservable_info;
13062: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13063: if (exists($remembered{$key})) {
13064: $reservable_info = $remembered{$key};
13065: } else {
13066: my %resv;
13067: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13068: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13069: $reservable_info = \%resv;
13070: $remembered{$key} = $reservable_info;
13071: }
13072: return $reservable_info;
13073: }
13074:
13075: sub get_course_slots {
13076: my ($cnum,$cdom) = @_;
13077: my $hashid=$cnum.':'.$cdom;
13078: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13079: if (defined($cached)) {
13080: if (ref($result) eq 'HASH') {
13081: return %{$result};
13082: }
13083: } else {
13084: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13085: my ($tmp) = keys(%slots);
13086: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13087: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13088: return %slots;
13089: }
13090: }
13091: return;
13092: }
13093:
13094: sub devalidate_slots_cache {
13095: my ($cnum,$cdom)=@_;
13096: my $hashid=$cnum.':'.$cdom;
13097: &devalidate_cache_new('allslots',$hashid);
13098: }
13099:
1.1181 raeburn 13100: sub get_coursechange {
13101: my ($cdom,$cnum) = @_;
13102: if ($cdom eq '' || $cnum eq '') {
13103: return unless ($env{'request.course.id'});
13104: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13105: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13106: }
13107: my $hashid=$cdom.'_'.$cnum;
13108: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13109: if ((defined($cached)) && ($change ne '')) {
13110: return $change;
13111: } else {
13112: my %crshash;
13113: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13114: if ($crshash{'internal.contentchange'} eq '') {
13115: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13116: if ($change eq '') {
13117: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13118: $change = $crshash{'internal.created'};
13119: }
13120: } else {
13121: $change = $crshash{'internal.contentchange'};
13122: }
13123: my $cachetime = 600;
13124: &do_cache_new('crschange',$hashid,$change,$cachetime);
13125: }
13126: return $change;
13127: }
13128:
13129: sub devalidate_coursechange_cache {
13130: my ($cnum,$cdom)=@_;
13131: my $hashid=$cnum.':'.$cdom;
13132: &devalidate_cache_new('crschange',$hashid);
13133: }
13134:
1.31 www 13135: # ------------------------------------------------- Update symbolic store links
13136:
13137: sub symblist {
13138: my ($mapname,%newhash)=@_;
1.438 www 13139: $mapname=&deversion(&declutter($mapname));
1.31 www 13140: my %hash;
1.620 albertel 13141: if (($env{'request.course.fn'}) && (%newhash)) {
13142: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13143: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13144: foreach my $url (keys(%newhash)) {
1.711 albertel 13145: next if ($url eq 'last_known'
13146: && $env{'form.no_update_last_known'});
13147: $hash{declutter($url)}=&encode_symb($mapname,
13148: $newhash{$url}->[1],
13149: $newhash{$url}->[0]);
1.191 harris41 13150: }
1.31 www 13151: if (untie(%hash)) {
13152: return 'ok';
13153: }
13154: }
13155: }
13156: return 'error';
1.212 www 13157: }
13158:
13159: # --------------------------------------------------------------- Verify a symb
13160:
13161: sub symbverify {
1.1190 raeburn 13162: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13163: my $thisfn=$thisurl;
1.439 www 13164: $thisfn=&declutter($thisfn);
1.215 www 13165: # direct jump to resource in page or to a sequence - will construct own symbs
13166: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13167: # check URL part
1.409 www 13168: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13169:
1.431 www 13170: unless ($url eq $thisfn) { return 0; }
1.213 www 13171:
1.216 www 13172: $symb=&symbclean($symb);
1.510 www 13173: $thisurl=&deversion($thisurl);
1.439 www 13174: $thisfn=&deversion($thisfn);
1.213 www 13175:
13176: my %bighash;
13177: my $okay=0;
1.431 www 13178:
1.620 albertel 13179: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13180: &GDBM_READER(),0640)) {
1.1032 raeburn 13181: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13182: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13183: if ($map =~ m{^uploaded/.+\.page$}) {
13184: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13185: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13186: }
13187: }
13188: my $ids;
1.1419 raeburn 13189: if ($map =~ m{^uploaded/.+\.page$}) {
13190: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13191: } else {
13192: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13193: }
1.1102 raeburn 13194: unless ($ids) {
13195: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13196: $ids=$bighash{$idkey};
1.216 www 13197: }
13198: if ($ids) {
13199: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13200: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13201: $symb =~ s/\?.+$//;
1.1202 raeburn 13202: }
1.800 albertel 13203: foreach my $id (split(/\,/,$ids)) {
13204: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13205: if (
13206: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13207: eq $symb) {
13208: if (ref($encstate)) {
13209: $$encstate = $bighash{'encrypted_'.$id};
13210: }
1.620 albertel 13211: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13212: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13213: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13214: $okay=1;
1.1202 raeburn 13215: last;
1.582 albertel 13216: }
13217: }
1.216 www 13218: }
13219: }
1.213 www 13220: untie(%bighash);
13221: }
13222: return $okay;
1.31 www 13223: }
13224:
1.210 www 13225: # --------------------------------------------------------------- Clean-up symb
13226:
13227: sub symbclean {
13228: my $symb=shift;
1.568 albertel 13229: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13230: # remove version from map
13231: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13232:
1.210 www 13233: # remove version from URL
13234: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13235:
1.507 www 13236: # remove wrapper
13237:
1.510 www 13238: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13239: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13240: return $symb;
1.409 www 13241: }
13242:
13243: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13244:
13245: sub encode_symb {
13246: my ($map,$resid,$url)=@_;
13247: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13248: }
1.409 www 13249:
13250: sub decode_symb {
1.568 albertel 13251: my $symb=shift;
13252: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13253: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13254: return (&fixversion($map),$resid,&fixversion($url));
13255: }
13256:
13257: sub fixversion {
13258: my $fn=shift;
1.609 banghart 13259: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13260: my %bighash;
13261: my $uri=&clutter($fn);
1.620 albertel 13262: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13263: # is this cached?
1.599 albertel 13264: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13265: if (defined($cached)) { return $result; }
13266: # unfortunately not cached, or expired
1.620 albertel 13267: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13268: &GDBM_READER(),0640)) {
13269: if ($bighash{'version_'.$uri}) {
13270: my $version=$bighash{'version_'.$uri};
1.444 www 13271: unless (($version eq 'mostrecent') ||
13272: ($version==&getversion($uri))) {
1.440 www 13273: $uri=~s/\.(\w+)$/\.$version\.$1/;
13274: }
13275: }
13276: untie %bighash;
1.413 www 13277: }
1.599 albertel 13278: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13279: }
13280:
13281: sub deversion {
13282: my $url=shift;
13283: $url=~s/\.\d+\.(\w+)$/\.$1/;
13284: return $url;
1.210 www 13285: }
13286:
1.31 www 13287: # ------------------------------------------------------ Return symb list entry
13288:
13289: sub symbread {
1.1282 raeburn 13290: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 13291: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 13292: if (defined($env{$cache_str})) {
13293: if ($ignorecachednull) {
13294: return $env{$cache_str} unless ($env{$cache_str} eq '');
13295: } else {
13296: return $env{$cache_str};
13297: }
13298: }
1.242 www 13299: # no filename provided? try from environment
1.1265 raeburn 13300: unless ($thisfn) {
1.620 albertel 13301: if ($env{'request.symb'}) {
13302: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13303: }
1.620 albertel 13304: $thisfn=$env{'request.filename'};
1.44 www 13305: }
1.569 albertel 13306: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13307: # is that filename actually a symb? Verify, clean, and return
13308: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13309: if (&symbverify($thisfn,$1)) {
1.620 albertel 13310: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13311: }
1.242 www 13312: }
1.44 www 13313: $thisfn=declutter($thisfn);
1.31 www 13314: my %hash;
1.37 www 13315: my %bighash;
13316: my $syval='';
1.620 albertel 13317: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13318: my $targetfn = $thisfn;
1.609 banghart 13319: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13320: $targetfn = 'adm/wrapper/'.$thisfn;
13321: }
1.687 albertel 13322: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13323: $targetfn=$1;
13324: }
1.620 albertel 13325: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13326: &GDBM_READER(),0640)) {
1.481 raeburn 13327: $syval=$hash{$targetfn};
1.37 www 13328: untie(%hash);
13329: }
13330: # ---------------------------------------------------------- There was an entry
13331: if ($syval) {
1.601 albertel 13332: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13333: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13334: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13335: #return $env{$cache_str}='';
1.601 albertel 13336: #}
13337: #$syval.=$1;
13338: #}
1.37 www 13339: } else {
13340: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13341: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13342: &GDBM_READER(),0640)) {
1.37 www 13343: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13344: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13345: unless ($ids) {
13346: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13347: }
13348: unless ($ids) {
13349: # alias?
13350: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13351: }
1.37 www 13352: if ($ids) {
13353: # ------------------------------------------------------------------- Has ID(s)
13354: my @possibilities=split(/\,/,$ids);
1.39 www 13355: if ($#possibilities==0) {
13356: # ----------------------------------------------- There is only one possibility
1.37 www 13357: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13358: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13359: $resid,$thisfn);
1.1282 raeburn 13360: if (ref($possibles) eq 'HASH') {
13361: $possibles->{$syval} = 1;
13362: }
13363: if ($checkforblock) {
13364: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13365: if (@blockers) {
13366: $syval = '';
13367: return;
13368: }
13369: }
13370: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13371: # ------------------------------------------ There is more than one possibility
13372: my $realpossible=0;
1.800 albertel 13373: foreach my $id (@possibilities) {
13374: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13375: my $canaccess;
13376: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13377: $canaccess = 1;
13378: } else {
13379: $canaccess = &allowed('bre',$file);
13380: }
13381: if ($canaccess) {
13382: my ($mapid,$resid)=split(/\./,$id);
13383: if ($bighash{'map_type_'.$mapid} ne 'page') {
13384: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13385: $resid,$thisfn);
13386: if (ref($possibles) eq 'HASH') {
13387: $possibles->{$syval} = 1;
13388: }
13389: if ($checkforblock) {
13390: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13391: unless (@blockers > 0) {
13392: $syval = $poss_syval;
13393: $realpossible++;
13394: }
13395: } else {
13396: $syval = $poss_syval;
13397: $realpossible++;
13398: }
13399: }
1.39 www 13400: }
1.191 harris41 13401: }
1.39 www 13402: if ($realpossible!=1) { $syval=''; }
1.249 www 13403: } else {
13404: $syval='';
1.37 www 13405: }
13406: }
1.1282 raeburn 13407: untie(%bighash);
1.481 raeburn 13408: }
1.31 www 13409: }
1.62 www 13410: if ($syval) {
1.620 albertel 13411: return $env{$cache_str}=$syval;
1.62 www 13412: }
1.31 www 13413: }
1.949 raeburn 13414: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13415: return $env{$cache_str}='';
1.31 www 13416: }
13417:
13418: # ---------------------------------------------------------- Return random seed
13419:
1.32 www 13420: sub numval {
13421: my $txt=shift;
13422: $txt=~tr/A-J/0-9/;
13423: $txt=~tr/a-j/0-9/;
13424: $txt=~tr/K-T/0-9/;
13425: $txt=~tr/k-t/0-9/;
13426: $txt=~tr/U-Z/0-5/;
13427: $txt=~tr/u-z/0-5/;
13428: $txt=~s/\D//g;
1.564 albertel 13429: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13430: return int($txt);
1.368 albertel 13431: }
13432:
1.484 albertel 13433: sub numval2 {
13434: my $txt=shift;
13435: $txt=~tr/A-J/0-9/;
13436: $txt=~tr/a-j/0-9/;
13437: $txt=~tr/K-T/0-9/;
13438: $txt=~tr/k-t/0-9/;
13439: $txt=~tr/U-Z/0-5/;
13440: $txt=~tr/u-z/0-5/;
13441: $txt=~s/\D//g;
13442: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13443: my $total;
13444: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13445: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13446: return int($total);
13447: }
13448:
1.575 albertel 13449: sub numval3 {
13450: use integer;
13451: my $txt=shift;
13452: $txt=~tr/A-J/0-9/;
13453: $txt=~tr/a-j/0-9/;
13454: $txt=~tr/K-T/0-9/;
13455: $txt=~tr/k-t/0-9/;
13456: $txt=~tr/U-Z/0-5/;
13457: $txt=~tr/u-z/0-5/;
13458: $txt=~s/\D//g;
13459: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13460: my $total;
13461: foreach my $val (@txts) { $total+=$val; }
13462: if ($_64bit) { $total=(($total<<32)>>32); }
13463: return $total;
13464: }
13465:
1.675 albertel 13466: sub digest {
13467: my ($data)=@_;
13468: my $digest=&Digest::MD5::md5($data);
13469: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13470: my ($e,$f);
13471: {
13472: use integer;
13473: $e=($a+$b);
13474: $f=($c+$d);
13475: if ($_64bit) {
13476: $e=(($e<<32)>>32);
13477: $f=(($f<<32)>>32);
13478: }
13479: }
13480: if (wantarray) {
13481: return ($e,$f);
13482: } else {
13483: my $g;
13484: {
13485: use integer;
13486: $g=($e+$f);
13487: if ($_64bit) {
13488: $g=(($g<<32)>>32);
13489: }
13490: }
13491: return $g;
13492: }
13493: }
13494:
1.368 albertel 13495: sub latest_rnd_algorithm_id {
1.675 albertel 13496: return '64bit5';
1.366 albertel 13497: }
1.32 www 13498:
1.503 albertel 13499: sub get_rand_alg {
13500: my ($courseid)=@_;
1.790 albertel 13501: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13502: if ($courseid) {
1.620 albertel 13503: return $env{"course.$courseid.rndseed"};
1.503 albertel 13504: }
13505: return &latest_rnd_algorithm_id();
13506: }
13507:
1.562 albertel 13508: sub validCODE {
13509: my ($CODE)=@_;
13510: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13511: return 0;
13512: }
13513:
1.491 albertel 13514: sub getCODE {
1.620 albertel 13515: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13516: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13517: defined($Apache::lonhomework::parsing_a_task) ) &&
13518: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13519: return $Apache::lonhomework::history{'resource.CODE'};
13520: }
13521: return undef;
13522: }
1.1133 foxr 13523: #
13524: # Determines the random seed for a specific context:
13525: #
13526: # parameters:
13527: # symb - in course context the symb for the seed.
13528: # course_id - The course id of the form domain_coursenum.
13529: # domain - Domain for the user.
13530: # course - Course for the user.
13531: # cenv - environment of the course.
13532: #
13533: # NOTE:
13534: # All parameters are picked out of the environment if missing
13535: # or not defined.
13536: # If a symb cannot be determined the current time is used instead.
13537: #
13538: # For a given well defined symb, courside, domain, username,
13539: # and course environment, the seed is reproducible.
13540: #
1.31 www 13541: sub rndseed {
1.1133 foxr 13542: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13543: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13544: if (!defined($symb)) {
1.366 albertel 13545: unless ($symb=$wsymb) { return time; }
13546: }
1.1146 foxr 13547: if (!defined $courseid) {
13548: $courseid=$wcourseid;
13549: }
13550: if (!defined $domain) { $domain=$wdomain; }
13551: if (!defined $username) { $username=$wusername }
1.1133 foxr 13552:
13553: my $which;
13554: if (defined($cenv->{'rndseed'})) {
13555: $which = $cenv->{'rndseed'};
13556: } else {
13557: $which =&get_rand_alg($courseid);
13558: }
1.491 albertel 13559: if (defined(&getCODE())) {
1.1133 foxr 13560:
1.675 albertel 13561: if ($which eq '64bit5') {
13562: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13563: } elsif ($which eq '64bit4') {
1.575 albertel 13564: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13565: } else {
13566: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13567: }
1.675 albertel 13568: } elsif ($which eq '64bit5') {
13569: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13570: } elsif ($which eq '64bit4') {
13571: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13572: } elsif ($which eq '64bit3') {
13573: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13574: } elsif ($which eq '64bit2') {
13575: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13576: } elsif ($which eq '64bit') {
13577: return &rndseed_64bit($symb,$courseid,$domain,$username);
13578: }
13579: return &rndseed_32bit($symb,$courseid,$domain,$username);
13580: }
13581:
13582: sub rndseed_32bit {
13583: my ($symb,$courseid,$domain,$username)=@_;
13584: {
13585: use integer;
13586: my $symbchck=unpack("%32C*",$symb) << 27;
13587: my $symbseed=numval($symb) << 22;
13588: my $namechck=unpack("%32C*",$username) << 17;
13589: my $nameseed=numval($username) << 12;
13590: my $domainseed=unpack("%32C*",$domain) << 7;
13591: my $courseseed=unpack("%32C*",$courseid);
13592: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13593: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13594: #&logthis("rndseed :$num:$symb");
1.564 albertel 13595: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13596: return $num;
13597: }
13598: }
13599:
13600: sub rndseed_64bit {
13601: my ($symb,$courseid,$domain,$username)=@_;
13602: {
13603: use integer;
13604: my $symbchck=unpack("%32S*",$symb) << 21;
13605: my $symbseed=numval($symb) << 10;
13606: my $namechck=unpack("%32S*",$username);
13607:
13608: my $nameseed=numval($username) << 21;
13609: my $domainseed=unpack("%32S*",$domain) << 10;
13610: my $courseseed=unpack("%32S*",$courseid);
13611:
13612: my $num1=$symbchck+$symbseed+$namechck;
13613: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13614: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13615: #&logthis("rndseed :$num:$symb");
1.564 albertel 13616: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13617: return "$num1,$num2";
1.155 albertel 13618: }
1.366 albertel 13619: }
13620:
1.443 albertel 13621: sub rndseed_64bit2 {
13622: my ($symb,$courseid,$domain,$username)=@_;
13623: {
13624: use integer;
13625: # strings need to be an even # of cahracters long, it it is odd the
13626: # last characters gets thrown away
13627: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13628: my $symbseed=numval($symb) << 10;
13629: my $namechck=unpack("%32S*",$username.' ');
13630:
13631: my $nameseed=numval($username) << 21;
1.501 albertel 13632: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13633: my $courseseed=unpack("%32S*",$courseid.' ');
13634:
13635: my $num1=$symbchck+$symbseed+$namechck;
13636: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13637: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13638: #&logthis("rndseed :$num:$symb");
1.803 albertel 13639: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13640: return "$num1,$num2";
13641: }
13642: }
13643:
13644: sub rndseed_64bit3 {
13645: my ($symb,$courseid,$domain,$username)=@_;
13646: {
13647: use integer;
13648: # strings need to be an even # of cahracters long, it it is odd the
13649: # last characters gets thrown away
13650: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13651: my $symbseed=numval2($symb) << 10;
13652: my $namechck=unpack("%32S*",$username.' ');
13653:
13654: my $nameseed=numval2($username) << 21;
1.443 albertel 13655: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13656: my $courseseed=unpack("%32S*",$courseid.' ');
13657:
13658: my $num1=$symbchck+$symbseed+$namechck;
13659: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13660: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13661: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13662: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13663:
1.503 albertel 13664: return "$num1:$num2";
1.443 albertel 13665: }
13666: }
13667:
1.575 albertel 13668: sub rndseed_64bit4 {
13669: my ($symb,$courseid,$domain,$username)=@_;
13670: {
13671: use integer;
13672: # strings need to be an even # of cahracters long, it it is odd the
13673: # last characters gets thrown away
13674: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13675: my $symbseed=numval3($symb) << 10;
13676: my $namechck=unpack("%32S*",$username.' ');
13677:
13678: my $nameseed=numval3($username) << 21;
13679: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13680: my $courseseed=unpack("%32S*",$courseid.' ');
13681:
13682: my $num1=$symbchck+$symbseed+$namechck;
13683: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13684: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13685: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13686: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13687:
1.575 albertel 13688: return "$num1:$num2";
13689: }
13690: }
13691:
1.675 albertel 13692: sub rndseed_64bit5 {
13693: my ($symb,$courseid,$domain,$username)=@_;
13694: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13695: return "$num1:$num2";
13696: }
13697:
1.366 albertel 13698: sub rndseed_CODE_64bit {
13699: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13700: {
1.366 albertel 13701: use integer;
1.443 albertel 13702: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13703: my $symbseed=numval2($symb);
1.491 albertel 13704: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13705: my $CODEseed=numval(&getCODE());
1.443 albertel 13706: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13707: my $num1=$symbseed+$CODEchck;
13708: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13709: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13710: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13711: if ($_64bit) { $num1=(($num1<<32)>>32); }
13712: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13713: return "$num1:$num2";
1.366 albertel 13714: }
13715: }
13716:
1.575 albertel 13717: sub rndseed_CODE_64bit4 {
13718: my ($symb,$courseid,$domain,$username)=@_;
13719: {
13720: use integer;
13721: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13722: my $symbseed=numval3($symb);
13723: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13724: my $CODEseed=numval3(&getCODE());
13725: my $courseseed=unpack("%32S*",$courseid.' ');
13726: my $num1=$symbseed+$CODEchck;
13727: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13728: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13729: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13730: if ($_64bit) { $num1=(($num1<<32)>>32); }
13731: if ($_64bit) { $num2=(($num2<<32)>>32); }
13732: return "$num1:$num2";
13733: }
13734: }
13735:
1.675 albertel 13736: sub rndseed_CODE_64bit5 {
13737: my ($symb,$courseid,$domain,$username)=@_;
13738: my $code = &getCODE();
13739: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13740: return "$num1:$num2";
13741: }
13742:
1.366 albertel 13743: sub setup_random_from_rndseed {
13744: my ($rndseed)=@_;
1.503 albertel 13745: if ($rndseed =~/([,:])/) {
1.1262 raeburn 13746: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13747: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13748: &Math::Random::random_set_seed_from_phrase($rndseed);
13749: } else {
13750: &Math::Random::random_set_seed($num1,$num2);
13751: }
1.366 albertel 13752: } else {
13753: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13754: }
1.36 albertel 13755: }
13756:
1.474 albertel 13757: sub latest_receipt_algorithm_id {
1.835 albertel 13758: return 'receipt3';
1.474 albertel 13759: }
13760:
1.480 www 13761: sub recunique {
13762: my $fucourseid=shift;
13763: my $unique;
1.835 albertel 13764: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13765: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13766: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13767: } else {
13768: $unique=$perlvar{'lonReceipt'};
13769: }
13770: return unpack("%32C*",$unique);
13771: }
13772:
13773: sub recprefix {
13774: my $fucourseid=shift;
13775: my $prefix;
1.835 albertel 13776: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13777: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13778: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13779: } else {
13780: $prefix=$perlvar{'lonHostID'};
13781: }
13782: return unpack("%32C*",$prefix);
13783: }
13784:
1.76 www 13785: sub ireceipt {
1.474 albertel 13786: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13787:
13788: my $return =&recprefix($fucourseid).'-';
13789:
13790: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13791: $env{'request.state'} eq 'construct') {
13792: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13793: return $return;
13794: }
13795:
1.76 www 13796: my $cuname=unpack("%32C*",$funame);
13797: my $cudom=unpack("%32C*",$fudom);
13798: my $cucourseid=unpack("%32C*",$fucourseid);
13799: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13800: my $cunique=&recunique($fucourseid);
1.474 albertel 13801: my $cpart=unpack("%32S*",$part);
1.835 albertel 13802: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13803:
1.790 albertel 13804: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13805:
13806: $return.= ($cunique%$cuname+
13807: $cunique%$cudom+
13808: $cusymb%$cuname+
13809: $cusymb%$cudom+
13810: $cucourseid%$cuname+
13811: $cucourseid%$cudom+
13812: $cpart%$cuname+
13813: $cpart%$cudom);
13814: } else {
13815: $return.= ($cunique%$cuname+
13816: $cunique%$cudom+
13817: $cusymb%$cuname+
13818: $cusymb%$cudom+
13819: $cucourseid%$cuname+
13820: $cucourseid%$cudom);
13821: }
13822: return $return;
1.76 www 13823: }
13824:
13825: sub receipt {
1.474 albertel 13826: my ($part)=@_;
1.790 albertel 13827: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13828: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13829: }
1.260 ng 13830:
1.790 albertel 13831: sub whichuser {
13832: my ($passedsymb)=@_;
13833: my ($symb,$courseid,$domain,$name,$publicuser);
13834: if (defined($env{'form.grade_symb'})) {
13835: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13836: my $allowed=&allowed('vgr',$tmp_courseid);
13837: if (!$allowed &&
13838: exists($env{'request.course.sec'}) &&
13839: $env{'request.course.sec'} !~ /^\s*$/) {
13840: $allowed=&allowed('vgr',$tmp_courseid.
13841: '/'.$env{'request.course.sec'});
13842: }
13843: if ($allowed) {
13844: ($symb)=&get_env_multiple('form.grade_symb');
13845: $courseid=$tmp_courseid;
13846: ($domain)=&get_env_multiple('form.grade_domain');
13847: ($name)=&get_env_multiple('form.grade_username');
13848: return ($symb,$courseid,$domain,$name,$publicuser);
13849: }
13850: }
13851: if (!$passedsymb) {
13852: $symb=&symbread();
13853: } else {
13854: $symb=$passedsymb;
13855: }
13856: $courseid=$env{'request.course.id'};
13857: $domain=$env{'user.domain'};
13858: $name=$env{'user.name'};
13859: if ($name eq 'public' && $domain eq 'public') {
13860: if (!defined($env{'form.username'})) {
13861: $env{'form.username'}.=time.rand(10000000);
13862: }
13863: $name.=$env{'form.username'};
13864: }
13865: return ($symb,$courseid,$domain,$name,$publicuser);
13866:
13867: }
13868:
1.36 albertel 13869: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13870: # returns either the contents of the file or
13871: # -1 if the file doesn't exist
1.481 raeburn 13872: #
13873: # if the target is a file that was uploaded via DOCS,
13874: # a check will be made to see if a current copy exists on the local server,
13875: # if it does this will be served, otherwise a copy will be retrieved from
13876: # the home server for the course and stored in /home/httpd/html/userfiles on
13877: # the local server.
1.472 albertel 13878:
1.36 albertel 13879: sub getfile {
1.538 albertel 13880: my ($file) = @_;
1.609 banghart 13881: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13882: &repcopy($file);
13883: return &readfile($file);
13884: }
13885:
13886: sub repcopy_userfile {
13887: my ($file)=@_;
1.1142 raeburn 13888: my $londocroot = $perlvar{'lonDocRoot'};
13889: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13890: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13891: my ($cdom,$cnum,$filename) =
1.811 albertel 13892: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13893: my $uri="/uploaded/$cdom/$cnum/$filename";
13894: if (-e "$file") {
1.828 www 13895: # we already have a local copy, check it out
1.538 albertel 13896: my @fileinfo = stat($file);
1.828 www 13897: my $rtncode;
13898: my $info;
1.538 albertel 13899: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13900: if ($lwpresp ne 'ok') {
1.828 www 13901: # there is no such file anymore, even though we had a local copy
1.482 albertel 13902: if ($rtncode eq '404') {
1.538 albertel 13903: unlink($file);
1.482 albertel 13904: }
13905: return -1;
13906: }
13907: if ($info < $fileinfo[9]) {
1.828 www 13908: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13909: return 'ok';
1.828 www 13910: } else {
13911: # the file is outdated, get rid of it
13912: unlink($file);
1.482 albertel 13913: }
1.828 www 13914: }
13915: # one way or the other, at this point, we don't have the file
13916: # construct the correct path for the file
13917: my @parts = ($cdom,$cnum);
13918: if ($filename =~ m|^(.+)/[^/]+$|) {
13919: push @parts, split(/\//,$1);
13920: }
13921: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13922: foreach my $part (@parts) {
13923: $path .= '/'.$part;
13924: if (!-e $path) {
13925: mkdir($path,0770);
1.482 albertel 13926: }
13927: }
1.828 www 13928: # now the path exists for sure
13929: # get a user agent
13930: my $transferfile=$file.'.in.transfer';
13931: # FIXME: this should flock
13932: if (-e $transferfile) { return 'ok'; }
13933: my $request;
13934: $uri=~s/^\///;
1.980 raeburn 13935: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 13936: my $hostname = &hostname($homeserver);
1.980 raeburn 13937: my $protocol = $protocol{$homeserver};
13938: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13939: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 13940: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 13941: # did it work?
13942: if ($response->is_error()) {
13943: unlink($transferfile);
13944: &logthis("Userfile repcopy failed for $uri");
13945: return -1;
13946: }
13947: # worked, rename the transfer file
13948: rename($transferfile,$file);
1.607 raeburn 13949: return 'ok';
1.481 raeburn 13950: }
13951:
1.517 albertel 13952: sub tokenwrapper {
13953: my $uri=shift;
1.980 raeburn 13954: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13955: $uri=~s|^/||;
1.620 albertel 13956: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13957: my $token=$1;
1.552 albertel 13958: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13959: if ($udom && $uname && $file) {
13960: $file=~s|(\?\.*)*$||;
1.949 raeburn 13961: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13962: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 13963: my $hostname = &hostname($homeserver);
1.980 raeburn 13964: my $protocol = $protocol{$homeserver};
13965: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13966: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13967: (($uri=~/\?/)?'&':'?').'token='.$token.
13968: '&tokenissued='.$perlvar{'lonHostID'};
13969: } else {
13970: return '/adm/notfound.html';
13971: }
13972: }
13973:
1.828 www 13974: # call with reqtype HEAD: get last modification time
13975: # call with reqtype GET: get the file contents
13976: # Do not call this with reqtype GET for large files! It loads everything into memory
13977: #
1.481 raeburn 13978: sub getuploaded {
13979: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13980: $uri=~s/^\///;
1.980 raeburn 13981: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 13982: my $hostname = &hostname($homeserver);
1.980 raeburn 13983: my $protocol = $protocol{$homeserver};
13984: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 13985: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13986: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 13987: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 13988: $$rtncode = $response->code;
1.482 albertel 13989: if (! $response->is_success()) {
13990: return 'failed';
13991: }
13992: if ($reqtype eq 'HEAD') {
1.486 www 13993: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13994: } elsif ($reqtype eq 'GET') {
13995: $$info = $response->content;
1.472 albertel 13996: }
1.482 albertel 13997: return 'ok';
1.36 albertel 13998: }
13999:
1.481 raeburn 14000: sub readfile {
14001: my $file = shift;
14002: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14003: my $fh;
1.1359 raeburn 14004: open($fh,"<",$file);
1.481 raeburn 14005: my $a='';
1.800 albertel 14006: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14007: return $a;
14008: }
14009:
1.36 albertel 14010: sub filelocation {
1.590 banghart 14011: my ($dir,$file) = @_;
14012: my $location;
14013: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14014:
14015: if ($file =~ m-^/adm/-) {
14016: $file=~s-^/adm/wrapper/-/-;
14017: $file=~s-^/adm/coursedocs/showdoc/-/-;
14018: }
1.882 albertel 14019:
1.1139 www 14020: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14021: $location = $file;
1.609 banghart 14022: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14023: my ($udom,$uname,$filename)=
1.811 albertel 14024: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14025: my $home=&homeserver($uname,$udom);
14026: my $is_me=0;
14027: my @ids=¤t_machine_ids();
14028: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14029: if ($is_me) {
1.1117 foxr 14030: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14031: } else {
14032: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14033: $udom.'/'.$uname.'/'.$filename;
14034: }
1.882 albertel 14035: } elsif ($file =~ m-^/adm/-) {
14036: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14037: } else {
14038: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14039: $file=~s:^/(res|priv)/:/:;
14040: my $space=$1;
1.590 banghart 14041: if ( !( $file =~ m:^/:) ) {
14042: $location = $dir. '/'.$file;
14043: } else {
1.1142 raeburn 14044: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14045: }
1.59 albertel 14046: }
1.590 banghart 14047: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14048: while ($location=~m{/\.\./}) {
14049: if ($location =~ m{/[^/]+/\.\./}) {
14050: $location=~ s{/[^/]+/\.\./}{/}g;
14051: } else {
14052: $location=~ s{/\.\./}{/}g;
14053: }
14054: } #remove dir/..
1.590 banghart 14055: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14056: return $location;
1.46 www 14057: }
1.36 albertel 14058:
1.46 www 14059: sub hreflocation {
14060: my ($dir,$file)=@_;
1.980 raeburn 14061: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14062: $file=filelocation($dir,$file);
1.700 albertel 14063: } elsif ($file=~m-^/adm/-) {
14064: $file=~s-^/adm/wrapper/-/-;
14065: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14066: }
14067: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14068: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14069: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14070: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14071: {/uploaded/$1/$2/}x;
1.46 www 14072: }
1.913 albertel 14073: if ($file=~ m{^/userfiles/}) {
14074: $file =~ s{^/userfiles/}{/uploaded/};
14075: }
1.462 albertel 14076: return $file;
1.465 albertel 14077: }
14078:
1.1139 www 14079:
14080:
14081:
14082:
1.465 albertel 14083: sub current_machine_domains {
1.853 albertel 14084: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14085: }
14086:
14087: sub machine_domains {
14088: my ($hostname) = @_;
1.465 albertel 14089: my @domains;
1.838 albertel 14090: my %hostname = &all_hostnames();
1.465 albertel 14091: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14092: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14093: if ($hostname eq $name) {
1.844 albertel 14094: push(@domains,&host_domain($id));
1.465 albertel 14095: }
14096: }
14097: return @domains;
14098: }
14099:
14100: sub current_machine_ids {
1.853 albertel 14101: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14102: }
14103:
14104: sub machine_ids {
14105: my ($hostname) = @_;
14106: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14107: my @ids;
1.888 albertel 14108: my %name_to_host = &all_names();
1.889 albertel 14109: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14110: return @{ $name_to_host{$hostname} };
14111: }
14112: return;
1.31 www 14113: }
14114:
1.824 raeburn 14115: sub additional_machine_domains {
14116: my @domains;
1.1359 raeburn 14117: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 14118: while( my $line = <$fh>) {
14119: $line =~ s/\s//g;
14120: push(@domains,$line);
14121: }
14122: return @domains;
14123: }
14124:
14125: sub default_login_domain {
14126: my $domain = $perlvar{'lonDefDomain'};
14127: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14128: foreach my $posdom (¤t_machine_domains(),
14129: &additional_machine_domains()) {
14130: if (lc($posdom) eq lc($testdomain)) {
14131: $domain=$posdom;
14132: last;
14133: }
14134: }
14135: return $domain;
14136: }
14137:
1.1414 raeburn 14138: sub shared_institution {
14139: my ($dom) = @_;
14140: my $same_intdom;
14141: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14142: if ($hostintdom ne '') {
14143: my %iphost = &get_iphost();
14144: my $primary_id = &domain($dom,'primary');
14145: my $primary_ip = &get_host_ip($primary_id);
14146: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14147: foreach my $id (@{$iphost{$primary_ip}}) {
14148: my $intdom = &internet_dom($id);
14149: if ($intdom eq $hostintdom) {
14150: $same_intdom = 1;
14151: last;
14152: }
14153: }
14154: }
14155: }
14156: return $same_intdom;
14157: }
14158:
1.1398 raeburn 14159: sub uses_sts {
14160: my ($ignore_cache) = @_;
14161: my $lonhost = $perlvar{'lonHostID'};
14162: my $hostname = &hostname($lonhost);
14163: my $sts_on;
14164: if ($protocol{$lonhost} eq 'https') {
14165: my $cachetime = 12*3600;
14166: if (!$ignore_cache) {
14167: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14168: if (defined($cached)) {
14169: return $sts_on;
14170: }
14171: }
14172: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14173: my $request=new HTTP::Request('HEAD',$url);
14174: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14175: if ($response->is_success) {
14176: my $has_sts = $response->header('Strict-Transport-Security');
14177: if ($has_sts eq '') {
14178: $sts_on = 0;
14179: } else {
14180: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14181: my $maxage = $1;
14182: if ($maxage) {
14183: $sts_on = 1;
14184: } else {
14185: $sts_on = 0;
14186: }
14187: } else {
14188: $sts_on = 0;
14189: }
14190: }
14191: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14192: }
14193: }
14194: return;
14195: }
14196:
1.31 www 14197: # ------------------------------------------------------------- Declutters URLs
14198:
14199: sub declutter {
14200: my $thisfn=shift;
1.569 albertel 14201: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 14202: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14203: $thisfn=~s{^/home/httpd/html}{};
14204: }
1.31 www 14205: $thisfn=~s/^\///;
1.697 albertel 14206: $thisfn=~s|^adm/wrapper/||;
14207: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14208: $thisfn=~s/^res\///;
1.1172 bisitz 14209: $thisfn=~s/^priv\///;
1.1032 raeburn 14210: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14211: $thisfn=~s/\?.+$//;
14212: }
1.268 www 14213: return $thisfn;
14214: }
14215:
14216: # ------------------------------------------------------------- Clutter up URLs
14217:
14218: sub clutter {
14219: my $thisfn='/'.&declutter(shift);
1.887 albertel 14220: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14221: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14222: $thisfn='/res'.$thisfn;
14223: }
1.1031 raeburn 14224: if ($thisfn !~m|^/adm|) {
14225: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14226: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14227: } else {
14228: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14229: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14230: if ($embstyle eq 'ssi'
14231: || ($embstyle eq 'hdn')
14232: || ($embstyle eq 'rat')
14233: || ($embstyle eq 'prv')
14234: || ($embstyle eq 'ign')) {
14235: #do nothing with these
14236: } elsif (($embstyle eq 'img')
1.695 albertel 14237: || ($embstyle eq 'emb')
14238: || ($embstyle eq 'wrp')) {
14239: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14240: } elsif ($embstyle eq 'unk'
14241: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14242: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14243: } else {
1.718 www 14244: # &logthis("Got a blank emb style");
1.695 albertel 14245: }
1.694 albertel 14246: }
1.1343 raeburn 14247: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14248: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14249: }
1.31 www 14250: return $thisfn;
1.12 www 14251: }
14252:
1.787 albertel 14253: sub clutter_with_no_wrapper {
14254: my $uri = &clutter(shift);
14255: if ($uri =~ m-^/adm/-) {
14256: $uri =~ s-^/adm/wrapper/-/-;
14257: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14258: }
14259: return $uri;
14260: }
14261:
1.557 albertel 14262: sub freeze_escape {
14263: my ($value)=@_;
14264: if (ref($value)) {
14265: $value=&nfreeze($value);
14266: return '__FROZEN__'.&escape($value);
14267: }
14268: return &escape($value);
14269: }
14270:
1.11 www 14271:
1.557 albertel 14272: sub thaw_unescape {
14273: my ($value)=@_;
14274: if ($value =~ /^__FROZEN__/) {
14275: substr($value,0,10,undef);
14276: $value=&unescape($value);
14277: return &thaw($value);
14278: }
14279: return &unescape($value);
14280: }
14281:
1.436 albertel 14282: sub correct_line_ends {
14283: my ($result)=@_;
14284: $$result =~s/\r\n/\n/mg;
14285: $$result =~s/\r/\n/mg;
1.415 albertel 14286: }
1.1 albertel 14287: # ================================================================ Main Program
14288:
1.184 www 14289: sub goodbye {
1.204 albertel 14290: &logthis("Starting Shut down");
1.443 albertel 14291: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14292: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14293: #converted
1.599 albertel 14294: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14295: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14296: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14297: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14298: #1.1 only
1.870 albertel 14299: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14300: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14301: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14302: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14303: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14304: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14305: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14306: &flushcourselogs();
14307: &logthis("Shutting down");
14308: }
14309:
1.852 albertel 14310: sub get_dns {
1.1210 raeburn 14311: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14312: if (!$ignore_cache) {
14313: my ($content,$cached)=
14314: &Apache::lonnet::is_cached_new('dns',$url);
14315: if ($cached) {
1.1210 raeburn 14316: &$func($content,$hashref);
1.869 albertel 14317: return;
14318: }
14319: }
14320:
14321: my %alldns;
1.1379 raeburn 14322: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14323: foreach my $dns (<$config>) {
14324: next if ($dns !~ /^\^(\S*)/x);
14325: my $line = $1;
14326: my ($host,$protocol) = split(/:/,$line);
14327: if ($protocol ne 'https') {
14328: $protocol = 'http';
14329: }
14330: $alldns{$host} = $protocol;
1.979 raeburn 14331: }
1.1379 raeburn 14332: close($config);
1.869 albertel 14333: }
14334: while (%alldns) {
1.1263 raeburn 14335: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 14336: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 14337: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 14338: delete($alldns{$dns});
1.852 albertel 14339: next if ($response->is_error());
1.1379 raeburn 14340: if ($url eq '/adm/dns/loncapaCRL') {
14341: return &$func($response);
14342: } else {
14343: my @content = split("\n",$response->content);
14344: unless ($nocache) {
14345: &do_cache_new('dns',$url,\@content,30*24*60*60);
14346: }
14347: &$func(\@content,$hashref);
14348: return;
14349: }
14350: }
14351: my $which = (split('/',$url,4))[3];
14352: if ($which eq 'loncapaCRL') {
14353: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14354: if (-e $diskfile) {
14355: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14356: } else {
14357: &logthis("unable to contact DNS, no on disk file $diskfile available");
14358: }
14359: } else {
14360: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14361: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14362: my @content = <$config>;
14363: close($config);
14364: &$func(\@content,$hashref);
14365: }
1.852 albertel 14366: }
1.1210 raeburn 14367: return;
14368: }
14369:
14370: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 14371: sub parse_dns_checksums_tab {
1.1210 raeburn 14372: my ($lines,$hashref) = @_;
1.1264 raeburn 14373: my $lonhost = $perlvar{'lonHostID'};
14374: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 14375: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 14376: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14377: my $webconfdir = '/etc/httpd/conf';
14378: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14379: $webconfdir = '/etc/apache2';
14380: } elsif ($distro =~ /^sles(\d+)$/) {
14381: if ($1 >= 10) {
14382: $webconfdir = '/etc/apache2';
14383: }
14384: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14385: if ($1 >= 10.0) {
14386: $webconfdir = '/etc/apache2';
14387: }
14388: }
1.1210 raeburn 14389: my ($release,$timestamp) = split(/\-/,$loncaparev);
14390: my (%chksum,%revnum);
14391: if (ref($lines) eq 'ARRAY') {
14392: chomp(@{$lines});
1.1238 raeburn 14393: my $version = shift(@{$lines});
14394: if ($version eq $release) {
1.1210 raeburn 14395: foreach my $line (@{$lines}) {
1.1238 raeburn 14396: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 14397: if ($file =~ m{^/etc/httpd/conf}) {
14398: if ($webconfdir eq '/etc/apache2') {
14399: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14400: }
14401: }
1.1238 raeburn 14402: $chksum{$file} = $shasum;
14403: $revnum{$file} = $version;
1.1210 raeburn 14404: }
14405: if (ref($hashref) eq 'HASH') {
14406: %{$hashref} = (
14407: sums => \%chksum,
14408: versions => \%revnum,
14409: );
14410: }
14411: }
14412: }
1.869 albertel 14413: return;
1.852 albertel 14414: }
1.1210 raeburn 14415:
14416: sub fetch_dns_checksums {
1.1238 raeburn 14417: my %checksums;
14418: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 14419: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 14420: my ($release,$timestamp) = split(/\-/,$loncaparev);
14421: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 14422: \%checksums);
1.1210 raeburn 14423: return \%checksums;
14424: }
14425:
1.1379 raeburn 14426: sub fetch_crl_pemfile {
14427: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14428: }
14429:
14430: sub save_crl_pem {
14431: my ($response) = @_;
1.1380 raeburn 14432: my ($msg,$hadchanges);
1.1379 raeburn 14433: if (ref($response)) {
14434: my $now = time;
14435: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14436: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14437: if (open(my $fh,'>',"$tmpcrl")) {
14438: print $fh $response->content;
14439: close($fh);
14440: if (-e $lonca) {
14441: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14442: my $check = <PIPE>;
14443: close(PIPE);
14444: chomp($check);
14445: if ($check eq 'verify OK') {
14446: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 14447: my $backup;
1.1379 raeburn 14448: if (-e $dest) {
1.1380 raeburn 14449: if (&File::Copy::move($dest,"$dest.bak")) {
14450: $backup = 'ok';
14451: }
1.1379 raeburn 14452: }
14453: if (&File::Copy::move($tmpcrl,$dest)) {
14454: $msg = 'ok';
1.1380 raeburn 14455: if ($backup) {
14456: my (%oldnums,%newnums);
14457: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14458: while (<PIPE>) {
14459: $oldnums{(split(/:/))[1]} = 1;
14460: }
14461: close(PIPE);
14462: }
14463: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14464: while(<PIPE>) {
14465: $newnums{(split(/:/))[1]} = 1;
14466: }
14467: close(PIPE);
14468: }
14469: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14470: unless (exists($oldnums{$key})) {
14471: $hadchanges = 1;
14472: last;
14473: }
14474: }
14475: unless ($hadchanges) {
14476: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14477: unless (exists($newnums{$key})) {
14478: $hadchanges = 1;
14479: last;
14480: }
14481: }
14482: }
14483: }
1.1379 raeburn 14484: }
14485: } else {
14486: unlink($tmpcrl);
14487: }
14488: } else {
14489: unlink($tmpcrl);
14490: }
14491: } else {
14492: unlink($tmpcrl);
14493: }
14494: }
14495: }
1.1380 raeburn 14496: return ($msg,$hadchanges);
1.1379 raeburn 14497: }
14498:
1.327 albertel 14499: # ------------------------------------------------------------ Read domain file
14500: {
1.852 albertel 14501: my $loaded;
1.846 albertel 14502: my %domain;
14503:
1.852 albertel 14504: sub parse_domain_tab {
14505: my ($lines) = @_;
14506: foreach my $line (@$lines) {
14507: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14508:
1.846 albertel 14509: chomp($line);
1.852 albertel 14510: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14511: my %this_domain;
14512: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14513: 'lang_def', 'city', 'longi', 'lati',
14514: 'primary') {
14515: $this_domain{$field} = shift(@elements);
14516: }
14517: $domain{$name} = \%this_domain;
1.852 albertel 14518: }
14519: }
1.864 albertel 14520:
14521: sub reset_domain_info {
14522: undef($loaded);
14523: undef(%domain);
14524: }
14525:
1.852 albertel 14526: sub load_domain_tab {
1.1293 raeburn 14527: my ($ignore_cache,$nocache) = @_;
14528: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14529: my $fh;
1.1359 raeburn 14530: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14531: my @lines = <$fh>;
14532: &parse_domain_tab(\@lines);
1.448 albertel 14533: }
1.852 albertel 14534: close($fh);
14535: $loaded = 1;
1.327 albertel 14536: }
1.846 albertel 14537:
14538: sub domain {
1.852 albertel 14539: &load_domain_tab() if (!$loaded);
14540:
1.846 albertel 14541: my ($name,$what) = @_;
14542: return if ( !exists($domain{$name}) );
14543:
14544: if (!$what) {
14545: return $domain{$name}{'description'};
14546: }
14547: return $domain{$name}{$what};
14548: }
1.974 raeburn 14549:
14550: sub domain_info {
14551: &load_domain_tab() if (!$loaded);
14552: return %domain;
14553: }
14554:
1.327 albertel 14555: }
14556:
14557:
1.1 albertel 14558: # ------------------------------------------------------------- Read hosts file
14559: {
1.838 albertel 14560: my %hostname;
1.844 albertel 14561: my %hostdom;
1.845 albertel 14562: my %libserv;
1.852 albertel 14563: my $loaded;
1.888 albertel 14564: my %name_to_host;
1.1074 raeburn 14565: my %internetdom;
1.1107 raeburn 14566: my %LC_dns_serv;
1.852 albertel 14567:
14568: sub parse_hosts_tab {
14569: my ($file) = @_;
14570: foreach my $configline (@$file) {
14571: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14572: chomp($configline);
14573: if ($configline =~ /^\^/) {
14574: if ($configline =~ /^\^([\w.\-]+)/) {
14575: $LC_dns_serv{$1} = 1;
14576: }
14577: next;
14578: }
1.1074 raeburn 14579: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14580: $name=~s/\s//g;
14581: if ($id && $domain && $role && $name) {
1.1351 raeburn 14582: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14583: my $curr = $hostname{$id};
14584: my $skip;
14585: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14586: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14587: $skip = 1;
14588: } else {
14589: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14590: }
14591: }
14592: unless ($skip) {
14593: push(@{$name_to_host{$name}},$id);
14594: }
14595: } else {
14596: push(@{$name_to_host{$name}},$id);
14597: }
1.852 albertel 14598: $hostname{$id}=$name;
14599: $hostdom{$id}=$domain;
14600: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14601: if (defined($protocol)) {
14602: if ($protocol eq 'https') {
14603: $protocol{$id} = $protocol;
14604: } else {
14605: $protocol{$id} = 'http';
14606: }
1.968 raeburn 14607: } else {
1.969 raeburn 14608: $protocol{$id} = 'http';
1.968 raeburn 14609: }
1.1074 raeburn 14610: if (defined($intdom)) {
14611: $internetdom{$id} = $intdom;
14612: }
1.852 albertel 14613: }
14614: }
14615: }
1.864 albertel 14616:
14617: sub reset_hosts_info {
1.897 albertel 14618: &purge_remembered();
1.864 albertel 14619: &reset_domain_info();
14620: &reset_hosts_ip_info();
1.1339 raeburn 14621: undef(%internetdom);
1.892 albertel 14622: undef(%name_to_host);
1.864 albertel 14623: undef(%hostname);
14624: undef(%hostdom);
14625: undef(%libserv);
14626: undef($loaded);
14627: }
1.1 albertel 14628:
1.852 albertel 14629: sub load_hosts_tab {
1.1293 raeburn 14630: my ($ignore_cache,$nocache) = @_;
14631: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 14632: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14633: my @config = <$config>;
14634: &parse_hosts_tab(\@config);
14635: close($config);
14636: $loaded=1;
1.1 albertel 14637: }
1.852 albertel 14638:
1.838 albertel 14639: sub hostname {
1.852 albertel 14640: &load_hosts_tab() if (!$loaded);
14641:
1.838 albertel 14642: my ($lonid) = @_;
14643: return $hostname{$lonid};
14644: }
1.845 albertel 14645:
1.838 albertel 14646: sub all_hostnames {
1.852 albertel 14647: &load_hosts_tab() if (!$loaded);
14648:
1.838 albertel 14649: return %hostname;
14650: }
1.845 albertel 14651:
1.888 albertel 14652: sub all_names {
1.1293 raeburn 14653: my ($ignore_cache,$nocache) = @_;
14654: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14655:
14656: return %name_to_host;
14657: }
14658:
1.974 raeburn 14659: sub all_host_domain {
14660: &load_hosts_tab() if (!$loaded);
14661: return %hostdom;
14662: }
14663:
1.1339 raeburn 14664: sub all_host_intdom {
14665: &load_hosts_tab() if (!$loaded);
14666: return %internetdom;
14667: }
14668:
1.845 albertel 14669: sub is_library {
1.852 albertel 14670: &load_hosts_tab() if (!$loaded);
14671:
1.845 albertel 14672: return exists($libserv{$_[0]});
14673: }
14674:
14675: sub all_library {
1.852 albertel 14676: &load_hosts_tab() if (!$loaded);
14677:
1.845 albertel 14678: return %libserv;
14679: }
14680:
1.1062 droeschl 14681: sub unique_library {
14682: #2x reverse removes all hostnames that appear more than once
14683: my %unique = reverse &all_library();
14684: return reverse %unique;
14685: }
14686:
1.841 albertel 14687: sub get_servers {
1.852 albertel 14688: &load_hosts_tab() if (!$loaded);
14689:
1.841 albertel 14690: my ($domain,$type) = @_;
14691: my %possible_hosts = ($type eq 'library') ? %libserv
14692: : %hostname;
14693: my %result;
1.842 albertel 14694: if (ref($domain) eq 'ARRAY') {
14695: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14696: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14697: $result{$host} = $hostname;
14698: }
14699: }
14700: } else {
14701: while ( my ($host,$hostname) = each(%possible_hosts)) {
14702: if ($hostdom{$host} eq $domain) {
14703: $result{$host} = $hostname;
14704: }
1.841 albertel 14705: }
14706: }
14707: return %result;
14708: }
1.845 albertel 14709:
1.1062 droeschl 14710: sub get_unique_servers {
14711: my %unique = reverse &get_servers(@_);
14712: return reverse %unique;
14713: }
14714:
1.844 albertel 14715: sub host_domain {
1.852 albertel 14716: &load_hosts_tab() if (!$loaded);
14717:
1.844 albertel 14718: my ($lonid) = @_;
14719: return $hostdom{$lonid};
14720: }
14721:
1.841 albertel 14722: sub all_domains {
1.852 albertel 14723: &load_hosts_tab() if (!$loaded);
14724:
1.841 albertel 14725: my %seen;
14726: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14727: return @uniq;
14728: }
1.1074 raeburn 14729:
14730: sub internet_dom {
14731: &load_hosts_tab() if (!$loaded);
14732:
14733: my ($lonid) = @_;
14734: return $internetdom{$lonid};
14735: }
1.1107 raeburn 14736:
14737: sub is_LC_dns {
14738: &load_hosts_tab() if (!$loaded);
14739:
14740: my ($hostname) = @_;
14741: return exists($LC_dns_serv{$hostname});
14742: }
14743:
1.1 albertel 14744: }
14745:
1.847 albertel 14746: {
14747: my %iphost;
1.856 albertel 14748: my %name_to_ip;
14749: my %lonid_to_ip;
1.869 albertel 14750:
1.847 albertel 14751: sub get_hosts_from_ip {
14752: my ($ip) = @_;
14753: my %iphosts = &get_iphost();
14754: if (ref($iphosts{$ip})) {
14755: return @{$iphosts{$ip}};
14756: }
14757: return;
1.839 albertel 14758: }
1.864 albertel 14759:
14760: sub reset_hosts_ip_info {
14761: undef(%iphost);
14762: undef(%name_to_ip);
14763: undef(%lonid_to_ip);
14764: }
1.856 albertel 14765:
14766: sub get_host_ip {
14767: my ($lonid) = @_;
14768: if (exists($lonid_to_ip{$lonid})) {
14769: return $lonid_to_ip{$lonid};
14770: }
14771: my $name=&hostname($lonid);
14772: my $ip = gethostbyname($name);
14773: return if (!$ip || length($ip) ne 4);
14774: $ip=inet_ntoa($ip);
14775: $name_to_ip{$name} = $ip;
14776: $lonid_to_ip{$lonid} = $ip;
14777: return $ip;
14778: }
1.847 albertel 14779:
14780: sub get_iphost {
1.1293 raeburn 14781: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14782:
1.869 albertel 14783: if (!$ignore_cache) {
14784: if (%iphost) {
14785: return %iphost;
14786: }
14787: my ($ip_info,$cached)=
14788: &Apache::lonnet::is_cached_new('iphost','iphost');
14789: if ($cached) {
14790: %iphost = %{$ip_info->[0]};
14791: %name_to_ip = %{$ip_info->[1]};
14792: %lonid_to_ip = %{$ip_info->[2]};
14793: return %iphost;
14794: }
14795: }
1.894 albertel 14796:
14797: # get yesterday's info for fallback
14798: my %old_name_to_ip;
14799: my ($ip_info,$cached)=
14800: &Apache::lonnet::is_cached_new('iphost','iphost');
14801: if ($cached) {
14802: %old_name_to_ip = %{$ip_info->[1]};
14803: }
14804:
1.1293 raeburn 14805: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14806: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14807: my $ip;
14808: if (!exists($name_to_ip{$name})) {
14809: $ip = gethostbyname($name);
14810: if (!$ip || length($ip) ne 4) {
1.894 albertel 14811: if (defined($old_name_to_ip{$name})) {
14812: $ip = $old_name_to_ip{$name};
14813: &logthis("Can't find $name defaulting to old $ip");
14814: } else {
14815: &logthis("Name $name no IP found");
14816: next;
14817: }
14818: } else {
14819: $ip=inet_ntoa($ip);
1.847 albertel 14820: }
14821: $name_to_ip{$name} = $ip;
14822: } else {
14823: $ip = $name_to_ip{$name};
1.653 albertel 14824: }
1.888 albertel 14825: foreach my $id (@{ $name_to_host{$name} }) {
14826: $lonid_to_ip{$id} = $ip;
14827: }
14828: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14829: }
1.1293 raeburn 14830: unless ($nocache) {
14831: &do_cache_new('iphost','iphost',
14832: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14833: 48*60*60);
14834: }
1.869 albertel 14835:
1.847 albertel 14836: return %iphost;
1.598 albertel 14837: }
14838:
1.992 raeburn 14839: #
14840: # Given a DNS returns the loncapa host name for that DNS
14841: #
14842: sub host_from_dns {
14843: my ($dns) = @_;
14844: my @hosts;
14845: my $ip;
14846:
1.993 raeburn 14847: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14848: $ip = $name_to_ip{$dns};
14849: }
14850: if (!$ip) {
14851: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14852: if (length($ip) == 4) {
14853: $ip = &IO::Socket::inet_ntoa($ip);
14854: }
14855: }
14856: if ($ip) {
14857: @hosts = get_hosts_from_ip($ip);
14858: return $hosts[0];
14859: }
14860: return undef;
1.986 foxr 14861: }
1.992 raeburn 14862:
1.1074 raeburn 14863: sub get_internet_names {
14864: my ($lonid) = @_;
14865: return if ($lonid eq '');
14866: my ($idnref,$cached)=
14867: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14868: if ($cached) {
14869: return $idnref;
14870: }
14871: my $ip = &get_host_ip($lonid);
14872: my @hosts = &get_hosts_from_ip($ip);
14873: my %iphost = &get_iphost();
14874: my (@idns,%seen);
14875: foreach my $id (@hosts) {
14876: my $dom = &host_domain($id);
14877: my $prim_id = &domain($dom,'primary');
14878: my $prim_ip = &get_host_ip($prim_id);
14879: next if ($seen{$prim_ip});
14880: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14881: foreach my $id (@{$iphost{$prim_ip}}) {
14882: my $intdom = &internet_dom($id);
14883: unless (grep(/^\Q$intdom\E$/,@idns)) {
14884: push(@idns,$intdom);
14885: }
14886: }
14887: }
14888: $seen{$prim_ip} = 1;
14889: }
1.1219 raeburn 14890: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14891: }
14892:
1.986 foxr 14893: }
14894:
1.1079 raeburn 14895: sub all_loncaparevs {
1.1249 raeburn 14896: 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 14897: }
14898:
1.1227 raeburn 14899: # ---------------------------------------------------------- Read loncaparev table
14900: {
14901: sub load_loncaparevs {
14902: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 14903: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 14904: while (my $configline=<$config>) {
14905: chomp($configline);
14906: my ($hostid,$loncaparev)=split(/:/,$configline);
14907: $loncaparevs{$hostid}=$loncaparev;
14908: }
14909: close($config);
14910: }
14911: }
14912: }
14913: }
14914:
14915: # ---------------------------------------------------------- Read serverhostID table
14916: {
14917: sub load_serverhomeIDs {
14918: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 14919: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 14920: while (my $configline=<$config>) {
14921: chomp($configline);
14922: my ($name,$id)=split(/:/,$configline);
14923: $serverhomeIDs{$name}=$id;
14924: }
14925: close($config);
14926: }
14927: }
14928: }
14929: }
14930:
14931:
1.862 albertel 14932: BEGIN {
14933:
14934: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14935: unless ($readit) {
14936: {
14937: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14938: %perlvar = (%perlvar,%{$configvars});
14939: }
14940:
14941:
1.1 albertel 14942: # ------------------------------------------------------ Read spare server file
14943: {
1.1359 raeburn 14944: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14945:
14946: while (my $configline=<$config>) {
14947: chomp($configline);
1.284 matthew 14948: if ($configline) {
1.784 albertel 14949: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14950: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14951: push(@{ $spareid{$type} }, $host);
1.1 albertel 14952: }
14953: }
1.448 albertel 14954: close($config);
1.1 albertel 14955: }
1.11 www 14956: # ------------------------------------------------------------ Read permissions
14957: {
1.1359 raeburn 14958: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14959:
14960: while (my $configline=<$config>) {
1.448 albertel 14961: chomp($configline);
14962: if ($configline) {
14963: my ($role,$perm)=split(/ /,$configline);
14964: if ($perm ne '') { $pr{$role}=$perm; }
14965: }
1.11 www 14966: }
1.448 albertel 14967: close($config);
1.11 www 14968: }
14969:
14970: # -------------------------------------------- Read plain texts for permissions
14971: {
1.1359 raeburn 14972: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14973:
14974: while (my $configline=<$config>) {
1.448 albertel 14975: chomp($configline);
14976: if ($configline) {
1.742 raeburn 14977: my ($short,@plain)=split(/:/,$configline);
14978: %{$prp{$short}} = ();
14979: if (@plain > 0) {
14980: $prp{$short}{'std'} = $plain[0];
14981: for (my $i=1; $i<@plain; $i++) {
14982: $prp{$short}{'alt'.$i} = $plain[$i];
14983: }
14984: }
1.448 albertel 14985: }
1.135 www 14986: }
1.448 albertel 14987: close($config);
1.135 www 14988: }
14989:
14990: # ---------------------------------------------------------- Read package table
14991: {
1.1359 raeburn 14992: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14993:
14994: while (my $configline=<$config>) {
1.483 albertel 14995: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14996: chomp($configline);
14997: my ($short,$plain)=split(/:/,$configline);
14998: my ($pack,$name)=split(/\&/,$short);
14999: if ($plain ne '') {
15000: $packagetab{$pack.'&'.$name.'&name'}=$name;
15001: $packagetab{$short}=$plain;
15002: }
1.11 www 15003: }
1.448 albertel 15004: close($config);
1.329 matthew 15005: }
15006:
1.1073 raeburn 15007: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15008:
15009: &load_loncaparevs();
1.1073 raeburn 15010:
1.1074 raeburn 15011: # ---------------------------------------------------------- Read serverhostID table
15012:
1.1227 raeburn 15013: &load_serverhomeIDs();
15014:
15015: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15016: {
15017: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15018: if (-e $file) {
15019: my $parser = HTML::LCParser->new($file);
15020: while (my $token = $parser->get_token()) {
15021: if ($token->[0] eq 'S') {
15022: my $item = $token->[1];
15023: my $name = $token->[2]{'name'};
15024: my $value = $token->[2]{'value'};
1.1285 raeburn 15025: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15026: my $namematch = $token->[2]{'namematch'};
15027: if ($item eq 'parameter') {
15028: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15029: my $release = $parser->get_text();
15030: $release =~ s/(^\s*|\s*$ )//gx;
15031: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15032: }
15033: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15034: my $release = $parser->get_text();
15035: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15036: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15037: }
15038: }
15039: }
15040: }
1.1073 raeburn 15041: }
15042:
1.1138 raeburn 15043: # ---------------------------------------------------------- Read managers table
15044: {
15045: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15046: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15047: while (my $configline=<$config>) {
15048: chomp($configline);
15049: next if ($configline =~ /^\#/);
15050: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15051: $managerstab{$configline} = 1;
15052: }
15053: }
15054: close($config);
15055: }
15056: }
15057: }
15058:
1.329 matthew 15059: # ------------- set up temporary directory
15060: {
1.1117 foxr 15061: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15062:
1.11 www 15063: }
15064:
1.1405 raeburn 15065: # ------------- set default texengine (domain default overrides this)
15066: {
15067: $deftex = LONCAPA::texengine();
15068: }
15069:
1.1416 raeburn 15070: # ------------- set default minimum length for passwords for internal auth users
15071: {
15072: $passwdmin = LONCAPA::passwd_min();
15073: }
15074:
1.794 albertel 15075: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15076: 'compress_threshold'=> 20_000,
15077: });
1.185 www 15078:
1.281 www 15079: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15080: $dumpcount=0;
1.958 www 15081: $locknum=0;
1.22 www 15082:
1.163 harris41 15083: &logtouch();
1.672 albertel 15084: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15085: $readit=1;
1.564 albertel 15086: {
15087: use integer;
15088: my $test=(2**32)+1;
1.568 albertel 15089: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15090: &logthis(" Detected 64bit platform ($_64bit)");
15091: }
1.195 www 15092: }
1.1 albertel 15093: }
1.179 www 15094:
1.1 albertel 15095: 1;
1.191 harris41 15096: __END__
15097:
1.243 albertel 15098: =pod
15099:
1.191 harris41 15100: =head1 NAME
15101:
1.243 albertel 15102: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15103:
15104: =head1 SYNOPSIS
15105:
1.243 albertel 15106: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15107:
15108: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15109:
1.243 albertel 15110: Common parameters:
15111:
15112: =over 4
15113:
15114: =item *
15115:
15116: $uname : an internal username (if $cname expecting a course Id specifically)
15117:
15118: =item *
15119:
15120: $udom : a domain (if $cdom expecting a course's domain specifically)
15121:
15122: =item *
15123:
15124: $symb : a resource instance identifier
15125:
15126: =item *
15127:
15128: $namespace : the name of a .db file that contains the data needed or
15129: being set.
15130:
15131: =back
15132:
1.394 bowersj2 15133: =head1 OVERVIEW
1.191 harris41 15134:
1.394 bowersj2 15135: lonnet provides subroutines which interact with the
15136: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15137: about classes, users, and resources.
1.243 albertel 15138:
15139: For many of these objects you can also use this to store data about
15140: them or modify them in various ways.
1.191 harris41 15141:
1.394 bowersj2 15142: =head2 Symbs
1.191 harris41 15143:
1.394 bowersj2 15144: To identify a specific instance of a resource, LON-CAPA uses symbols
15145: or "symbs"X<symb>. These identifiers are built from the URL of the
15146: map, the resource number of the resource in the map, and the URL of
15147: the resource itself. The latter is somewhat redundant, but might help
15148: if maps change.
15149:
15150: An example is
15151:
15152: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15153:
15154: The respective map entry is
15155:
15156: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15157: title="Problem 2">
15158: </resource>
15159:
15160: Symbs are used by the random number generator, as well as to store and
15161: restore data specific to a certain instance of for example a problem.
15162:
15163: =head2 Storing And Retrieving Data
15164:
15165: X<store()>X<cstore()>X<restore()>Three of the most important functions
15166: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15167: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15168: is is the non-critical message twin of cstore. These functions are for
15169: handlers to store a perl hash to a user's permanent data space in an
15170: easy manner, and to retrieve it again on another call. It is expected
15171: that a handler would use this once at the beginning to retrieve data,
15172: and then again once at the end to send only the new data back.
15173:
15174: The data is stored in the user's data directory on the user's
15175: homeserver under the ID of the course.
15176:
15177: The hash that is returned by restore will have all of the previous
15178: value for all of the elements of the hash.
15179:
15180: Example:
15181:
15182: #creating a hash
15183: my %hash;
15184: $hash{'foo'}='bar';
15185:
15186: #storing it
15187: &Apache::lonnet::cstore(\%hash);
15188:
15189: #changing a value
15190: $hash{'foo'}='notbar';
15191:
15192: #adding a new value
15193: $hash{'bar'}='foo';
15194: &Apache::lonnet::cstore(\%hash);
15195:
15196: #retrieving the hash
15197: my %history=&Apache::lonnet::restore();
15198:
15199: #print the hash
15200: foreach my $key (sort(keys(%history))) {
15201: print("\%history{$key} = $history{$key}");
15202: }
15203:
15204: Will print out:
1.191 harris41 15205:
1.394 bowersj2 15206: %history{1:foo} = bar
15207: %history{1:keys} = foo:timestamp
15208: %history{1:timestamp} = 990455579
15209: %history{2:bar} = foo
15210: %history{2:foo} = notbar
15211: %history{2:keys} = foo:bar:timestamp
15212: %history{2:timestamp} = 990455580
15213: %history{bar} = foo
15214: %history{foo} = notbar
15215: %history{timestamp} = 990455580
15216: %history{version} = 2
15217:
15218: Note that the special hash entries C<keys>, C<version> and
15219: C<timestamp> were added to the hash. C<version> will be equal to the
15220: total number of versions of the data that have been stored. The
15221: C<timestamp> attribute will be the UNIX time the hash was
15222: stored. C<keys> is available in every historical section to list which
15223: keys were added or changed at a specific historical revision of a
15224: hash.
15225:
15226: B<Warning>: do not store the hash that restore returns directly. This
15227: will cause a mess since it will restore the historical keys as if the
15228: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15229:
1.394 bowersj2 15230: Calling convention:
1.191 harris41 15231:
1.1225 raeburn 15232: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15233: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15234:
1.394 bowersj2 15235: For more detailed information, see lonnet specific documentation.
1.191 harris41 15236:
1.394 bowersj2 15237: =head1 RETURN MESSAGES
1.191 harris41 15238:
1.394 bowersj2 15239: =over 4
1.191 harris41 15240:
1.394 bowersj2 15241: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15242:
1.394 bowersj2 15243: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15244: when the connection is brought back up
1.191 harris41 15245:
1.394 bowersj2 15246: =item * B<con_failed>: unable to contact remote host and unable to save message
15247: for later delivery
1.191 harris41 15248:
1.967 bisitz 15249: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15250:
1.394 bowersj2 15251: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15252: that was requested
1.191 harris41 15253:
1.243 albertel 15254: =back
1.191 harris41 15255:
1.243 albertel 15256: =head1 PUBLIC SUBROUTINES
1.191 harris41 15257:
1.243 albertel 15258: =head2 Session Environment Functions
1.191 harris41 15259:
1.243 albertel 15260: =over 4
1.191 harris41 15261:
1.394 bowersj2 15262: =item *
15263: X<appenv()>
1.949 raeburn 15264: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15265: the user envirnoment file, and will be restored for each access this
1.620 albertel 15266: user makes during this session, also modifies the %env for the current
1.949 raeburn 15267: process. Optional rolesarrayref - if defined contains a reference to an array
15268: of roles which are exempt from the restriction on modifying user.role entries
15269: in the user's environment.db and in %env.
1.191 harris41 15270:
15271: =item *
1.394 bowersj2 15272: X<delenv()>
1.987 raeburn 15273: B<delenv($delthis,$regexp)>: removes all items from the session
15274: environment file that begin with $delthis. If the
15275: optional second arg - $regexp - is true, $delthis is treated as a
15276: regular expression, otherwise \Q$delthis\E is used.
15277: The values are also deleted from the current processes %env.
1.191 harris41 15278:
1.795 albertel 15279: =item * get_env_multiple($name)
15280:
15281: gets $name from the %env hash, it seemlessly handles the cases where multiple
15282: values may be defined and end up as an array ref.
15283:
15284: returns an array of values
15285:
1.243 albertel 15286: =back
15287:
15288: =head2 User Information
1.191 harris41 15289:
1.243 albertel 15290: =over 4
1.191 harris41 15291:
15292: =item *
1.394 bowersj2 15293: X<queryauthenticate()>
15294: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15295: authentication scheme
15296:
15297: =item *
1.394 bowersj2 15298: X<authenticate()>
1.1073 raeburn 15299: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15300: authenticate user from domain's lib servers (first use the current
15301: one). C<$upass> should be the users password.
1.1073 raeburn 15302: $checkdefauth is optional (value is 1 if a check should be made to
15303: authenticate user using default authentication method, and allow
15304: account creation if username does not have account in the domain).
15305: $clientcancheckhost is optional (value is 1 if checking whether the
15306: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15307:
15308: =item *
1.394 bowersj2 15309: X<homeserver()>
15310: B<homeserver($uname,$udom)>: find the server which has
15311: the user's directory and files (there must be only one), this caches
15312: the answer, and also caches if there is a borken connection.
1.191 harris41 15313:
15314: =item *
1.394 bowersj2 15315: X<idget()>
1.1300 raeburn 15316: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15317: a list of student/employee IDs or clicker IDs
15318: (student/employee IDs are a unique resource in a domain, there must be
15319: only 1 ID per username, and only 1 username per ID in a specific domain).
15320: clickerIDs are not necessarily unique, as students might share clickers.
15321: (returns hash: id=>name,id=>name)
1.191 harris41 15322:
15323: =item *
1.394 bowersj2 15324: X<idrget()>
15325: B<idrget($udom,@unames)>: find the IDs behind a list of
15326: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15327:
15328: =item *
1.394 bowersj2 15329: X<idput()>
1.1300 raeburn 15330: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15331: names and associated student/employee IDs or clicker IDs.
15332:
15333: =item *
15334: X<iddel()>
15335: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15336: student/employee ID or clicker ID username look-ups from domain.
15337: The homeserver ($uhome) and namespace ($namespace) are optional.
15338: If no $uhome is provided, it will be determined usig &homeserver()
15339: for each user. If no $namespace is provided, the default is ids.
15340:
15341: =item *
15342: X<updateclickers()>
15343: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15344: clicker ID-to-username look-ups in clickers.db on library server.
15345: Permitted actions are add or del (i.e., add or delete). The
15346: clickers.db contains clickerID as keys (escaped), and each corresponding
15347: value is an escaped comma-separated list of usernames (for whom the
15348: library server is the homeserver), who registered that particular ID.
15349: If $critical is true, the update will be sent via &critical, otherwise
15350: &reply() will be used.
1.191 harris41 15351:
15352: =item *
1.394 bowersj2 15353: X<rolesinit()>
1.1169 droeschl 15354: B<rolesinit($udom,$username)>: get user privileges.
15355: returns user role, first access and timer interval hashes
1.243 albertel 15356:
15357: =item *
1.1171 droeschl 15358: X<privileged()>
15359: B<privileged($username,$domain)>: returns a true if user has a
15360: privileged and active role (i.e. su or dc), false otherwise.
15361:
15362: =item *
1.551 albertel 15363: X<getsection()>
15364: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15365: course $cname, return section name/number or '' for "not in course"
15366: and '-1' for "no section"
15367:
15368: =item *
1.394 bowersj2 15369: X<userenvironment()>
15370: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15371: passed in @what from the requested user's environment, returns a hash
15372:
1.858 raeburn 15373: =item *
15374: X<userlog_query()>
1.859 albertel 15375: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15376: activity.log file. %filters defines filters applied when parsing the
15377: log file. These can be start or end timestamps, or the type of action
15378: - log to look for Login or Logout events, check for Checkin or
15379: Checkout, role for role selection. The response is in the form
15380: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15381: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15382:
1.243 albertel 15383: =back
15384:
15385: =head2 User Roles
15386:
15387: =over 4
15388:
15389: =item *
15390:
1.1284 raeburn 15391: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15392: returns codes for allowed actions.
15393:
15394: The first argument is required, all others are optional.
15395:
15396: $priv is the privilege being checked.
15397: $uri contains additional information about what is being checked for access (e.g.,
15398: URL, course ID etc.).
15399: $symb is the unique resource instance identifier in a course; if needed,
15400: but not provided, it will be retrieved via a call to &symbread().
15401: $role is the role for which a priv is being checked (only used if priv is evb).
15402: $clientip is the user's IP address (only used when checking for access to portfolio
15403: files).
15404: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15405: prevents recursive calls to &allowed.
15406:
1.243 albertel 15407: F: full access
15408: U,I,K: authentication modes (cxx only)
15409: '': forbidden
15410: 1: user needs to choose course
15411: 2: browse allowed
1.766 albertel 15412: A: passphrase authentication needed
1.1284 raeburn 15413: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 15414: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15415:
15416: =item *
15417:
1.1192 raeburn 15418: constructaccess($url,$setpriv) : check for access to construction space URL
15419:
15420: See if the owner domain and name in the URL match those in the
15421: expected environment. If so, return three element list
15422: ($ownername,$ownerdomain,$ownerhome).
15423:
15424: Otherwise return the null string.
15425:
15426: If second argument 'setpriv' is true, it assigns the privileges,
15427: and returns the same three element list, unless the owner has
15428: blocked "ad hoc" Domain Coordinator access to the Author Space,
15429: in which case the null string is returned.
15430:
15431: =item *
15432:
1.1326 raeburn 15433: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15434: define a custom role rolename set privileges in format of lonTabs/roles.tab
15435: for system, domain, and course level. $uname and $udom are optional (current
15436: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15437:
15438: =item *
15439:
1.988 raeburn 15440: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15441: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15442: $type is Course (default) or Community.
1.988 raeburn 15443: If $forcedefault evaluates to true, text returned will be default
15444: text for $type. Otherwise, if this is a course, the text returned
15445: will be a custom name for the role (if defined in the course's
15446: environment). If no custom name is defined the default is returned.
15447:
1.832 raeburn 15448: =item *
15449:
1.1219 raeburn 15450: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15451: All arguments are optional. Returns a hash of a roles, either for
15452: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15453: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15454: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15455: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15456: For each key, value is set to colon-separated start and end times for
15457: the role. If no username and domain are specified, will default to
1.934 raeburn 15458: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15459: of role statuses (active, future or previous), roles
15460: (e.g., cc,in, st etc.) and domains of the roles which can be used
15461: to restrict the list of roles reported. If no array ref is
15462: provided for types, will default to return only active roles.
1.834 albertel 15463:
1.1195 raeburn 15464: =item *
15465:
15466: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 15467: user: $uname:$udom has a role in the course: $cdom_$cnum.
15468:
15469: Additional optional arguments are: $type (if role checking is to be restricted
15470: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 15471: available roles) or future (roles available in the future), and
15472: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 15473: have active Domain Coordinator role in course's domain or in additional
15474: domains (specified in 'Domains to check for privileged users' in course
15475: environment -- set via: Course Settings -> Classlists and staff listing).
15476:
15477: =item *
15478:
15479: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15480: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15481: $possdomains and $possroles are optional array refs -- to domains to check and
15482: roles to check. If $possdomains is not specified, a dump will be done of the
15483: users' roles.db to check for a dc or su role in any domain. This can be
15484: time consuming if &privileged is called repeatedly (e.g., when displaying a
15485: classlist), so in such cases, supplying a $possdomains array is preferred, as
15486: this then allows &privileged_by_domain() to be used, which caches the identity
15487: of privileged users, eliminating the need for repeated calls to &dump().
15488:
15489: =item *
15490:
15491: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15492: where the outer hash keys are domains specified in the $possdomains array ref,
15493: next inner hash keys are privileged roles specified in the $roles array ref,
15494: and the innermost hash contains key = value pairs for username:domain = end:start
15495: for active or future "privileged" users with that role in that domain. To avoid
15496: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15497: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 15498:
1.243 albertel 15499: =back
15500:
15501: =head2 User Modification
15502:
15503: =over 4
15504:
15505: =item *
15506:
1.957 raeburn 15507: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15508: user for the level given by URL. Optional start and end dates (leave empty
15509: string or zero for "no date")
1.191 harris41 15510:
15511: =item *
15512:
1.243 albertel 15513: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15514: change a users, password, possible return values are: ok,
15515: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15516: refused
1.191 harris41 15517:
15518: =item *
15519:
1.243 albertel 15520: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15521:
15522: =item *
15523:
1.1058 raeburn 15524: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15525: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15526:
15527: will update user information (firstname,middlename,lastname,generation,
15528: permanentemail), and if forceid is true, student/employee ID also.
15529: A user's institutional affiliation(s) can also be updated.
15530: User information fields will not be overwritten with empty entries
15531: unless the field is included in the $candelete array reference.
15532: This array is included when a single user is modified via "Manage Users",
15533: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15534:
15535: =item *
15536:
1.286 matthew 15537: modifystudent
15538:
1.957 raeburn 15539: modify a student's enrollment and identification information.
1.1235 raeburn 15540: The course id is resolved based on the current user's environment.
15541: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15542: associated with a course.
15543:
1.297 matthew 15544: This call is essentially a wrapper for lonnet::modifyuser and
15545: lonnet::modify_student_enrollment
1.286 matthew 15546:
15547: Inputs:
15548:
15549: =over 4
15550:
1.957 raeburn 15551: =item B<$udom> Student's loncapa domain
1.286 matthew 15552:
1.957 raeburn 15553: =item B<$uname> Student's loncapa login name
1.286 matthew 15554:
1.964 bisitz 15555: =item B<$uid> Student/Employee ID
1.286 matthew 15556:
1.957 raeburn 15557: =item B<$umode> Student's authentication mode
1.286 matthew 15558:
1.957 raeburn 15559: =item B<$upass> Student's password
1.286 matthew 15560:
1.957 raeburn 15561: =item B<$first> Student's first name
1.286 matthew 15562:
1.957 raeburn 15563: =item B<$middle> Student's middle name
1.286 matthew 15564:
1.957 raeburn 15565: =item B<$last> Student's last name
1.286 matthew 15566:
1.957 raeburn 15567: =item B<$gene> Student's generation
1.286 matthew 15568:
1.957 raeburn 15569: =item B<$usec> Student's section in course
1.286 matthew 15570:
15571: =item B<$end> Unix time of the roles expiration
15572:
15573: =item B<$start> Unix time of the roles start date
15574:
15575: =item B<$forceid> If defined, allow $uid to be changed
15576:
15577: =item B<$desiredhome> server to use as home server for student
15578:
1.957 raeburn 15579: =item B<$email> Student's permanent e-mail address
15580:
15581: =item B<$type> Type of enrollment (auto or manual)
15582:
1.963 raeburn 15583: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15584:
15585: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15586:
1.963 raeburn 15587: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15588:
1.963 raeburn 15589: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15590:
1.1216 raeburn 15591: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15592:
15593: =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 15594:
1.286 matthew 15595: =back
1.297 matthew 15596:
15597: =item *
15598:
15599: modify_student_enrollment
15600:
1.1235 raeburn 15601: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15602: 'role.request.course' must be defined for this function to proceed.
15603:
15604: Inputs:
15605:
15606: =over 4
15607:
1.1235 raeburn 15608: =item $udom, student's domain
1.297 matthew 15609:
1.1235 raeburn 15610: =item $uname, student's name
1.297 matthew 15611:
1.1235 raeburn 15612: =item $uid, student's user id
1.297 matthew 15613:
1.1235 raeburn 15614: =item $first, student's first name
1.297 matthew 15615:
15616: =item $middle
15617:
15618: =item $last
15619:
15620: =item $gene
15621:
15622: =item $usec
15623:
15624: =item $end
15625:
15626: =item $start
15627:
1.957 raeburn 15628: =item $type
15629:
15630: =item $locktype
15631:
15632: =item $cid
15633:
15634: =item $selfenroll
15635:
15636: =item $context
15637:
1.1216 raeburn 15638: =item $credits, number of credits student will earn from this class
15639:
1.1314 raeburn 15640: =item $instsec, institutional course section code for student
15641:
1.297 matthew 15642: =back
15643:
1.191 harris41 15644:
15645: =item *
15646:
1.243 albertel 15647: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15648: custom role; give a custom role to a user for the level given by URL. Specify
15649: name and domain of role author, and role name
1.191 harris41 15650:
15651: =item *
15652:
1.243 albertel 15653: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15654:
15655: =item *
15656:
1.243 albertel 15657: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15658:
15659: =back
15660:
15661: =head2 Course Infomation
15662:
15663: =over 4
1.191 harris41 15664:
15665: =item *
15666:
1.1118 foxr 15667: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15668: specified course id, including all environment settings for the
15669: course, the description of the course will be in the hash under the
15670: key 'description'
1.191 harris41 15671:
1.1118 foxr 15672: $options is an optional parameter that if supplied is a hash reference that controls
15673: what how this function works. It has the following key/values:
15674:
15675: =over 4
15676:
15677: =item freshen_cache
15678:
15679: If defined, and the environment cache for the course is valid, it is
15680: returned in the returned hash.
15681:
15682: =item one_time
15683:
15684: If defined, the last cache time is set to _now_
15685:
15686: =item user
15687:
15688: If defined, the supplied username is used instead of the current user.
15689:
15690:
15691: =back
15692:
1.191 harris41 15693: =item *
15694:
1.624 albertel 15695: resdata($name,$domain,$type,@which) : request for current parameter
15696: setting for a specific $type, where $type is either 'course' or 'user',
15697: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 15698: answers for 10 minutes.
1.243 albertel 15699:
1.877 foxr 15700: =item *
15701:
15702: get_courseresdata($courseid, $domain) : dump the entire course resource
15703: data base, returning a hash that is keyed by the resource name and has
15704: values that are the resource value. I believe that the timestamps and
15705: versions are also returned.
15706:
1.1236 raeburn 15707: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15708: supplemental content area. This routine caches the number of files for
15709: 10 minutes.
15710:
1.243 albertel 15711: =back
15712:
15713: =head2 Course Modification
15714:
15715: =over 4
1.191 harris41 15716:
15717: =item *
15718:
1.243 albertel 15719: writecoursepref($courseid,%prefs) : write preferences (environment
15720: database) for a course
1.191 harris41 15721:
15722: =item *
15723:
1.1011 raeburn 15724: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15725:
15726: =item *
15727:
1.1038 raeburn 15728: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15729:
1.1167 droeschl 15730: =item *
15731:
15732: is_course($courseid), is_course($cdom, $cnum)
15733:
15734: Accepts either a combined $courseid (in the form of domain_courseid) or the
15735: two component version $cdom, $cnum. It checks if the specified course exists.
15736:
15737: Returns:
15738: undef if the course doesn't exist, otherwise
15739: in scalar context the combined courseid.
15740: in list context the two components of the course identifier, domain and
15741: courseid.
15742:
1.243 albertel 15743: =back
15744:
1.1401 raeburn 15745: =head2 Bubblesheet Configuration
15746:
15747: =over 4
15748:
15749: =item *
15750:
15751: get_scantron_config($which)
15752:
15753: $which - the name of the configuration to parse from the file.
15754:
15755: Parses and returns the bubblesheet configuration line selected as a
15756: hash of configuration file fields.
15757:
15758:
15759: Returns:
15760: If the named configuration is not in the file, an empty
15761: hash is returned.
15762:
15763: a hash with the fields
15764: name - internal name for the this configuration setup
15765: description - text to display to operator that describes this config
15766: CODElocation - if 0 or the string 'none'
15767: - no CODE exists for this config
15768: if -1 || the string 'letter'
15769: - a CODE exists for this config and is
15770: a string of letters
15771: Unsupported value (but planned for future support)
15772: if a positive integer
15773: - The CODE exists as the first n items from
15774: the question section of the form
15775: if the string 'number'
15776: - The CODE exists for this config and is
15777: a string of numbers
15778: CODEstart - (only matter if a CODE exists) column in the line where
15779: the CODE starts
15780: CODElength - length of the CODE
15781: IDstart - column where the student/employee ID starts
15782: IDlength - length of the student/employee ID info
15783: Qstart - column where the information from the bubbled
15784: 'questions' start
15785: Qlength - number of columns comprising a single bubble line from
15786: the sheet. (usually either 1 or 10)
15787: Qon - either a single character representing the character used
15788: to signal a bubble was chosen in the positional setup, or
15789: the string 'letter' if the letter of the chosen bubble is
15790: in the final, or 'number' if a number representing the
15791: chosen bubble is in the file (1->A 0->J)
15792: Qoff - the character used to represent that a bubble was
15793: left blank
15794: PaperID - if the scanning process generates a unique number for each
15795: sheet scanned the column that this ID number starts in
15796: PaperIDlength - number of columns that comprise the unique ID number
15797: for the sheet of paper
15798: FirstName - column that the first name starts in
15799: FirstNameLength - number of columns that the first name spans
15800: LastName - column that the last name starts in
15801: LastNameLength - number of columns that the last name spans
15802: BubblesPerRow - number of bubbles available in each row used to
15803: bubble an answer. (If not specified, 10 assumed).
15804:
15805:
15806: =item *
15807:
15808: get_scantronformat_file($cdom)
15809:
15810: $cdom - the course's domain (optional); if not supplied, uses
15811: domain for current $env{'request.course.id'}.
15812:
15813: Returns an array containing lines from the scantron format file for
15814: the domain of the course.
15815:
15816: If a url for a custom.tab file is listed in domain's configuration.db,
15817: lines are from this file.
15818:
15819: Otherwise, if a default.tab has been published in RES space by the
15820: domainconfig user, lines are from this file.
15821:
15822: Otherwise, fall back to getting lines from the legacy file on the
15823: local server: /home/httpd/lonTabs/default_scantronformat.tab
15824:
15825: =back
15826:
1.243 albertel 15827: =head2 Resource Subroutines
15828:
15829: =over 4
1.191 harris41 15830:
15831: =item *
15832:
1.243 albertel 15833: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15834:
15835: =item *
15836:
1.243 albertel 15837: repcopy($filename) : subscribes to the requested file, and attempts to
15838: replicate from the owning library server, Might return
1.607 raeburn 15839: 'unavailable', 'not_found', 'forbidden', 'ok', or
15840: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15841: resource. Expects the local filesystem pathname
15842: (/home/httpd/html/res/....)
15843:
15844: =back
15845:
15846: =head2 Resource Information
15847:
15848: =over 4
1.191 harris41 15849:
15850: =item *
15851:
1.1228 raeburn 15852: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15853: and returns the value of a variety of different possible values,
15854: $varname should be a request string, and the other parameters can be
15855: used to specify who and what one is asking about. Ordinarily, $cid
15856: does not need to be specified, as it is retrived from
15857: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15858: within lonuserstate::loadmap() when initializing a course, before
15859: $env{'request.course.id'} has been set, so it needs to be provided
15860: in that one case.
1.243 albertel 15861:
15862: Possible values for $varname are environment.lastname (or other item
15863: from the envirnment hash), user.name (or someother aspect about the
15864: user), resource.0.maxtries (or some other part and parameter of a
15865: resource)
1.204 albertel 15866:
15867: =item *
15868:
1.243 albertel 15869: directcondval($number) : get current value of a condition; reads from a state
15870: string
1.204 albertel 15871:
15872: =item *
15873:
1.243 albertel 15874: condval($condidx) : value of condition index based on state
1.204 albertel 15875:
15876: =item *
15877:
1.1362 raeburn 15878: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 15879: resource's metadata, $what should be either a specific key, or either
15880: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 15881: packages that this resource currently uses, the last 3 arguments are
15882: only used internally for recursive metadata.
15883:
15884: the toolsymb is only used where the uri is for an external tool (for which
15885: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 15886:
1.1371 raeburn 15887: this function automatically caches all requests except any made recursively
15888: to retrieve a list of metadata keys for an imported library file ($liburi is
15889: defined).
1.191 harris41 15890:
15891: =item *
15892:
1.243 albertel 15893: metadata_query($query,$custom,$customshow) : make a metadata query against the
15894: network of library servers; returns file handle of where SQL and regex results
15895: will be stored for query
1.191 harris41 15896:
15897: =item *
15898:
1.1282 raeburn 15899: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15900: return symbolic list entry (all arguments optional).
15901:
15902: Args: filename is the filename (including path) for the file for which a symb
15903: is required; donotrecurse, if true will prevent calls to allowed() being made
15904: to check access status if more than one resource was found in the bighash
15905: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15906: a randompick); ignorecachednull, if true will prevent a symb of '' being
15907: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15908: cause possible symbs to be checked to determine if they are subject to content
15909: blocking, if so they will not be included as possible symbs; possibles is a
15910: ref to a hash, which, as a side effect, will be populated with all possible
15911: symbs (content blocking not tested).
15912:
1.243 albertel 15913: returns the data handle
1.191 harris41 15914:
15915: =item *
15916:
1.1190 raeburn 15917: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15918: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15919: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 15920: on failure, user must be in a course, as it assumes the existence of
15921: the course initial hash, and uses $env('request.course.id'}. The third
15922: arg is an optional reference to a scalar. If this arg is passed in the
15923: call to symbverify, it will be set to 1 if the symb has been set to be
15924: encrypted; otherwise it will be null.
1.191 harris41 15925:
15926: =item *
15927:
1.243 albertel 15928: symbclean($symb) : removes versions numbers from a symb, returns the
15929: cleaned symb
1.191 harris41 15930:
15931: =item *
15932:
1.243 albertel 15933: is_on_map($uri) : checks if the $uri is somewhere on the current
15934: course map, user must be in a course for it to work.
1.191 harris41 15935:
15936: =item *
15937:
1.243 albertel 15938: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15939:
15940: =item *
15941:
1.243 albertel 15942: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15943: a random seed, all arguments are optional, if they aren't sent it uses the
15944: environment to derive them. Note: if symb isn't sent and it can't get one
15945: from &symbread it will use the current time as its return value
1.191 harris41 15946:
15947: =item *
15948:
1.243 albertel 15949: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15950: unfakeable, receipt
1.191 harris41 15951:
15952: =item *
15953:
1.620 albertel 15954: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15955:
15956: =item *
15957:
1.243 albertel 15958: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15959:
15960: =item *
15961:
1.243 albertel 15962: 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 15963:
15964: =item *
15965:
1.243 albertel 15966: 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 15967:
15968: =item *
15969:
1.243 albertel 15970: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15971:
15972: =item *
15973:
1.243 albertel 15974: devalidate($symb) : devalidate temporary spreadsheet calculations,
15975: forcing spreadsheet to reevaluate the resource scores next time.
15976:
1.1195 raeburn 15977: =item *
15978:
1.1196 raeburn 15979: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15980: when viewing in course context.
1.1195 raeburn 15981:
1.1196 raeburn 15982: input: six args -- filename (decluttered), course number, course domain,
15983: url, symb (if registered) and group (if this is a
15984: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 15985:
1.1196 raeburn 15986: output: array of five scalars --
1.1195 raeburn 15987: $cfile -- url for file editing if editable on current server
15988: $home -- homeserver of resource (i.e., for author if published,
15989: or course if uploaded.).
15990: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 15991: $forceedit -- 1 if icon/link should be to go to edit mode
15992: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 15993:
15994: =item *
15995:
15996: is_course_upload($file,$cnum,$cdom)
15997:
15998: Used in course context to determine if current file was uploaded to
15999: the course (i.e., would be found in /userfiles/docs on the course's
16000: homeserver.
16001:
16002: input: 3 args -- filename (decluttered), course number and course domain.
16003: output: boolean -- 1 if file was uploaded.
16004:
1.243 albertel 16005: =back
16006:
16007: =head2 Storing/Retreiving Data
16008:
16009: =over 4
1.191 harris41 16010:
16011: =item *
16012:
1.1269 raeburn 16013: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16014: permanently for this url; hashref needs to be given and should be a \%hashname;
16015: the remaining args aren't required and if they aren't passed or are '' they will
16016: be derived from the env (with the exception of $laststore, which is an
16017: optional arg used when a user's submission is stored in grading).
16018: $laststore is $version=$timestamp, where $version is the most recent version
16019: number retrieved for the corresponding $symb in the $namespace db file, and
16020: $timestamp is the timestamp for that transaction (UNIX time).
16021: $laststore is currently only passed when cstore() is called by
16022: structuretags::finalize_storage().
1.191 harris41 16023:
16024: =item *
16025:
1.1269 raeburn 16026: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16027: but uses critical subroutine
1.191 harris41 16028:
16029: =item *
16030:
1.243 albertel 16031: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16032: all args are optional
1.191 harris41 16033:
16034: =item *
16035:
1.717 albertel 16036: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16037: dumps the complete (or key matching regexp) namespace into a hash
16038: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16039: normally &store()ed into
16040:
16041: $range should be either an integer '100' (give me the first 100
16042: matching records)
16043: or be two integers sperated by a - with no spaces
16044: '30-50' (give me the 30th through the 50th matching
16045: records)
16046:
16047:
16048: =item *
16049:
1.1269 raeburn 16050: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16051: replaces a &store() version of data with a replacement set of data
16052: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16053: reference. If $tolog is true, the transaction is logged in the courselog
16054: with an action=PUTSTORE.
1.717 albertel 16055:
16056: =item *
16057:
1.243 albertel 16058: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16059: works very similar to store/cstore, but all data is stored in a
16060: temporary location and can be reset using tmpreset, $storehash should
16061: be a hash reference, returns nothing on success
1.191 harris41 16062:
16063: =item *
16064:
1.243 albertel 16065: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16066: similar to restore, but all data is stored in a temporary location and
16067: can be reset using tmpreset. Returns a hash of values on success,
16068: error string otherwise.
1.191 harris41 16069:
16070: =item *
16071:
1.243 albertel 16072: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16073: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16074:
16075: =item *
16076:
1.243 albertel 16077: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16078: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16079:
16080: =item *
16081:
1.243 albertel 16082: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16083: namesp ($udom and $uname are optional)
1.191 harris41 16084:
16085: =item *
16086:
1.702 albertel 16087: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16088: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16089: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16090:
1.702 albertel 16091: $range should be either an integer '100' (give me the first 100
16092: matching records)
16093: or be two integers sperated by a - with no spaces
16094: '30-50' (give me the 30th through the 50th matching
16095: records)
1.449 matthew 16096: =item *
16097:
16098: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16099: $store can be a scalar, an array reference, or if the amount to be
16100: incremented is > 1, a hash reference.
16101:
16102: ($udom and $uname are optional)
1.191 harris41 16103:
16104: =item *
16105:
1.243 albertel 16106: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16107: ($udom and $uname are optional)
1.191 harris41 16108:
16109: =item *
16110:
1.243 albertel 16111: cput($namespace,$storehash,$udom,$uname) : critical put
16112: ($udom and $uname are optional)
1.191 harris41 16113:
16114: =item *
16115:
1.748 albertel 16116: newput($namespace,$storehash,$udom,$uname) :
16117:
16118: Attempts to store the items in the $storehash, but only if they don't
16119: currently exist, if this succeeds you can be certain that you have
16120: successfully created a new key value pair in the $namespace db.
16121:
16122:
16123: Args:
16124: $namespace: name of database to store values to
16125: $storehash: hashref to store to the db
16126: $udom: (optional) domain of user containing the db
16127: $uname: (optional) name of user caontaining the db
16128:
16129: Returns:
16130: 'ok' -> succeeded in storing all keys of $storehash
16131: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16132: least <key> already existed in the db (other
16133: requested keys may also already exist)
1.967 bisitz 16134: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16135: 'con_lost' -> unable to contact request server
16136: 'refused' -> action was not allowed by remote machine
16137:
16138:
16139: =item *
16140:
1.243 albertel 16141: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16142: reference filled in from namesp (encrypts the return communication)
16143: ($udom and $uname are optional)
1.191 harris41 16144:
16145: =item *
16146:
1.243 albertel 16147: log($udom,$name,$home,$message) : write to permanent log for user; use
16148: critical subroutine
16149:
1.806 raeburn 16150: =item *
16151:
1.860 raeburn 16152: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16153: array reference filled in from namespace found in domain level on either
16154: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16155:
16156: =item *
16157:
1.860 raeburn 16158: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16159: domain level either on specified domain server ($uhome) or primary domain
16160: server ($udom and $uhome are optional)
1.806 raeburn 16161:
1.943 raeburn 16162: =item *
16163:
1.1240 raeburn 16164: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16165: for: authentication, language, quotas, timezone, date locale, and portal URL in
16166: the target domain.
16167:
16168: May also include additional key => value pairs for the following groups:
16169:
16170: =over
16171:
16172: =item
16173: disk quotas (MB allocated by default to portfolios and authoring spaces).
16174:
16175: =over
16176:
16177: =item defaultquota, authorquota
16178:
16179: =back
16180:
16181: =item
16182: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16183: portfolio for users).
16184:
16185: =over
16186:
16187: =item
16188: aboutme, blog, webdav, portfolio
16189:
16190: =back
16191:
16192: =item
16193: requestcourses: ability to request courses, and how requests are processed.
16194:
16195: =over
16196:
16197: =item
1.1305 raeburn 16198: official, unofficial, community, textbook, placement
1.1240 raeburn 16199:
16200: =back
16201:
16202: =item
16203: inststatus: types of institutional affiliation, and order in which they are displayed.
16204:
16205: =over
16206:
16207: =item
1.1256 raeburn 16208: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 16209:
16210: =back
16211:
16212: =item
16213: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16214: for course's uploaded content.
16215:
16216: =over
16217:
16218: =item
1.1246 raeburn 16219: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16220: communityquota, textbookquota, placementquota
1.1240 raeburn 16221:
16222: =back
16223:
16224: =item
16225: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16226: on your servers.
16227:
16228: =over
16229:
16230: =item
16231: remotesessions, hostedsessions
16232:
16233: =back
16234:
16235: =back
16236:
16237: In cases where a domain coordinator has never used the "Set Domain Configuration"
16238: utility to create a configuration.db file on a domain's primary library server
16239: only the following domain defaults: auth_def, auth_arg_def, lang_def
16240: -- corresponding values are authentication type (internal, krb4, krb5,
16241: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16242: will be available. Values are retrieved from cache (if current), unless the
16243: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16244: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16245:
16246: Typical usage:
1.943 raeburn 16247:
1.1240 raeburn 16248: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16249:
1.243 albertel 16250: =back
16251:
16252: =head2 Network Status Functions
16253:
16254: =over 4
1.191 harris41 16255:
16256: =item *
16257:
1.1137 raeburn 16258: dirlist() : return directory list based on URI (first arg).
16259:
16260: Inputs: 1 required, 5 optional.
16261:
16262: =over
16263:
16264: =item
16265: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16266:
16267: =item
16268: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16269:
16270: =item
16271: $username - username of user/course to be listed. Extracted from $uri if absent.
16272:
16273: =item
16274: $getpropath - boolean: 1 if prepend path using &propath().
16275:
16276: =item
16277: $getuserdir - boolean: 1 if prepend path for "userfiles".
16278:
16279: =item
16280: $alternateRoot - path to prepend in place of path from $uri.
16281:
16282: =back
16283:
16284: Returns: Array of up to two items.
16285:
16286: =over
16287:
16288: a reference to an array of files/subdirectories
16289:
16290: =over
16291:
16292: Each element in the array of files/subdirectories is a & separated list of
16293: item name and the result of running stat on the item. If dirlist was requested
16294: for a file instead of a directory, the item name will be ''. For a directory
16295: listing, if the item is a metadata file, the element will end &N&M
16296: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16297: default copyright set (1).
16298:
16299: =back
16300:
16301: a scalar containing error condition (if encountered).
16302:
16303: =over
16304:
16305: =item
16306: no_host (no homeserver identified for $username:$domain).
16307:
16308: =item
16309: no_such_host (server contacted for listing not identified as valid host).
16310:
16311: =item
16312: con_lost (connection to remote server failed).
16313:
16314: =item
16315: refused (invalid $username:$domain received on lond side).
16316:
16317: =item
16318: no_such_dir (directory at specified path on lond side does not exist).
16319:
16320: =item
16321: empty (directory at specified path on lond side is empty).
16322:
16323: =over
16324:
16325: This is currently not encountered because the &ls3, &ls2,
16326: &ls (_handler) routines on the lond side do not filter out
16327: . and .. from a directory listing.
16328:
16329: =back
16330:
16331: =back
16332:
16333: =back
1.191 harris41 16334:
16335: =item *
16336:
1.243 albertel 16337: spareserver() : find server with least workload from spare.tab
16338:
1.986 foxr 16339:
16340: =item *
16341:
16342: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16343: if there is no corresponding loncapa host.
16344:
1.243 albertel 16345: =back
16346:
1.986 foxr 16347:
1.243 albertel 16348: =head2 Apache Request
16349:
16350: =over 4
1.191 harris41 16351:
16352: =item *
16353:
1.243 albertel 16354: ssi($url,%hash) : server side include, does a complete request cycle on url to
16355: localhost, posts hash
16356:
16357: =back
16358:
16359: =head2 Data to String to Data
16360:
16361: =over 4
1.191 harris41 16362:
16363: =item *
16364:
1.243 albertel 16365: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16366: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16367:
16368: =item *
16369:
1.243 albertel 16370: hashref2str($hashref) : convert a hashref into a string complete with
16371: escaping and '=' and '&' separators, supports elements that are
16372: arrayrefs and hashrefs
1.191 harris41 16373:
16374: =item *
16375:
1.243 albertel 16376: arrayref2str($arrayref) : convert an arrayref into a string complete
16377: with escaping and '&' separators, supports elements that are arrayrefs
16378: and hashrefs
1.191 harris41 16379:
16380: =item *
16381:
1.243 albertel 16382: str2hash($string) : convert string to hash using unescaping and
16383: splitting on '=' and '&', supports elements that are arrayrefs and
16384: hashrefs
1.191 harris41 16385:
16386: =item *
16387:
1.243 albertel 16388: str2array($string) : convert string to hash using unescaping and
16389: splitting on '&', supports elements that are arrayrefs and hashrefs
16390:
16391: =back
16392:
16393: =head2 Logging Routines
16394:
16395:
16396: These routines allow one to make log messages in the lonnet.log and
16397: lonnet.perm logfiles.
1.191 harris41 16398:
1.1119 foxr 16399: =over 4
16400:
1.191 harris41 16401: =item *
16402:
1.243 albertel 16403: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16404:
16405: =item *
16406:
1.243 albertel 16407: logthis() : append message to the normal lonnet.log file, it gets
16408: preiodically rolled over and deleted.
1.191 harris41 16409:
16410: =item *
16411:
1.243 albertel 16412: logperm() : append a permanent message to lonnet.perm.log, this log
16413: file never gets deleted by any automated portion of the system, only
16414: messages of critical importance should go in here.
16415:
1.1119 foxr 16416:
1.243 albertel 16417: =back
16418:
16419: =head2 General File Helper Routines
16420:
16421: =over 4
1.191 harris41 16422:
16423: =item *
16424:
1.481 raeburn 16425: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16426: (a) files in /uploaded
16427: (i) If a local copy of the file exists -
16428: compares modification date of local copy with last-modified date for
16429: definitive version stored on home server for course. If local copy is
16430: stale, requests a new version from the home server and stores it.
16431: If the original has been removed from the home server, then local copy
16432: is unlinked.
16433: (ii) If local copy does not exist -
16434: requests the file from the home server and stores it.
16435:
16436: If $caller is 'uploadrep':
16437: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16438: for request for files originally uploaded via DOCS.
16439: - returns 'ok' if fresh local copy now available, -1 otherwise.
16440:
16441: Otherwise:
16442: This indicates a call from the content generation phase of the request.
16443: - returns the entire contents of the file or -1.
16444:
16445: (b) files in /res
16446: - returns the entire contents of a file or -1;
16447: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16448:
1.712 albertel 16449:
16450: =item *
16451:
16452: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16453: reference
16454:
16455: returns either a stat() list of data about the file or an empty list
16456: if the file doesn't exist or couldn't find out about it (connection
16457: problems or user unknown)
16458:
1.191 harris41 16459: =item *
16460:
1.243 albertel 16461: filelocation($dir,$file) : returns file system location of a file
16462: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16463: directory that relative $file lookups are to looked in ($dir of /a/dir
16464: and a file of ../bob will become /a/bob)
1.191 harris41 16465:
16466: =item *
16467:
16468: hreflocation($dir,$file) : returns file system location or a URL; same as
16469: filelocation except for hrefs
16470:
16471: =item *
16472:
1.1261 raeburn 16473: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16474: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16475:
1.243 albertel 16476: =back
16477:
1.608 albertel 16478: =head2 Usererfile file routines (/uploaded*)
16479:
16480: =over 4
16481:
16482: =item *
16483:
16484: userfileupload(): main rotine for putting a file in a user or course's
16485: filespace, arguments are,
16486:
1.620 albertel 16487: formname - required - this is the name of the element in $env where the
1.608 albertel 16488: filename, and the contents of the file to create/modifed exist
1.620 albertel 16489: the filename is in $env{'form.'.$formname.'.filename'} and the
16490: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16491: context - if coursedoc, store the file in the course of the active role
16492: of the current user;
16493: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16494: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16495: subdir - required - subdirectory to put the file in under ../userfiles/
16496: if undefined, it will be placed in "unknown"
16497:
16498: (This routine calls clean_filename() to remove any dangerous
16499: characters from the filename, and then calls finuserfileupload() to
16500: complete the transaction)
16501:
16502: returns either the url of the uploaded file (/uploaded/....) if successful
16503: and /adm/notfound.html if unsuccessful
16504:
16505: =item *
16506:
16507: clean_filename(): routine for cleaing a filename up for storage in
16508: userfile space, argument is:
16509:
16510: filename - proposed filename
16511:
16512: returns: the new clean filename
16513:
16514: =item *
16515:
1.1090 raeburn 16516: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16517: userspace, probably shouldn't be called directly
16518:
16519: docuname: username or courseid of destination for the file
16520: docudom: domain of user/course of destination for the file
16521: formname: same as for userfileupload()
1.1090 raeburn 16522: fname: filename (including subdirectories) for the file
16523: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 16524: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16525: allfiles: reference to hash used to store objects found by parser
16526: codebase: reference to hash used for codebases of java objects found by parser
16527: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16528: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16529: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16530: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16531: context: if 'overwrite', will move the uploaded file from its temporary location to
16532: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16533: mimetype: reference to scalar to accommodate mime type determined
16534: from File::MMagic if $parser = parse.
1.608 albertel 16535:
16536: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16537: and /adm/notfound.html if unsuccessful (or an error message if context
16538: was 'overwrite').
16539:
1.608 albertel 16540:
16541: =item *
16542:
16543: renameuserfile(): renames an existing userfile to a new name
16544:
16545: Args:
16546: docuname: username or courseid of destination for the file
16547: docudom: domain of user/course of destination for the file
16548: old: current file name (including any subdirs under userfiles)
16549: new: desired file name (including any subdirs under userfiles)
16550:
16551: =item *
16552:
16553: mkdiruserfile(): creates a directory is a userfiles dir
16554:
16555: Args:
16556: docuname: username or courseid of destination for the file
16557: docudom: domain of user/course of destination for the file
16558: dir: dir to create (including any subdirs under userfiles)
16559:
16560: =item *
16561:
16562: removeuserfile(): removes a file that exists in userfiles
16563:
16564: Args:
16565: docuname: username or courseid of destination for the file
16566: docudom: domain of user/course of destination for the file
16567: fname: filname to delete (including any subdirs under userfiles)
16568:
16569: =item *
16570:
16571: removeuploadedurl(): convience function for removeuserfile()
16572:
16573: Args:
16574: url: a full /uploaded/... url to delete
16575:
1.747 albertel 16576: =item *
16577:
16578: get_portfile_permissions():
16579: Args:
16580: domain: domain of user or course contain the portfolio files
16581: user: name of user or num of course contain the portfolio files
16582: Returns:
16583: hashref of a dump of the proper file_permissions.db
16584:
16585:
16586: =item *
16587:
16588: get_access_controls():
16589:
16590: Args:
16591: current_permissions: the hash ref returned from get_portfile_permissions()
16592: group: (optional) the group you want the files associated with
16593: file: (optional) the file you want access info on
16594:
16595: Returns:
1.749 raeburn 16596: a hash (keys are file names) of hashes containing
16597: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16598: values are XML containing access control settings (see below)
1.747 albertel 16599:
16600: Internal notes:
16601:
1.749 raeburn 16602: access controls are stored in file_permissions.db as key=value pairs.
16603: key -> path to file/file_name\0uniqueID:scope_end_start
16604: where scope -> public,guest,course,group,domains or users.
16605: end -> UNIX time for end of access (0 -> no end date)
16606: start -> UNIX time for start of access
16607:
16608: value -> XML description of access control
16609: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16610: <start></start>
16611: <end></end>
16612:
16613: <password></password> for scope type = guest
16614:
16615: <domain></domain> for scope type = course or group
16616: <number></number>
16617: <roles id="">
16618: <role></role>
16619: <access></access>
16620: <section></section>
16621: <group></group>
16622: </roles>
16623:
16624: <dom></dom> for scope type = domains
16625:
16626: <users> for scope type = users
16627: <user>
16628: <uname></uname>
16629: <udom></udom>
16630: </user>
16631: </users>
16632: </scope>
16633:
16634: Access data is also aggregated for each file in an additional key=value pair:
16635: key -> path to file/file_name\0accesscontrol
16636: value -> reference to hash
16637: hash contains key = value pairs
16638: where key = uniqueID:scope_end_start
16639: value = UNIX time record was last updated
16640:
16641: Used to improve speed of look-ups of access controls for each file.
16642:
16643: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16644:
1.1198 raeburn 16645: =item *
16646:
1.749 raeburn 16647: modify_access_controls():
16648:
16649: Modifies access controls for a portfolio file
16650: Args
16651: 1. file name
16652: 2. reference to hash of required changes,
16653: 3. domain
16654: 4. username
16655: where domain,username are the domain of the portfolio owner
16656: (either a user or a course)
16657:
16658: Returns:
16659: 1. result of additions or updates ('ok' or 'error', with error message).
16660: 2. result of deletions ('ok' or 'error', with error message).
16661: 3. reference to hash of any new or updated access controls.
16662: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16663: key = integer (inbound ID)
1.1198 raeburn 16664: value = uniqueID
16665:
16666: =item *
16667:
16668: get_timebased_id():
16669:
16670: Attempts to get a unique timestamp-based suffix for use with items added to a
16671: course via the Course Editor (e.g., folders, composite pages,
16672: group bulletin boards).
16673:
16674: Args: (first three required; six others optional)
16675:
16676: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16677: docssequence, or name of group
16678:
16679: 2. keyid (alphanumeric): name of temporary locking key in hash,
16680: e.g., num, boardids
16681:
16682: 3. namespace: name of gdbm file used to store suffixes already assigned;
16683: file will be named nohist_namespace.db
16684:
16685: 4. cdom: domain of course; default is current course domain from %env
16686:
16687: 5. cnum: course number; default is current course number from %env
16688:
16689: 6. idtype: set to concat if an additional digit is to be appended to the
16690: unix timestamp to form the suffix, if the plain timestamp is already
16691: in use. Default is to not do this, but simply increment the unix
16692: timestamp by 1 until a unique key is obtained.
16693:
16694: 7. who: holder of locking key; defaults to user:domain for user.
16695:
16696: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16697: retrying); default is 3.
16698:
16699: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16700:
16701: Returns:
16702:
16703: 1. suffix obtained (numeric)
16704:
16705: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16706:
16707: 3. error: contains (localized) error message if an error occurred.
16708:
1.747 albertel 16709:
1.608 albertel 16710: =back
16711:
1.243 albertel 16712: =head2 HTTP Helper Routines
16713:
16714: =over 4
16715:
1.191 harris41 16716: =item *
16717:
16718: escape() : unpack non-word characters into CGI-compatible hex codes
16719:
16720: =item *
16721:
16722: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16723:
1.243 albertel 16724: =back
16725:
16726: =head1 PRIVATE SUBROUTINES
16727:
16728: =head2 Underlying communication routines (Shouldn't call)
16729:
16730: =over 4
16731:
16732: =item *
16733:
16734: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16735:
16736: =item *
16737:
16738: reply() : uses subreply to send a message to remote machine, logs all failures
16739:
16740: =item *
16741:
16742: critical() : passes a critical message to another server; if cannot
16743: get through then place message in connection buffer directory and
16744: returns con_delayed, if incapable of saving message, returns
16745: con_failed
16746:
16747: =item *
16748:
16749: reconlonc() : tries to reconnect lonc client processes.
16750:
16751: =back
16752:
16753: =head2 Resource Access Logging
16754:
16755: =over 4
16756:
16757: =item *
16758:
16759: flushcourselogs() : flush (save) buffer logs and access logs
16760:
16761: =item *
16762:
16763: courselog($what) : save message for course in hash
16764:
16765: =item *
16766:
16767: courseacclog($what) : save message for course using &courselog(). Perform
16768: special processing for specific resource types (problems, exams, quizzes, etc).
16769:
1.191 harris41 16770: =item *
16771:
16772: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16773: as a PerlChildExitHandler
1.243 albertel 16774:
16775: =back
16776:
16777: =head2 Other
16778:
16779: =over 4
16780:
16781: =item *
16782:
16783: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16784:
16785: =back
16786:
16787: =cut
1.877 foxr 16788:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>