Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1289
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1289 ! damieng 4: # $Id: lonnet.pm,v 1.1288 2015/06/12 21:11:20 damieng 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.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.1289 ! damieng 95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.1288 damieng 108: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 ! damieng 378: sleep(0.1);
1.549 foxr 379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.1289 ! damieng 396: sleep(0.1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
1.1288 damieng 489: sleep 1;
1.1 albertel 490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 852: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
853: $try_server));
1.1123 raeburn 854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
1.1083 raeburn 857: }
1.784 albertel 858:
1.1123 raeburn 859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 864: next unless (&spare_can_host($udom,$uint_dom,
865: $remotesessions,$try_server));
1.1123 raeburn 866: ($spare_server, $lowest_load) =
867: &compare_server_load($try_server, $spare_server, $lowest_load);
868: }
869: }
870: }
1.784 albertel 871: }
872:
873: if (!$want_server_name) {
1.968 raeburn 874: my $protocol = 'http';
875: if ($protocol{$spare_server} eq 'https') {
876: $protocol = $protocol{$spare_server};
877: }
1.1001 raeburn 878: if (defined($spare_server)) {
879: my $hostname = &hostname($spare_server);
1.1083 raeburn 880: if (defined($hostname)) {
1.1001 raeburn 881: $spare_server = $protocol.'://'.$hostname;
882: }
883: }
1.784 albertel 884: }
885: return $spare_server;
886: }
887:
888: sub compare_server_load {
1.1253 raeburn 889: my ($try_server, $spare_server, $lowest_load, $required) = @_;
890:
891: if ($required) {
892: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
893: my $remoterev = &get_server_loncaparev(undef,$try_server);
894: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
895: if (($major eq '' && $minor eq '') ||
896: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
897: return ($spare_server,$lowest_load);
898: }
899: }
1.784 albertel 900:
901: my $loadans = &reply('load', $try_server);
902: my $userloadans = &reply('userload',$try_server);
903:
904: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 905: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 906: }
907:
908: my $load;
909: if ($loadans =~ /\d/) {
910: if ($userloadans =~ /\d/) {
911: #both are numbers, pick the bigger one
912: $load = ($loadans > $userloadans) ? $loadans
913: : $userloadans;
1.411 albertel 914: } else {
1.784 albertel 915: $load = $loadans;
1.411 albertel 916: }
1.784 albertel 917: } else {
918: $load = $userloadans;
919: }
920:
921: if (($load =~ /\d/) && ($load < $lowest_load)) {
922: $spare_server = $try_server;
923: $lowest_load = $load;
1.370 albertel 924: }
1.784 albertel 925: return ($spare_server,$lowest_load);
1.202 matthew 926: }
1.914 albertel 927:
928: # --------------------------- ask offload servers if user already has a session
929: sub find_existing_session {
930: my ($udom,$uname) = @_;
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
938: if (ref($spareshash->{'default'}) eq 'ARRAY') {
939: foreach my $try_server (@{ $spareshash->{'default'} }) {
940: return $try_server if (&has_user_session($try_server, $udom, $uname));
941: }
942: }
1.914 albertel 943: }
944: return;
945: }
946:
947: # -------------------------------- ask if server already has a session for user
948: sub has_user_session {
949: my ($lonid,$udom,$uname) = @_;
950: my $result = &reply(join(':','userhassession',
951: map {&escape($_)} ($udom,$uname)),$lonid);
952: return 1 if ($result eq 'ok');
953:
954: return 0;
955: }
956:
1.1076 raeburn 957: # --------- determine least loaded server in a user's domain which allows login
958:
959: sub choose_server {
1.1259 raeburn 960: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 961: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 962: my %servers = &get_servers($udom);
1.1076 raeburn 963: my $lowest_load = 30000;
1.1259 raeburn 964: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
965: if ($skiploadbal) {
966: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
967: unless (defined($cached)) {
968: my $cachetime = 60*60*24;
969: my %domconfig =
970: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
971: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
972: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
973: $cachetime);
974: }
975: }
976: }
1.1076 raeburn 977: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: my $loginvia;
984: if ($checkloginvia) {
985: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 986: if ($loginvia) {
987: my ($server,$path) = split(/:/,$loginvia);
988: ($login_host, $lowest_load) =
1.1253 raeburn 989: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 990: if ($login_host eq $server) {
991: $portal_path = $path;
1.1151 raeburn 992: $isredirect = 1;
1.1116 raeburn 993: }
994: } else {
995: ($login_host, $lowest_load) =
1.1253 raeburn 996: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $lonhost) {
998: $portal_path = '';
1.1151 raeburn 999: $isredirect = '';
1.1116 raeburn 1000: }
1001: }
1002: } else {
1.1076 raeburn 1003: ($login_host, $lowest_load) =
1.1253 raeburn 1004: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1005: }
1006: }
1007: if ($login_host ne '') {
1.1116 raeburn 1008: $hostname = &hostname($login_host);
1.1076 raeburn 1009: }
1.1151 raeburn 1010: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1011: }
1012:
1.202 matthew 1013: # --------------------------------------------- Try to change a user's password
1014:
1015: sub changepass {
1.799 raeburn 1016: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1017: $currentpass = &escape($currentpass);
1018: $newpass = &escape($newpass);
1.1030 raeburn 1019: my $lonhost = $perlvar{'lonHostID'};
1020: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1021: $server);
1022: if (! $answer) {
1023: &logthis("No reply on password change request to $server ".
1024: "by $uname in domain $udom.");
1025: } elsif ($answer =~ "^ok") {
1026: &logthis("$uname in $udom successfully changed their password ".
1027: "on $server.");
1028: } elsif ($answer =~ "^pwchange_failure") {
1029: &logthis("$uname in $udom was unable to change their password ".
1030: "on $server. The action was blocked by either lcpasswd ".
1031: "or pwchange");
1032: } elsif ($answer =~ "^non_authorized") {
1033: &logthis("$uname in $udom did not get their password correct when ".
1034: "attempting to change it on $server.");
1035: } elsif ($answer =~ "^auth_mode_error") {
1036: &logthis("$uname in $udom attempted to change their password despite ".
1037: "not being locally or internally authenticated on $server.");
1038: } elsif ($answer =~ "^unknown_user") {
1039: &logthis("$uname in $udom attempted to change their password ".
1040: "on $server but were unable to because $server is not ".
1041: "their home server.");
1042: } elsif ($answer =~ "^refused") {
1043: &logthis("$server refused to change $uname in $udom password because ".
1044: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1045: } elsif ($answer =~ "invalid_client") {
1046: &logthis("$server refused to change $uname in $udom password because ".
1047: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1048: }
1049: return $answer;
1.1 albertel 1050: }
1051:
1.169 harris41 1052: # ----------------------- Try to determine user's current authentication scheme
1053:
1054: sub queryauthenticate {
1055: my ($uname,$udom)=@_;
1.456 albertel 1056: my $uhome=&homeserver($uname,$udom);
1057: if (!$uhome) {
1058: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1059: return 'no_host';
1060: }
1061: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1062: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1063: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1064: }
1.456 albertel 1065: return $answer;
1.169 harris41 1066: }
1067:
1.1 albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1069:
1.1 albertel 1070: sub authenticate {
1.1073 raeburn 1071: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1072: $upass=&escape($upass);
1073: $uname= &LONCAPA::clean_username($uname);
1.836 www 1074: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1075: my $newhome;
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: # Maybe the machine was offline and only re-appeared again recently?
1078: &reconlonc();
1079: # One more
1.952 raeburn 1080: $uhome=&homeserver($uname,$udom,1);
1081: if (($uhome eq 'no_host') && $checkdefauth) {
1082: if (defined(&domain($udom,'primary'))) {
1083: $newhome=&domain($udom,'primary');
1084: }
1085: if ($newhome ne '') {
1086: $uhome = $newhome;
1087: }
1088: }
1.836 www 1089: if ((!$uhome) || ($uhome eq 'no_host')) {
1090: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1091: return 'no_host';
1092: }
1.1 albertel 1093: }
1.1073 raeburn 1094: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1095: if ($answer eq 'authorized') {
1.952 raeburn 1096: if ($newhome) {
1097: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1098: return 'no_account_on_host';
1099: } else {
1100: &logthis("User $uname at $udom authorized by $uhome");
1101: return $uhome;
1102: }
1.471 albertel 1103: }
1104: if ($answer eq 'non_authorized') {
1105: &logthis("User $uname at $udom rejected by $uhome");
1106: return 'no_host';
1.9 www 1107: }
1.471 albertel 1108: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1109: return 'no_host';
1110: }
1111:
1.1073 raeburn 1112: sub can_host_session {
1.1074 raeburn 1113: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1114: my $canhost = 1;
1.1074 raeburn 1115: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1116: if (ref($remotesessions) eq 'HASH') {
1117: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1118: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1119: $canhost = 0;
1120: } else {
1121: $canhost = 1;
1122: }
1123: }
1124: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1126: $canhost = 1;
1127: } else {
1128: $canhost = 0;
1129: }
1130: }
1131: if ($canhost) {
1132: if ($remotesessions->{'version'} ne '') {
1133: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1134: if ($reqmajor ne '' && $reqminor ne '') {
1135: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1136: my $major = $1;
1137: my $minor = $2;
1138: if (($major < $reqmajor ) ||
1139: (($major == $reqmajor) && ($minor < $reqminor))) {
1140: $canhost = 0;
1141: }
1142: } else {
1143: $canhost = 0;
1144: }
1145: }
1146: }
1147: }
1148: }
1149: if ($canhost) {
1150: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1151: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1152: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1153: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1154: if (($uint_dom ne '') &&
1155: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1156: $canhost = 0;
1157: } else {
1158: $canhost = 1;
1159: }
1160: }
1161: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1162: if (($uint_dom ne '') &&
1163: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1164: $canhost = 1;
1165: } else {
1166: $canhost = 0;
1167: }
1168: }
1169: }
1170: }
1171: return $canhost;
1172: }
1173:
1.1083 raeburn 1174: sub spare_can_host {
1175: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1176: my $canhost=1;
1.1279 raeburn 1177: my $try_server_hostname = &hostname($try_server);
1178: my $serverhomeID = &get_server_homeID($try_server_hostname);
1179: my $serverhomedom = &host_domain($serverhomeID);
1180: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1181: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1182: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1183: $canhost = 0;
1184: }
1185: }
1186: if (($canhost) && ($uint_dom)) {
1187: my @intdoms;
1188: my $internet_names = &get_internet_names($try_server);
1189: if (ref($internet_names) eq 'ARRAY') {
1190: @intdoms = @{$internet_names};
1191: }
1192: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1193: my $remoterev = &get_server_loncaparev(undef,$try_server);
1194: $canhost = &can_host_session($udom,$try_server,$remoterev,
1195: $remotesessions,
1196: $defdomdefaults{'hostedsessions'});
1197: }
1.1083 raeburn 1198: }
1199: return $canhost;
1200: }
1201:
1.1123 raeburn 1202: sub this_host_spares {
1203: my ($dom) = @_;
1.1126 raeburn 1204: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1205: my @hosts = ¤t_machine_ids();
1206: foreach my $lonhost (@hosts) {
1207: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1208: $dom_in_use = $dom;
1209: $lonhost_in_use = $lonhost;
1.1123 raeburn 1210: last;
1211: }
1212: }
1.1126 raeburn 1213: if ($dom_in_use ne '') {
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: }
1216: if (ref($result) ne 'HASH') {
1217: $lonhost_in_use = $perlvar{'lonHostID'};
1218: $dom_in_use = &host_domain($lonhost_in_use);
1219: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1220: if (ref($result) ne 'HASH') {
1221: $result = \%spareid;
1222: }
1223: }
1224: return $result;
1225: }
1226:
1227: sub spares_for_offload {
1228: my ($dom_in_use,$lonhost_in_use) = @_;
1229: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1230: if (defined($cached)) {
1231: return $result;
1232: } else {
1.1126 raeburn 1233: my $cachetime = 60*60*24;
1234: my %domconfig =
1235: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1236: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1237: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1238: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1239: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1240: }
1241: }
1242: }
1243: }
1.1126 raeburn 1244: return;
1.1123 raeburn 1245: }
1246:
1.1129 raeburn 1247: sub get_lonbalancer_config {
1248: my ($servers) = @_;
1249: my ($currbalancer,$currtargets);
1250: if (ref($servers) eq 'HASH') {
1251: foreach my $server (keys(%{$servers})) {
1252: my %what = (
1253: spareid => 1,
1254: perlvar => 1,
1255: );
1256: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1257: if ($result eq 'ok') {
1258: if (ref($returnhash) eq 'HASH') {
1259: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1260: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1261: $currbalancer = $server;
1262: $currtargets = {};
1263: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1264: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1265: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1266: }
1267: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1268: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1269: }
1270: }
1271: last;
1272: }
1273: }
1274: }
1275: }
1276: }
1277: }
1278: return ($currbalancer,$currtargets);
1279: }
1280:
1281: sub check_loadbalancing {
1282: my ($uname,$udom) = @_;
1.1191 raeburn 1283: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1284: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1286: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1287: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1288: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1289: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1290: my $serverhomedom = &host_domain($lonhost);
1291:
1292: my $cachetime = 60*60*24;
1293:
1294: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1295: $dom_in_use = $udom;
1296: $homeintdom = 1;
1297: } else {
1298: $dom_in_use = $serverhomedom;
1299: }
1300: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1301: unless (defined($cached)) {
1302: my %domconfig =
1303: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1304: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1305: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1306: }
1307: }
1308: if (ref($result) eq 'HASH') {
1.1191 raeburn 1309: ($is_balancer,$currtargets,$currrules) =
1310: &check_balancer_result($result,@hosts);
1.1129 raeburn 1311: if ($is_balancer) {
1312: if (ref($currrules) eq 'HASH') {
1313: if ($homeintdom) {
1314: if ($uname ne '') {
1315: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1316: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1317: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1318: $rule_in_effect = $currrules->{'_LC_author'};
1319: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1320: $rule_in_effect = $currrules->{'_LC_adv'}
1321: }
1322: }
1323: if ($rule_in_effect eq '') {
1324: my %userenv = &userenvironment($udom,$uname,'inststatus');
1325: if ($userenv{'inststatus'} ne '') {
1326: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1327: my ($othertitle,$usertypes,$types) =
1328: &Apache::loncommon::sorted_inst_types($udom);
1329: if (ref($types) eq 'ARRAY') {
1330: foreach my $type (@{$types}) {
1331: if (grep(/^\Q$type\E$/,@statuses)) {
1332: if (exists($currrules->{$type})) {
1333: $rule_in_effect = $currrules->{$type};
1334: }
1335: }
1336: }
1337: }
1338: } else {
1339: if (exists($currrules->{'default'})) {
1340: $rule_in_effect = $currrules->{'default'};
1341: }
1342: }
1343: }
1344: } else {
1345: if (exists($currrules->{'default'})) {
1346: $rule_in_effect = $currrules->{'default'};
1347: }
1348: }
1349: } else {
1350: if ($currrules->{'_LC_external'} ne '') {
1351: $rule_in_effect = $currrules->{'_LC_external'};
1352: }
1353: }
1354: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1355: $uname,$udom);
1356: }
1357: }
1358: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1359: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1360: unless (defined($cached)) {
1361: my %domconfig =
1362: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1363: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1364: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1365: }
1366: }
1367: if (ref($result) eq 'HASH') {
1.1191 raeburn 1368: ($is_balancer,$currtargets,$currrules) =
1369: &check_balancer_result($result,@hosts);
1370: if ($is_balancer) {
1.1129 raeburn 1371: if (ref($currrules) eq 'HASH') {
1372: if ($currrules->{'_LC_internetdom'} ne '') {
1373: $rule_in_effect = $currrules->{'_LC_internetdom'};
1374: }
1375: }
1376: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1377: $uname,$udom);
1378: }
1379: } else {
1380: if ($perlvar{'lonBalancer'} eq 'yes') {
1381: $is_balancer = 1;
1382: $offloadto = &this_host_spares($dom_in_use);
1383: }
1384: }
1385: } else {
1386: if ($perlvar{'lonBalancer'} eq 'yes') {
1387: $is_balancer = 1;
1388: $offloadto = &this_host_spares($dom_in_use);
1389: }
1390: }
1.1176 raeburn 1391: if ($is_balancer) {
1392: my $lowest_load = 30000;
1393: if (ref($offloadto) eq 'HASH') {
1394: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'primary'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1.1129 raeburn 1399: }
1.1176 raeburn 1400: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1401:
1.1176 raeburn 1402: if (!$found_server) {
1403: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1404: foreach my $try_server (@{$offloadto->{'default'}}) {
1405: ($otherserver,$lowest_load) =
1406: &compare_server_load($try_server,$otherserver,$lowest_load);
1407: }
1408: }
1409: }
1410: } elsif (ref($offloadto) eq 'ARRAY') {
1411: if (@{$offloadto} == 1) {
1412: $otherserver = $offloadto->[0];
1413: } elsif (@{$offloadto} > 1) {
1414: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1415: ($otherserver,$lowest_load) =
1416: &compare_server_load($try_server,$otherserver,$lowest_load);
1417: }
1418: }
1419: }
1.1176 raeburn 1420: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1421: $is_balancer = 0;
1422: if ($uname ne '' && $udom ne '') {
1423: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1424:
1425: &appenv({'user.loadbalexempt' => $lonhost,
1426: 'user.loadbalcheck.time' => time});
1427: }
1.1129 raeburn 1428: }
1429: }
1430: }
1431: return ($is_balancer,$otherserver);
1432: }
1433:
1.1191 raeburn 1434: sub check_balancer_result {
1435: my ($result,@hosts) = @_;
1436: my ($is_balancer,$currtargets,$currrules);
1437: if (ref($result) eq 'HASH') {
1438: if ($result->{'lonhost'} ne '') {
1439: my $currbalancer = $result->{'lonhost'};
1440: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1441: $is_balancer = 1;
1442: $currtargets = $result->{'targets'};
1443: $currrules = $result->{'rules'};
1444: }
1445: } else {
1446: foreach my $key (keys(%{$result})) {
1447: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1448: (ref($result->{$key}) eq 'HASH')) {
1449: $is_balancer = 1;
1450: $currrules = $result->{$key}{'rules'};
1451: $currtargets = $result->{$key}{'targets'};
1452: last;
1453: }
1454: }
1455: }
1456: }
1457: return ($is_balancer,$currtargets,$currrules);
1458: }
1459:
1.1129 raeburn 1460: sub get_loadbalancer_targets {
1461: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1462: my $offloadto;
1.1175 raeburn 1463: if ($rule_in_effect eq 'none') {
1464: return [$perlvar{'lonHostID'}];
1465: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1466: $offloadto = $currtargets;
1467: } else {
1468: if ($rule_in_effect eq 'homeserver') {
1469: my $homeserver = &homeserver($uname,$udom);
1470: if ($homeserver ne 'no_host') {
1471: $offloadto = [$homeserver];
1472: }
1473: } elsif ($rule_in_effect eq 'externalbalancer') {
1474: my %domconfig =
1475: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1476: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1477: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1478: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1479: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1480: }
1481: }
1482: } else {
1.1178 raeburn 1483: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1484: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1485: if (&hostname($remotebalancer) ne '') {
1486: $offloadto = [$remotebalancer];
1487: }
1488: }
1489: } elsif (&hostname($rule_in_effect) ne '') {
1490: $offloadto = [$rule_in_effect];
1491: }
1492: }
1493: return $offloadto;
1494: }
1495:
1.1127 raeburn 1496: sub internet_dom_servers {
1497: my ($dom) = @_;
1498: my (%uniqservers,%servers);
1499: my $primaryserver = &hostname(&domain($dom,'primary'));
1500: my @machinedoms = &machine_domains($primaryserver);
1501: foreach my $mdom (@machinedoms) {
1502: my %currservers = %servers;
1503: my %server = &get_servers($mdom);
1504: %servers = (%currservers,%server);
1505: }
1506: my %by_hostname;
1507: foreach my $id (keys(%servers)) {
1508: push(@{$by_hostname{$servers{$id}}},$id);
1509: }
1510: foreach my $hostname (sort(keys(%by_hostname))) {
1511: if (@{$by_hostname{$hostname}} > 1) {
1512: my $match = 0;
1513: foreach my $id (@{$by_hostname{$hostname}}) {
1514: if (&host_domain($id) eq $dom) {
1515: $uniqservers{$id} = $hostname;
1516: $match = 1;
1517: }
1518: }
1519: unless ($match) {
1520: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1521: }
1522: } else {
1523: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1524: }
1525: }
1526: return %uniqservers;
1527: }
1528:
1.1 albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1530:
1.599 albertel 1531: my %homecache;
1.1 albertel 1532: sub homeserver {
1.230 stredwic 1533: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1534: my $index="$uname:$udom";
1.426 albertel 1535:
1.599 albertel 1536: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1537:
1538: my %servers = &get_servers($udom,'library');
1539: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1540: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1541: exists($badServerCache{$tryserver}));
1.841 albertel 1542:
1543: my $answer=reply("home:$udom:$uname",$tryserver);
1544: if ($answer eq 'found') {
1545: delete($badServerCache{$tryserver});
1546: return $homecache{$index}=$tryserver;
1547: } elsif ($answer eq 'no_host') {
1548: $badServerCache{$tryserver}=1;
1549: }
1.1 albertel 1550: }
1551: return 'no_host';
1.70 www 1552: }
1553:
1554: # ------------------------------------- Find the usernames behind a list of IDs
1555:
1556: sub idget {
1557: my ($udom,@ids)=@_;
1558: my %returnhash=();
1559:
1.841 albertel 1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1562: my $idlist=join('&',@ids);
1563: $idlist=~tr/A-Z/a-z/;
1564: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1565: my @answer=();
1566: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1567: @answer=split(/\&/,$reply);
1568: } ;
1569: my $i;
1570: for ($i=0;$i<=$#ids;$i++) {
1571: if ($answer[$i]) {
1572: $returnhash{$ids[$i]}=$answer[$i];
1573: }
1574: }
1575: }
1.70 www 1576: return %returnhash;
1577: }
1578:
1579: # ------------------------------------- Find the IDs behind a list of usernames
1580:
1581: sub idrget {
1582: my ($udom,@unames)=@_;
1583: my %returnhash=();
1.800 albertel 1584: foreach my $uname (@unames) {
1585: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1586: }
1.70 www 1587: return %returnhash;
1588: }
1589:
1590: # ------------------------------- Store away a list of names and associated IDs
1591:
1592: sub idput {
1593: my ($udom,%ids)=@_;
1594: my %servers=();
1.800 albertel 1595: foreach my $uname (keys(%ids)) {
1596: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1597: my $uhom=&homeserver($uname,$udom);
1.70 www 1598: if ($uhom ne 'no_host') {
1.800 albertel 1599: my $id=&escape($ids{$uname});
1.70 www 1600: $id=~tr/A-Z/a-z/;
1.800 albertel 1601: my $esc_unam=&escape($uname);
1.70 www 1602: if ($servers{$uhom}) {
1.800 albertel 1603: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1604: } else {
1.800 albertel 1605: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1606: }
1607: }
1.191 harris41 1608: }
1.800 albertel 1609: foreach my $server (keys(%servers)) {
1610: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1611: }
1.344 www 1612: }
1613:
1.1231 raeburn 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file
1615:
1616: sub iddel {
1617: my ($udom,$idshashref,$uhome)=@_;
1618: my %result=();
1619: unless (ref($idshashref) eq 'HASH') {
1620: return %result;
1621: }
1622: my %servers=();
1623: while (my ($id,$uname) = each(%{$idshashref})) {
1624: my $uhom;
1625: if ($uhome) {
1626: $uhom = $uhome;
1627: } else {
1628: $uhom=&homeserver($uname,$udom);
1629: }
1630: if ($uhom ne 'no_host') {
1631: if ($servers{$uhom}) {
1632: $servers{$uhom}.='&'.&escape($id);
1633: } else {
1634: $servers{$uhom}=&escape($id);
1635: }
1636: }
1637: }
1638: foreach my $server (keys(%servers)) {
1639: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1640: }
1641: return %result;
1642: }
1643:
1.1023 raeburn 1644: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1645: sub dump_dom {
1.1165 droeschl 1646: my ($namespace, $udom, $regexp) = @_;
1647:
1648: $udom ||= $env{'user.domain'};
1649:
1650: return () unless $udom;
1651:
1652: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1653: }
1654:
1.1023 raeburn 1655: # ------------------------------------------ get items from domain db files
1.806 raeburn 1656:
1657: sub get_dom {
1.860 raeburn 1658: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1659: return if ($udom eq 'public');
1.806 raeburn 1660: my $items='';
1661: foreach my $item (@$storearr) {
1662: $items.=&escape($item).'&';
1663: }
1664: $items=~s/\&$//;
1.860 raeburn 1665: if (!$udom) {
1666: $udom=$env{'user.domain'};
1.1267 raeburn 1667: return if ($udom eq 'public');
1.860 raeburn 1668: if (defined(&domain($udom,'primary'))) {
1669: $uhome=&domain($udom,'primary');
1670: } else {
1.874 albertel 1671: undef($uhome);
1.860 raeburn 1672: }
1673: } else {
1674: if (!$uhome) {
1675: if (defined(&domain($udom,'primary'))) {
1676: $uhome=&domain($udom,'primary');
1677: }
1678: }
1679: }
1680: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1681: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1682: my %returnhash;
1.875 albertel 1683: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1684: return %returnhash;
1685: }
1.806 raeburn 1686: my @pairs=split(/\&/,$rep);
1687: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1688: return @pairs;
1689: }
1690: my $i=0;
1691: foreach my $item (@$storearr) {
1692: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1693: $i++;
1694: }
1695: return %returnhash;
1696: } else {
1.880 banghart 1697: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1698: }
1699: }
1700:
1701: # -------------------------------------------- put items in domain db files
1702:
1703: sub put_dom {
1.860 raeburn 1704: my ($namespace,$storehash,$udom,$uhome)=@_;
1705: if (!$udom) {
1706: $udom=$env{'user.domain'};
1707: if (defined(&domain($udom,'primary'))) {
1708: $uhome=&domain($udom,'primary');
1709: } else {
1.874 albertel 1710: undef($uhome);
1.860 raeburn 1711: }
1712: } else {
1713: if (!$uhome) {
1714: if (defined(&domain($udom,'primary'))) {
1715: $uhome=&domain($udom,'primary');
1716: }
1717: }
1718: }
1719: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1720: my $items='';
1721: foreach my $item (keys(%$storehash)) {
1722: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1723: }
1724: $items=~s/\&$//;
1725: return &reply("putdom:$udom:$namespace:$items",$uhome);
1726: } else {
1.860 raeburn 1727: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1728: }
1729: }
1730:
1.1023 raeburn 1731: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1732: sub newput_dom {
1.1023 raeburn 1733: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1734: my $result;
1735: if (!$udom) {
1736: $udom=$env{'user.domain'};
1737: }
1.1023 raeburn 1738: if ($udom) {
1739: my $uname = &get_domainconfiguser($udom);
1740: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1741: }
1742: return $result;
1743: }
1744:
1.1023 raeburn 1745: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1746: sub del_dom {
1.1023 raeburn 1747: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1748: if (ref($storearr) eq 'ARRAY') {
1749: if (!$udom) {
1750: $udom=$env{'user.domain'};
1751: }
1.1023 raeburn 1752: if ($udom) {
1753: my $uname = &get_domainconfiguser($udom);
1754: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1755: }
1756: }
1757: }
1758:
1.1023 raeburn 1759: # ----------------------------------construct domainconfig user for a domain
1760: sub get_domainconfiguser {
1761: my ($udom) = @_;
1762: return $udom.'-domainconfig';
1763: }
1764:
1.837 raeburn 1765: sub retrieve_inst_usertypes {
1766: my ($udom) = @_;
1767: my (%returnhash,@order);
1.989 raeburn 1768: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1769: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1770: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1771: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1772: } else {
1773: if (defined(&domain($udom,'primary'))) {
1774: my $uhome=&domain($udom,'primary');
1775: my $rep=&reply("inst_usertypes:$udom",$uhome);
1776: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1777: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1778: return (\%returnhash,\@order);
1779: }
1780: my ($hashitems,$orderitems) = split(/:/,$rep);
1781: my @pairs=split(/\&/,$hashitems);
1782: foreach my $item (@pairs) {
1783: my ($key,$value)=split(/=/,$item,2);
1784: $key = &unescape($key);
1785: next if ($key =~ /^error: 2 /);
1786: $returnhash{$key}=&thaw_unescape($value);
1787: }
1788: my @esc_order = split(/\&/,$orderitems);
1789: foreach my $item (@esc_order) {
1790: push(@order,&unescape($item));
1791: }
1792: } else {
1.1256 raeburn 1793: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1794: }
1.1256 raeburn 1795: return (\%returnhash,\@order);
1.837 raeburn 1796: }
1797: }
1798:
1.868 raeburn 1799: sub is_domainimage {
1800: my ($url) = @_;
1801: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1802: if (&domain($1) ne '') {
1803: return '1';
1804: }
1805: }
1806: return;
1807: }
1808:
1.899 raeburn 1809: sub inst_directory_query {
1810: my ($srch) = @_;
1811: my $udom = $srch->{'srchdomain'};
1812: my %results;
1813: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1814: my $outcome;
1.899 raeburn 1815: if ($homeserver ne '') {
1.904 albertel 1816: my $queryid=&reply("querysend:instdirsearch:".
1817: &escape($srch->{'srchby'}).':'.
1818: &escape($srch->{'srchterm'}).':'.
1819: &escape($srch->{'srchtype'}),$homeserver);
1820: my $host=&hostname($homeserver);
1821: if ($queryid !~/^\Q$host\E\_/) {
1822: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1823: return;
1824: }
1825: my $response = &get_query_reply($queryid);
1826: my $maxtries = 5;
1827: my $tries = 1;
1828: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1829: $response = &get_query_reply($queryid);
1830: $tries ++;
1831: }
1832:
1833: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1834: if ($response eq 'unavailable') {
1835: $outcome = $response;
1836: } else {
1837: $outcome = 'ok';
1838: my @matches = split(/\n/,$response);
1839: foreach my $match (@matches) {
1840: my ($key,$value) = split(/=/,$match);
1841: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1842: }
1.899 raeburn 1843: }
1844: }
1845: }
1.909 raeburn 1846: return ($outcome,%results);
1.899 raeburn 1847: }
1848:
1849: sub usersearch {
1850: my ($srch) = @_;
1851: my $dom = $srch->{'srchdomain'};
1852: my %results;
1853: my %libserv = &all_library();
1854: my $query = 'usersearch';
1855: foreach my $tryserver (keys(%libserv)) {
1856: if (&host_domain($tryserver) eq $dom) {
1857: my $host=&hostname($tryserver);
1858: my $queryid=
1.911 raeburn 1859: &reply("querysend:".&escape($query).':'.
1860: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1861: &escape($srch->{'srchtype'}).':'.
1862: &escape($srch->{'srchterm'}),$tryserver);
1863: if ($queryid !~/^\Q$host\E\_/) {
1864: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1865: next;
1.899 raeburn 1866: }
1867: my $reply = &get_query_reply($queryid);
1868: my $maxtries = 1;
1869: my $tries = 1;
1870: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1871: $reply = &get_query_reply($queryid);
1872: $tries ++;
1873: }
1874: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1875: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1876: } else {
1.911 raeburn 1877: my @matches;
1878: if ($reply =~ /\n/) {
1879: @matches = split(/\n/,$reply);
1880: } else {
1881: @matches = split(/\&/,$reply);
1882: }
1.899 raeburn 1883: foreach my $match (@matches) {
1884: my ($uname,$udom,%userhash);
1.911 raeburn 1885: foreach my $entry (split(/:/,$match)) {
1886: my ($key,$value) =
1887: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1888: $userhash{$key} = $value;
1889: if ($key eq 'username') {
1890: $uname = $value;
1891: } elsif ($key eq 'domain') {
1892: $udom = $value;
1.911 raeburn 1893: }
1.899 raeburn 1894: }
1895: $results{$uname.':'.$udom} = \%userhash;
1896: }
1897: }
1898: }
1899: }
1900: return %results;
1901: }
1902:
1.912 raeburn 1903: sub get_instuser {
1904: my ($udom,$uname,$id) = @_;
1905: my $homeserver = &domain($udom,'primary');
1906: my ($outcome,%results);
1907: if ($homeserver ne '') {
1908: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1909: &escape($id).':'.&escape($udom),$homeserver);
1910: my $host=&hostname($homeserver);
1911: if ($queryid !~/^\Q$host\E\_/) {
1912: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1913: return;
1914: }
1915: my $response = &get_query_reply($queryid);
1916: my $maxtries = 5;
1917: my $tries = 1;
1918: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1919: $response = &get_query_reply($queryid);
1920: $tries ++;
1921: }
1922: if (!&error($response) && $response ne 'refused') {
1923: if ($response eq 'unavailable') {
1924: $outcome = $response;
1925: } else {
1926: $outcome = 'ok';
1927: my @matches = split(/\n/,$response);
1928: foreach my $match (@matches) {
1929: my ($key,$value) = split(/=/,$match);
1930: $results{&unescape($key)} = &thaw_unescape($value);
1931: }
1932: }
1933: }
1934: }
1935: my %userinfo;
1936: if (ref($results{$uname}) eq 'HASH') {
1937: %userinfo = %{$results{$uname}};
1938: }
1939: return ($outcome,%userinfo);
1940: }
1941:
1942: sub inst_rulecheck {
1.923 raeburn 1943: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1944: my %returnhash;
1945: if ($udom ne '') {
1946: if (ref($rules) eq 'ARRAY') {
1947: @{$rules} = map {&escape($_);} (@{$rules});
1948: my $rulestr = join(':',@{$rules});
1949: my $homeserver=&domain($udom,'primary');
1950: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1951: my $response;
1952: if ($item eq 'username') {
1953: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1954: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1955: $homeserver));
1.923 raeburn 1956: } elsif ($item eq 'id') {
1957: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1958: ':'.&escape($id).':'.$rulestr,
1959: $homeserver));
1.945 raeburn 1960: } elsif ($item eq 'selfcreate') {
1961: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1962: &escape($udom).':'.&escape($uname).
1963: ':'.$rulestr,$homeserver));
1.923 raeburn 1964: }
1.912 raeburn 1965: if ($response ne 'refused') {
1966: my @pairs=split(/\&/,$response);
1967: foreach my $item (@pairs) {
1968: my ($key,$value)=split(/=/,$item,2);
1969: $key = &unescape($key);
1970: next if ($key =~ /^error: 2 /);
1971: $returnhash{$key}=&thaw_unescape($value);
1972: }
1973: }
1974: }
1975: }
1976: }
1977: return %returnhash;
1978: }
1979:
1980: sub inst_userrules {
1.923 raeburn 1981: my ($udom,$check) = @_;
1.912 raeburn 1982: my (%ruleshash,@ruleorder);
1983: if ($udom ne '') {
1984: my $homeserver=&domain($udom,'primary');
1985: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1986: my $response;
1987: if ($check eq 'id') {
1988: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1989: $homeserver);
1.943 raeburn 1990: } elsif ($check eq 'email') {
1991: $response=&reply('instemailrules:'.&escape($udom),
1992: $homeserver);
1.923 raeburn 1993: } else {
1994: $response=&reply('instuserrules:'.&escape($udom),
1995: $homeserver);
1996: }
1.912 raeburn 1997: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1998: ($response ne 'unknown_cmd') &&
1.912 raeburn 1999: ($response ne 'no_such_host')) {
2000: my ($hashitems,$orderitems) = split(/:/,$response);
2001: my @pairs=split(/\&/,$hashitems);
2002: foreach my $item (@pairs) {
2003: my ($key,$value)=split(/=/,$item,2);
2004: $key = &unescape($key);
2005: next if ($key =~ /^error: 2 /);
2006: $ruleshash{$key}=&thaw_unescape($value);
2007: }
2008: my @esc_order = split(/\&/,$orderitems);
2009: foreach my $item (@esc_order) {
2010: push(@ruleorder,&unescape($item));
2011: }
2012: }
2013: }
2014: }
2015: return (\%ruleshash,\@ruleorder);
2016: }
2017:
1.976 raeburn 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2019:
2020: sub get_domain_defaults {
1.1240 raeburn 2021: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2022: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2023: my $cachetime = 60*60*24;
1.1240 raeburn 2024: unless ($ignore_cache) {
2025: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2026: if (defined($cached)) {
2027: if (ref($result) eq 'HASH') {
2028: return %{$result};
2029: }
1.943 raeburn 2030: }
2031: }
2032: my %domdefaults;
2033: my %domconfig =
1.989 raeburn 2034: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2035: 'requestcourses','inststatus',
1.1183 raeburn 2036: 'coursedefaults','usersessions',
1.1258 raeburn 2037: 'requestauthor','selfenrollment',
2038: 'coursecategories'],$domain);
1.1254 raeburn 2039: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2040: if (ref($domconfig{'defaults'}) eq 'HASH') {
2041: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2042: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2043: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2044: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2045: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2046: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2047: } else {
2048: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2049: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2050: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2051: }
1.976 raeburn 2052: if (ref($domconfig{'quotas'}) eq 'HASH') {
2053: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2054: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2055: } else {
2056: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2057: }
1.1177 raeburn 2058: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2059: foreach my $item (@usertools) {
2060: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2061: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2062: }
2063: }
1.1229 raeburn 2064: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2065: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2066: }
1.976 raeburn 2067: }
1.985 raeburn 2068: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2069: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2070: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2071: }
2072: }
1.1183 raeburn 2073: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2074: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2075: }
1.989 raeburn 2076: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2077: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2078: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2079: }
2080: }
1.1047 raeburn 2081: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2082: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2083: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2084: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2085: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2086: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2087: }
1.1254 raeburn 2088: foreach my $type (@coursetypes) {
2089: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2090: unless ($type eq 'community') {
2091: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2092: }
2093: }
2094: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2095: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2096: }
1.1277 raeburn 2097: if ($domdefaults{'postsubmit'} eq 'on') {
2098: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2099: $domdefaults{$type.'postsubtimeout'} =
2100: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2101: }
2102: }
1.1230 raeburn 2103: }
1.1286 raeburn 2104: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2105: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2106: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2107: if (@clonecodes) {
2108: $domdefaults{'canclone'} = join('+',@clonecodes);
2109: }
2110: }
2111: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2112: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2113: }
1.1047 raeburn 2114: }
1.1073 raeburn 2115: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2116: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2117: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2118: }
2119: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2120: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2121: }
1.1279 raeburn 2122: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2123: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2124: }
1.1073 raeburn 2125: }
1.1254 raeburn 2126: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2127: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2128: my @settings = ('types','registered','enroll_dates','access_dates','section',
2129: 'approval','limit');
2130: foreach my $type (@coursetypes) {
2131: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2132: my @mgrdc = ();
2133: foreach my $item (@settings) {
2134: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2135: push(@mgrdc,$item);
2136: }
2137: }
2138: if (@mgrdc) {
2139: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2140: }
2141: }
2142: }
2143: }
2144: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2145: foreach my $type (@coursetypes) {
2146: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2147: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2148: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2149: }
2150: }
2151: }
2152: }
2153: }
1.1258 raeburn 2154: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2155: $domdefaults{'catauth'} = 'std';
2156: $domdefaults{'catunauth'} = 'std';
2157: if ($domconfig{'coursecategories'}{'auth'}) {
2158: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2159: }
2160: if ($domconfig{'coursecategories'}{'unauth'}) {
2161: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2162: }
2163: }
1.1219 raeburn 2164: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2165: return %domdefaults;
2166: }
2167:
1.344 www 2168: # --------------------------------------------------- Assign a key to a student
2169:
2170: sub assign_access_key {
1.364 www 2171: #
2172: # a valid key looks like uname:udom#comments
2173: # comments are being appended
2174: #
1.498 www 2175: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2176: $kdom=
1.620 albertel 2177: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2178: $knum=
1.620 albertel 2179: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2180: $cdom=
1.620 albertel 2181: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2182: $cnum=
1.620 albertel 2183: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2184: $udom=$env{'user.name'} unless (defined($udom));
2185: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2186: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2187: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2188: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2189: # assigned to this person
2190: # - this should not happen,
1.345 www 2191: # unless something went wrong
2192: # the first time around
2193: # ready to assign
1.364 www 2194: $logentry=$1.'; '.$logentry;
1.496 www 2195: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2196: $kdom,$knum) eq 'ok') {
1.345 www 2197: # key now belongs to user
1.346 www 2198: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2199: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2200: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2201: return 'ok';
2202: } else {
2203: return
2204: 'error: Count not permanently assign key, will need to be re-entered later.';
2205: }
2206: } else {
2207: return 'error: Could not assign key, try again later.';
2208: }
1.364 www 2209: } elsif (!$existing{$ckey}) {
1.345 www 2210: # the key does not exist
2211: return 'error: The key does not exist';
2212: } else {
2213: # the key is somebody else's
2214: return 'error: The key is already in use';
2215: }
1.344 www 2216: }
2217:
1.364 www 2218: # ------------------------------------------ put an additional comment on a key
2219:
2220: sub comment_access_key {
2221: #
2222: # a valid key looks like uname:udom#comments
2223: # comments are being appended
2224: #
2225: my ($ckey,$cdom,$cnum,$logentry)=@_;
2226: $cdom=
1.620 albertel 2227: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2228: $cnum=
1.620 albertel 2229: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2230: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2231: if ($existing{$ckey}) {
2232: $existing{$ckey}.='; '.$logentry;
2233: # ready to assign
1.367 www 2234: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2235: $cdom,$cnum) eq 'ok') {
2236: return 'ok';
2237: } else {
2238: return 'error: Count not store comment.';
2239: }
2240: } else {
2241: # the key does not exist
2242: return 'error: The key does not exist';
2243: }
2244: }
2245:
1.344 www 2246: # ------------------------------------------------------ Generate a set of keys
2247:
2248: sub generate_access_keys {
1.364 www 2249: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2250: $cdom=
1.620 albertel 2251: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2252: $cnum=
1.620 albertel 2253: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2254: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2255: unless (($cdom) && ($cnum)) { return 0; }
2256: if ($number>10000) { return 0; }
2257: sleep(2); # make sure don't get same seed twice
2258: srand(time()^($$+($$<<15))); # from "Programming Perl"
2259: my $total=0;
2260: for (my $i=1;$i<=$number;$i++) {
2261: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2262: sprintf("%lx",int(100000*rand)).'-'.
2263: sprintf("%lx",int(100000*rand));
2264: $newkey=~s/1/g/g; # folks mix up 1 and l
2265: $newkey=~s/0/h/g; # and also 0 and O
2266: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2267: if ($existing{$newkey}) {
2268: $i--;
2269: } else {
1.364 www 2270: if (&put('accesskeys',
2271: { $newkey => '# generated '.localtime().
1.620 albertel 2272: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2273: '; '.$logentry },
2274: $cdom,$cnum) eq 'ok') {
1.344 www 2275: $total++;
2276: }
2277: }
2278: }
1.620 albertel 2279: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2280: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2281: return $total;
2282: }
2283:
2284: # ------------------------------------------------------- Validate an accesskey
2285:
2286: sub validate_access_key {
2287: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2288: $cdom=
1.620 albertel 2289: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2290: $cnum=
1.620 albertel 2291: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2292: $udom=$env{'user.domain'} unless (defined($udom));
2293: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2294: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2295: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2296: }
2297:
2298: # ------------------------------------- Find the section of student in a course
1.652 albertel 2299: sub devalidate_getsection_cache {
2300: my ($udom,$unam,$courseid)=@_;
2301: my $hashid="$udom:$unam:$courseid";
2302: &devalidate_cache_new('getsection',$hashid);
2303: }
1.298 matthew 2304:
1.815 albertel 2305: sub courseid_to_courseurl {
2306: my ($courseid) = @_;
2307: #already url style courseid
2308: return $courseid if ($courseid =~ m{^/});
2309:
2310: if (exists($env{'course.'.$courseid.'.num'})) {
2311: my $cnum = $env{'course.'.$courseid.'.num'};
2312: my $cdom = $env{'course.'.$courseid.'.domain'};
2313: return "/$cdom/$cnum";
2314: }
2315:
2316: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2317: if (exists($courseinfo{'num'})) {
2318: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2319: }
2320:
2321: return undef;
2322: }
2323:
1.298 matthew 2324: sub getsection {
2325: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2326: my $cachetime=1800;
1.551 albertel 2327:
2328: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2329: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2330: if (defined($cached)) { return $result; }
2331:
1.298 matthew 2332: my %Pending;
2333: my %Expired;
2334: #
2335: # Each role can either have not started yet (pending), be active,
2336: # or have expired.
2337: #
2338: # If there is an active role, we are done.
2339: #
2340: # If there is more than one role which has not started yet,
2341: # choose the one which will start sooner
2342: # If there is one role which has not started yet, return it.
2343: #
2344: # If there is more than one expired role, choose the one which ended last.
2345: # If there is a role which has expired, return it.
2346: #
1.815 albertel 2347: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2348: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2349: foreach my $key (keys(%roleshash)) {
1.479 albertel 2350: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2351: my $section=$1;
2352: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2353: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2354: my $now=time;
1.548 albertel 2355: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2356: $Expired{$end}=$section;
2357: next;
2358: }
1.548 albertel 2359: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2360: $Pending{$start}=$section;
2361: next;
2362: }
1.599 albertel 2363: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2364: }
2365: #
2366: # Presumedly there will be few matching roles from the above
2367: # loop and the sorting time will be negligible.
2368: if (scalar(keys(%Pending))) {
2369: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2370: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2371: }
2372: if (scalar(keys(%Expired))) {
2373: my @sorted = sort {$a <=> $b} keys(%Expired);
2374: my $time = pop(@sorted);
1.599 albertel 2375: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2376: }
1.599 albertel 2377: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2378: }
1.70 www 2379:
1.599 albertel 2380: sub save_cache {
2381: &purge_remembered();
1.722 albertel 2382: #&Apache::loncommon::validate_page();
1.620 albertel 2383: undef(%env);
1.780 albertel 2384: undef($env_loaded);
1.599 albertel 2385: }
1.452 albertel 2386:
1.599 albertel 2387: my $to_remember=-1;
2388: my %remembered;
2389: my %accessed;
2390: my $kicks=0;
2391: my $hits=0;
1.849 albertel 2392: sub make_key {
2393: my ($name,$id) = @_;
1.872 albertel 2394: if (length($id) > 65
2395: && length(&escape($id)) > 200) {
2396: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2397: }
1.849 albertel 2398: return &escape($name.':'.$id);
2399: }
2400:
1.599 albertel 2401: sub devalidate_cache_new {
2402: my ($name,$id,$debug) = @_;
2403: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2404: $id=&make_key($name,$id);
1.599 albertel 2405: $memcache->delete($id);
2406: delete($remembered{$id});
2407: delete($accessed{$id});
2408: }
2409:
2410: sub is_cached_new {
2411: my ($name,$id,$debug) = @_;
1.849 albertel 2412: $id=&make_key($name,$id);
1.599 albertel 2413: if (exists($remembered{$id})) {
1.1133 foxr 2414: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2415: $accessed{$id}=[&gettimeofday()];
2416: $hits++;
2417: return ($remembered{$id},1);
2418: }
2419: my $value = $memcache->get($id);
2420: if (!(defined($value))) {
2421: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2422: return (undef,undef);
1.416 albertel 2423: }
1.599 albertel 2424: if ($value eq '__undef__') {
2425: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2426: $value=undef;
2427: }
2428: &make_room($id,$value,$debug);
2429: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2430: return ($value,1);
2431: }
2432:
2433: sub do_cache_new {
2434: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2435: $id=&make_key($name,$id);
1.599 albertel 2436: my $setvalue=$value;
2437: if (!defined($setvalue)) {
2438: $setvalue='__undef__';
2439: }
1.623 albertel 2440: if (!defined($time) ) {
2441: $time=600;
2442: }
1.599 albertel 2443: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2444: my $result = $memcache->set($id,$setvalue,$time);
2445: if (! $result) {
1.872 albertel 2446: &logthis("caching of id -> $id failed");
1.910 albertel 2447: $memcache->disconnect_all();
1.872 albertel 2448: }
1.600 albertel 2449: # need to make a copy of $value
1.919 albertel 2450: &make_room($id,$value,$debug);
1.599 albertel 2451: return $value;
2452: }
2453:
2454: sub make_room {
2455: my ($id,$value,$debug)=@_;
1.919 albertel 2456:
2457: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2458: : $value;
1.599 albertel 2459: if ($to_remember<0) { return; }
2460: $accessed{$id}=[&gettimeofday()];
2461: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2462: my $to_kick;
2463: my $max_time=0;
2464: foreach my $other (keys(%accessed)) {
2465: if (&tv_interval($accessed{$other}) > $max_time) {
2466: $to_kick=$other;
2467: $max_time=&tv_interval($accessed{$other});
2468: }
2469: }
2470: delete($remembered{$to_kick});
2471: delete($accessed{$to_kick});
2472: $kicks++;
2473: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2474: return;
2475: }
2476:
1.599 albertel 2477: sub purge_remembered {
1.604 albertel 2478: #&logthis("Tossing ".scalar(keys(%remembered)));
2479: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2480: undef(%remembered);
2481: undef(%accessed);
1.428 albertel 2482: }
1.70 www 2483: # ------------------------------------- Read an entry from a user's environment
2484:
2485: sub userenvironment {
2486: my ($udom,$unam,@what)=@_;
1.976 raeburn 2487: my $items;
2488: foreach my $item (@what) {
2489: $items.=&escape($item).'&';
2490: }
2491: $items=~s/\&$//;
1.70 www 2492: my %returnhash=();
1.1009 raeburn 2493: my $uhome = &homeserver($unam,$udom);
2494: unless ($uhome eq 'no_host') {
2495: my @answer=split(/\&/,
2496: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2497: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2498: return %returnhash;
2499: }
1.1009 raeburn 2500: my $i;
2501: for ($i=0;$i<=$#what;$i++) {
2502: $returnhash{$what[$i]}=&unescape($answer[$i]);
2503: }
1.70 www 2504: }
2505: return %returnhash;
1.1 albertel 2506: }
2507:
1.617 albertel 2508: # ---------------------------------------------------------- Get a studentphoto
2509: sub studentphoto {
2510: my ($udom,$unam,$ext) = @_;
2511: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2512: if (defined($env{'request.course.id'})) {
1.708 raeburn 2513: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2514: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2515: return(&retrievestudentphoto($udom,$unam,$ext));
2516: } else {
2517: my ($result,$perm_reqd)=
1.707 albertel 2518: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2519: if ($result eq 'ok') {
2520: if (!($perm_reqd eq 'yes')) {
2521: return(&retrievestudentphoto($udom,$unam,$ext));
2522: }
2523: }
2524: }
2525: }
2526: } else {
2527: my ($result,$perm_reqd) =
1.707 albertel 2528: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2529: if ($result eq 'ok') {
2530: if (!($perm_reqd eq 'yes')) {
2531: return(&retrievestudentphoto($udom,$unam,$ext));
2532: }
2533: }
2534: }
2535: return '/adm/lonKaputt/lonlogo_broken.gif';
2536: }
2537:
2538: sub retrievestudentphoto {
2539: my ($udom,$unam,$ext,$type) = @_;
2540: my $home=&Apache::lonnet::homeserver($unam,$udom);
2541: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2542: if ($ret eq 'ok') {
2543: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2544: if ($type eq 'thumbnail') {
2545: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2546: }
2547: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2548: return $tokenurl;
2549: } else {
2550: if ($type eq 'thumbnail') {
2551: return '/adm/lonKaputt/genericstudent_tn.gif';
2552: } else {
2553: return '/adm/lonKaputt/lonlogo_broken.gif';
2554: }
1.617 albertel 2555: }
2556: }
2557:
1.263 www 2558: # -------------------------------------------------------------------- New chat
2559:
2560: sub chatsend {
1.724 raeburn 2561: my ($newentry,$anon,$group)=@_;
1.620 albertel 2562: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2563: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2564: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2565: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2566: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2567: &escape($newentry)).':'.$group,$chome);
1.292 www 2568: }
2569:
2570: # ------------------------------------------ Find current version of a resource
2571:
2572: sub getversion {
2573: my $fname=&clutter(shift);
1.1189 raeburn 2574: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2575: return ¤tversion(&filelocation('',$fname));
2576: }
2577:
2578: sub currentversion {
2579: my $fname=shift;
2580: my $author=$fname;
2581: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2582: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2583: my $home=&homeserver($uname,$udom);
1.292 www 2584: if ($home eq 'no_host') {
2585: return -1;
2586: }
1.1112 www 2587: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2588: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2589: return -1;
2590: }
1.1112 www 2591: return $answer;
1.263 www 2592: }
2593:
1.1111 www 2594: #
2595: # Return special version number of resource if set by override, empty otherwise
2596: #
2597: sub usedversion {
2598: my $fname=shift;
2599: unless ($fname) { $fname=$env{'request.uri'}; }
2600: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2601: if ($urlversion) { return $urlversion; }
2602: return '';
2603: }
2604:
1.1 albertel 2605: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2606:
1.1 albertel 2607: sub subscribe {
2608: my $fname=shift;
1.761 raeburn 2609: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2610: $fname=~s/[\n\r]//g;
1.1 albertel 2611: my $author=$fname;
2612: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2613: my ($udom,$uname)=split(/\//,$author);
2614: my $home=homeserver($uname,$udom);
1.335 albertel 2615: if ($home eq 'no_host') {
2616: return 'not_found';
1.1 albertel 2617: }
2618: my $answer=reply("sub:$fname",$home);
1.64 www 2619: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2620: $answer.=' by '.$home;
2621: }
1.1 albertel 2622: return $answer;
2623: }
2624:
1.8 www 2625: # -------------------------------------------------------------- Replicate file
2626:
2627: sub repcopy {
2628: my $filename=shift;
1.23 www 2629: $filename=~s/\/+/\//g;
1.1142 raeburn 2630: my $londocroot = $perlvar{'lonDocRoot'};
2631: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2632: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2633: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2634: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2635: return &repcopy_userfile($filename);
2636: }
1.532 albertel 2637: $filename=~s/[\n\r]//g;
1.8 www 2638: my $transname="$filename.in.transfer";
1.828 www 2639: # FIXME: this should flock
1.607 raeburn 2640: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2641: my $remoteurl=subscribe($filename);
1.64 www 2642: if ($remoteurl =~ /^con_lost by/) {
2643: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2644: return 'unavailable';
1.8 www 2645: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2646: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2647: return 'not_found';
1.64 www 2648: } elsif ($remoteurl =~ /^rejected by/) {
2649: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2650: return 'forbidden';
1.20 www 2651: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2652: return 'ok';
1.8 www 2653: } else {
1.290 www 2654: my $author=$filename;
2655: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2656: my ($udom,$uname)=split(/\//,$author);
2657: my $home=homeserver($uname,$udom);
2658: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2659: my @parts=split(/\//,$filename);
2660: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2661: if ($path ne "$londocroot/res") {
1.8 www 2662: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2663: return 'bad_request';
1.8 www 2664: }
2665: my $count;
2666: for ($count=5;$count<$#parts;$count++) {
2667: $path.="/$parts[$count]";
2668: if ((-e $path)!=1) {
2669: mkdir($path,0777);
2670: }
2671: }
2672: my $ua=new LWP::UserAgent;
2673: my $request=new HTTP::Request('GET',"$remoteurl");
2674: my $response=$ua->request($request,$transname);
2675: if ($response->is_error()) {
2676: unlink($transname);
2677: my $message=$response->status_line;
1.672 albertel 2678: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2679: ." LWP get: $message: $filename</font>");
1.607 raeburn 2680: return 'unavailable';
1.8 www 2681: } else {
1.16 www 2682: if ($remoteurl!~/\.meta$/) {
2683: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2684: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2685: if ($mresponse->is_error()) {
2686: unlink($filename.'.meta');
2687: &logthis(
1.672 albertel 2688: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2689: }
2690: }
1.8 www 2691: rename($transname,$filename);
1.607 raeburn 2692: return 'ok';
1.8 www 2693: }
1.290 www 2694: }
1.8 www 2695: }
1.330 www 2696: }
2697:
2698: # ------------------------------------------------ Get server side include body
2699: sub ssi_body {
1.381 albertel 2700: my ($filelink,%form)=@_;
1.606 matthew 2701: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2702: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2703: }
1.953 www 2704: my $output='';
2705: my $response;
1.980 raeburn 2706: if ($filelink=~/^https?\:/) {
1.954 raeburn 2707: ($output,$response)=&externalssi($filelink);
1.953 www 2708: } else {
1.1004 droeschl 2709: $filelink .= $filelink=~/\?/ ? '&' : '?';
2710: $filelink .= 'inhibitmenu=yes';
1.953 www 2711: ($output,$response)=&ssi($filelink,%form);
2712: }
1.778 albertel 2713: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2714: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2715: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2716: if (wantarray) {
2717: return ($output, $response);
2718: } else {
2719: return $output;
2720: }
1.8 www 2721: }
2722:
1.15 www 2723: # --------------------------------------------------------- Server Side Include
2724:
1.782 albertel 2725: sub absolute_url {
2726: my ($host_name) = @_;
2727: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2728: if ($host_name eq '') {
2729: $host_name = $ENV{'SERVER_NAME'};
2730: }
2731: return $protocol.$host_name;
2732: }
2733:
1.942 foxr 2734: #
2735: # Server side include.
2736: # Parameters:
2737: # fn Possibly encrypted resource name/id.
2738: # form Hash that describes how the rendering should be done
2739: # and other things.
1.944 foxr 2740: # Returns:
1.950 raeburn 2741: # Scalar context: The content of the response.
2742: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2743: #
1.15 www 2744: sub ssi {
2745:
1.944 foxr 2746: my ($fn,%form)=@_;
1.15 www 2747: my $ua=new LWP::UserAgent;
1.23 www 2748: my $request;
1.711 albertel 2749:
2750: $form{'no_update_last_known'}=1;
1.895 albertel 2751: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2752: if (%form) {
1.782 albertel 2753: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2754: $request->content(join('&',map {
2755: my $name = escape($_);
2756: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2757: ? join("&$name=", map {escape($_) } @{$form{$_}})
2758: : &escape($form{$_}) );
2759: } keys(%form)));
1.23 www 2760: } else {
1.782 albertel 2761: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2762: }
2763:
1.15 www 2764: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2765: my $response= $ua->request($request);
1.1182 foxr 2766: my $content = $response->content;
2767:
2768:
1.944 foxr 2769: if (wantarray) {
1.1173 foxr 2770: return ($content, $response);
1.944 foxr 2771: } else {
1.1173 foxr 2772: return $content;
1.942 foxr 2773: }
1.324 www 2774: }
2775:
2776: sub externalssi {
2777: my ($url)=@_;
2778: my $ua=new LWP::UserAgent;
2779: my $request=new HTTP::Request('GET',$url);
2780: my $response=$ua->request($request);
1.954 raeburn 2781: if (wantarray) {
2782: return ($response->content, $response);
2783: } else {
2784: return $response->content;
2785: }
1.15 www 2786: }
1.254 www 2787:
1.492 albertel 2788: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2789:
2790: sub allowuploaded {
2791: my ($srcurl,$url)=@_;
2792: $url=&clutter(&declutter($url));
2793: my $dir=$url;
2794: $dir=~s/\/[^\/]+$//;
2795: my %httpref=();
2796: my $httpurl=&hreflocation('',$url);
2797: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2798: &Apache::lonnet::appenv(\%httpref);
1.254 www 2799: }
1.477 raeburn 2800:
1.1193 raeburn 2801: #
2802: # Determine if the current user should be able to edit a particular resource,
2803: # when viewing in course context.
2804: # (a) When viewing resource used to determine if "Edit" item is included in
2805: # Functions.
2806: # (b) When displaying folder contents in course editor, used to determine if
2807: # "Edit" link will be displayed alongside resource.
2808: #
1.1196 raeburn 2809: # input: six args -- filename (decluttered), course number, course domain,
2810: # url, symb (if registered) and group (if this is a group
2811: # item -- e.g., bulletin board, group page etc.).
2812: # output: array of five scalars --
1.1193 raeburn 2813: # $cfile -- url for file editing if editable on current server
2814: # $home -- homeserver of resource (i.e., for author if published,
2815: # or course if uploaded.).
2816: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2817: # $forceedit -- 1 if icon/link should be to go to edit mode
2818: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2819: #
2820:
2821: sub can_edit_resource {
1.1194 raeburn 2822: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2823: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2824: #
2825: # For aboutme pages user can only edit his/her own.
2826: #
1.1199 raeburn 2827: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2828: my ($sdom,$sname) = ($1,$2);
2829: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2830: $home = $env{'user.home'};
2831: $cfile = $resurl;
2832: if ($env{'form.forceedit'}) {
2833: $forceview = 1;
2834: } else {
2835: $forceedit = 1;
2836: }
2837: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2838: } else {
2839: return;
2840: }
2841: }
2842:
2843: if ($env{'request.course.id'}) {
2844: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2845: if ($group ne '') {
2846: # if this is a group homepage or group bulletin board, check group privs
2847: my $allowed = 0;
1.1197 raeburn 2848: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2849: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2850: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2851: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2852: $allowed = 1;
2853: }
1.1197 raeburn 2854: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2855: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2856: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2857: $allowed = 1;
2858: }
2859: }
2860: if ($allowed) {
2861: $home=&homeserver($cnum,$cdom);
2862: if ($env{'form.forceedit'}) {
2863: $forceview = 1;
2864: } else {
2865: $forceedit = 1;
2866: }
2867: $cfile = $resurl;
2868: } else {
2869: return;
2870: }
2871: } else {
1.1208 raeburn 2872: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2873: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2874: return;
2875: }
2876: } elsif (!$crsedit) {
1.1194 raeburn 2877: #
2878: # No edit allowed where CC has switched to student role.
2879: #
2880: return;
2881: }
2882: }
2883: }
2884:
1.1193 raeburn 2885: if ($file ne '') {
2886: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2887: if (&is_course_upload($file,$cnum,$cdom)) {
2888: $uploaded = 1;
2889: $incourse = 1;
1.1193 raeburn 2890: if ($file =~/\.(htm|html|css|js|txt)$/) {
2891: $cfile = &hreflocation('',$file);
1.1201 raeburn 2892: if ($env{'form.forceedit'}) {
2893: $forceview = 1;
2894: } else {
2895: $forceedit = 1;
2896: }
1.1194 raeburn 2897: }
2898: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2899: $incourse = 1;
2900: if ($env{'form.forceedit'}) {
2901: $forceview = 1;
2902: } else {
2903: $forceedit = 1;
2904: }
2905: $cfile = $resurl;
2906: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2907: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2908: $incourse = 1;
2909: if ($env{'form.forceedit'}) {
2910: $forceview = 1;
2911: } else {
2912: $forceedit = 1;
2913: }
2914: $cfile = $resurl;
1.1199 raeburn 2915: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2916: $incourse = 1;
2917: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2918: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2919: $incourse = 1;
1.1199 raeburn 2920: if ($env{'form.forceedit'}) {
2921: $forceview = 1;
2922: } else {
2923: $forceedit = 1;
2924: }
2925: $cfile = $resurl;
1.1208 raeburn 2926: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2927: $incourse = 1;
2928: if ($env{'form.forceedit'}) {
2929: $forceview = 1;
2930: } else {
2931: $forceedit = 1;
2932: }
2933: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2934: }
2935: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2936: my $template = '/res/lib/templates/simpleproblem.problem';
2937: if (&is_on_map($template)) {
2938: $incourse = 1;
2939: $forceview = 1;
2940: $cfile = $template;
1.1193 raeburn 2941: }
1.1199 raeburn 2942: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2943: $incourse = 1;
2944: if ($env{'form.forceedit'}) {
2945: $forceview = 1;
2946: } else {
2947: $forceedit = 1;
2948: }
2949: $cfile = $resurl;
2950: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2951: $incourse = 1;
2952: $forceview = 1;
2953: if ($symb) {
2954: my ($map,$id,$res)=&decode_symb($symb);
2955: $env{'request.symb'} = $symb;
2956: $cfile = &clutter($res);
2957: } else {
2958: $cfile = $env{'form.suppurl'};
2959: $cfile =~ s{^http://}{};
2960: $cfile = '/adm/wrapper/ext/'.$cfile;
2961: }
1.1234 raeburn 2962: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2963: if ($env{'form.forceedit'}) {
2964: $forceview = 1;
2965: } else {
2966: $forceedit = 1;
2967: }
2968: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2969: }
2970: }
1.1194 raeburn 2971: if ($uploaded || $incourse) {
2972: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2973: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2974: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2975: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2976: # Check that the user has permission to edit this resource
2977: my $setpriv = 1;
2978: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2979: if (defined($cfudom)) {
2980: $home=&homeserver($cfuname,$cfudom);
2981: $cfile=$file;
2982: }
2983: }
1.1194 raeburn 2984: if (($cfile ne '') && (!$incourse || $uploaded) &&
2985: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2986: my @ids=¤t_machine_ids();
2987: unless (grep(/^\Q$home\E$/,@ids)) {
2988: $switchserver=1;
2989: }
2990: }
2991: }
1.1194 raeburn 2992: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2993: }
2994:
2995: sub is_course_upload {
2996: my ($file,$cnum,$cdom) = @_;
2997: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2998: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2999: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3000: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3001: return 1;
3002: }
3003: return;
3004: }
3005:
1.1194 raeburn 3006: sub in_course {
1.1195 raeburn 3007: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3008: if ($hideprivileged) {
3009: my $skipuser;
1.1219 raeburn 3010: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3011: my @possdoms = ($cdom);
3012: if ($coursehash{'checkforpriv'}) {
3013: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3014: }
3015: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3016: $skipuser = 1;
3017: if ($coursehash{'nothideprivileged'}) {
3018: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3019: my $user;
3020: if ($item =~ /:/) {
3021: $user = $item;
3022: } else {
3023: $user = join(':',split(/[\@]/,$item));
3024: }
3025: if ($user eq $uname.':'.$udom) {
3026: undef($skipuser);
3027: last;
3028: }
3029: }
3030: }
3031: if ($skipuser) {
3032: return 0;
3033: }
3034: }
3035: }
1.1194 raeburn 3036: $type ||= 'any';
3037: if (!defined($cdom) || !defined($cnum)) {
3038: my $cid = $env{'request.course.id'};
3039: $cdom = $env{'course.'.$cid.'.domain'};
3040: $cnum = $env{'course.'.$cid.'.num'};
3041: }
3042: my $typesref;
1.1195 raeburn 3043: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3044: $typesref = ['active','previous','future'];
3045: } elsif ($type eq 'previous' || $type eq 'future') {
3046: $typesref = [$type];
3047: }
3048: my %roles = &get_my_roles($uname,$udom,'userroles',
3049: $typesref,undef,[$cdom]);
3050: my ($tmp) = keys(%roles);
3051: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3052: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3053: if (@course_roles > 0) {
3054: return 1;
3055: }
3056: return 0;
3057: }
3058:
1.478 albertel 3059: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3060: # input: action, courseID, current domain, intended
1.637 raeburn 3061: # path to file, source of file, instruction to parse file for objects,
3062: # ref to hash for embedded objects,
3063: # ref to hash for codebase of java objects.
1.1095 raeburn 3064: # reference to scalar to accommodate mime type determined
3065: # from File::MMagic if $parser = parse.
1.637 raeburn 3066: #
1.485 raeburn 3067: # output: url to file (if action was uploaddoc),
3068: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3069: #
1.478 albertel 3070: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3071: # course.
1.477 raeburn 3072: #
1.478 albertel 3073: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3074: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3075: # course's home server.
1.477 raeburn 3076: #
1.478 albertel 3077: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3078: # be copied from $source (current location) to
3079: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3080: # and will then be copied to
3081: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3082: # course's home server.
1.485 raeburn 3083: #
1.481 raeburn 3084: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3085: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3086: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3087: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3088: # in course's home server.
1.637 raeburn 3089: #
1.477 raeburn 3090:
3091: sub process_coursefile {
1.1095 raeburn 3092: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3093: $mimetype)=@_;
1.477 raeburn 3094: my $fetchresult;
1.638 albertel 3095: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3096: if ($action eq 'propagate') {
1.638 albertel 3097: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3098: $home);
1.481 raeburn 3099: } else {
1.477 raeburn 3100: my $fpath = '';
3101: my $fname = $file;
1.478 albertel 3102: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3103: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3104: my $filepath = &build_filepath($fpath);
1.481 raeburn 3105: if ($action eq 'copy') {
3106: if ($source eq '') {
3107: $fetchresult = 'no source file';
3108: return $fetchresult;
3109: } else {
3110: my $destination = $filepath.'/'.$fname;
3111: rename($source,$destination);
3112: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3113: $home);
1.481 raeburn 3114: }
3115: } elsif ($action eq 'uploaddoc') {
3116: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3117: print $fh $env{'form.'.$source};
1.481 raeburn 3118: close($fh);
1.637 raeburn 3119: if ($parser eq 'parse') {
1.1024 raeburn 3120: my $mm = new File::MMagic;
1.1095 raeburn 3121: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3122: if ($type eq 'text/html') {
1.1024 raeburn 3123: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3124: unless ($parse_result eq 'ok') {
3125: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3126: }
1.637 raeburn 3127: }
1.1095 raeburn 3128: if (ref($mimetype)) {
3129: $$mimetype = $type;
3130: }
1.637 raeburn 3131: }
1.477 raeburn 3132: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3133: $home);
1.481 raeburn 3134: if ($fetchresult eq 'ok') {
3135: return '/uploaded/'.$fpath.'/'.$fname;
3136: } else {
3137: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3138: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3139: return '/adm/notfound.html';
3140: }
1.477 raeburn 3141: }
3142: }
1.485 raeburn 3143: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3144: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3145: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3146: }
3147: return $fetchresult;
3148: }
3149:
1.637 raeburn 3150: sub build_filepath {
3151: my ($fpath) = @_;
3152: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3153: unless ($fpath eq '') {
3154: my @parts=split('/',$fpath);
3155: foreach my $part (@parts) {
3156: $filepath.= '/'.$part;
3157: if ((-e $filepath)!=1) {
3158: mkdir($filepath,0777);
3159: }
3160: }
3161: }
3162: return $filepath;
3163: }
3164:
3165: sub store_edited_file {
1.638 albertel 3166: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3167: my $file = $primary_url;
3168: $file =~ s#^/uploaded/$docudom/$docuname/##;
3169: my $fpath = '';
3170: my $fname = $file;
3171: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3172: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3173: my $filepath = &build_filepath($fpath);
3174: open(my $fh,'>'.$filepath.'/'.$fname);
3175: print $fh $content;
3176: close($fh);
1.638 albertel 3177: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3178: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3179: $home);
1.637 raeburn 3180: if ($$fetchresult eq 'ok') {
3181: return '/uploaded/'.$fpath.'/'.$fname;
3182: } else {
1.638 albertel 3183: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3184: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3185: return '/adm/notfound.html';
3186: }
3187: }
3188:
1.531 albertel 3189: sub clean_filename {
1.831 albertel 3190: my ($fname,$args)=@_;
1.315 www 3191: # Replace Windows backslashes by forward slashes
1.257 www 3192: $fname=~s/\\/\//g;
1.831 albertel 3193: if (!$args->{'keep_path'}) {
3194: # Get rid of everything but the actual filename
3195: $fname=~s/^.*\/([^\/]+)$/$1/;
3196: }
1.315 www 3197: # Replace spaces by underscores
3198: $fname=~s/\s+/\_/g;
3199: # Replace all other weird characters by nothing
1.831 albertel 3200: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3201: # Replace all .\d. sequences with _\d. so they no longer look like version
3202: # numbers
3203: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3204: return $fname;
3205: }
1.1051 raeburn 3206: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3207: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3208: # image with the same aspect ratio as the original, but with dimensions which do
3209: # not exceed $resizewidth and $resizeheight.
3210:
1.984 neumanie 3211: sub resizeImage {
1.1051 raeburn 3212: my ($img_path,$resizewidth,$resizeheight) = @_;
3213: my $ima = Image::Magick->new;
3214: my $resized;
3215: if (-e $img_path) {
3216: $ima->Read($img_path);
3217: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3218: my $width = $ima->Get('width');
3219: my $height = $ima->Get('height');
3220: if ($width > $resizewidth) {
3221: my $factor = $width/$resizewidth;
3222: my $newheight = $height/$factor;
3223: $ima->Scale(width=>$resizewidth,height=>$newheight);
3224: $resized = 1;
3225: }
3226: }
3227: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3228: my $width = $ima->Get('width');
3229: my $height = $ima->Get('height');
3230: if ($height > $resizeheight) {
3231: my $factor = $height/$resizeheight;
3232: my $newwidth = $width/$factor;
3233: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3234: $resized = 1;
3235: }
3236: }
3237: if ($resized) {
3238: $ima->Write($img_path);
3239: }
3240: }
3241: return;
1.977 amueller 3242: }
3243:
1.608 albertel 3244: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3245: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3246: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3247: # $context - possible values: coursedoc, existingfile, overwrite,
3248: # canceloverwrite, or ''.
3249: # if 'coursedoc': upload to the current course
3250: # if 'existingfile': write file to tmp/overwrites directory
3251: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3252: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3253: # $subdir - directory in userfile to store the file into
1.858 raeburn 3254: # $parser - instruction to parse file for objects ($parser = parse)
3255: # $allfiles - reference to hash for embedded objects
3256: # $codebase - reference to hash for codebase of java objects
3257: # $desuname - username for permanent storage of uploaded file
3258: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3259: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3260: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3261: # $resizewidth - width (pixels) to which to resize uploaded image
3262: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3263: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3264: # from File::MMagic.
1.858 raeburn 3265: #
1.686 albertel 3266: # output: url of file in userspace, or error: <message>
3267: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3268:
1.531 albertel 3269: sub userfileupload {
1.1090 raeburn 3270: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3271: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3272: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3273: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3274: $fname=&clean_filename($fname);
1.1090 raeburn 3275: # See if there is anything left
1.257 www 3276: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3277: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3278: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3279: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3280: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3281: my $now = time;
1.1090 raeburn 3282: my $filepath;
1.1095 raeburn 3283: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3284: $filepath = 'tmp/helprequests/'.$now;
3285: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3286: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3287: '_'.$env{'user.domain'}.'/pending';
3288: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3289: my ($docuname,$docudom);
3290: if ($destudom) {
3291: $docudom = $destudom;
3292: } else {
3293: $docudom = $env{'user.domain'};
3294: }
3295: if ($destuname) {
3296: $docuname = $destuname;
3297: } else {
3298: $docuname = $env{'user.name'};
3299: }
3300: if (exists($env{'form.group'})) {
3301: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3302: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3303: }
3304: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3305: if ($context eq 'canceloverwrite') {
3306: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3307: if (-e $tempfile) {
3308: my @info = stat($tempfile);
3309: if ($info[9] eq $env{'form.timestamp'}) {
3310: unlink($tempfile);
3311: }
3312: }
3313: return;
1.523 raeburn 3314: }
3315: }
1.1090 raeburn 3316: # Create the directory if not present
1.741 raeburn 3317: my @parts=split(/\//,$filepath);
3318: my $fullpath = $perlvar{'lonDaemons'};
3319: for (my $i=0;$i<@parts;$i++) {
3320: $fullpath .= '/'.$parts[$i];
3321: if ((-e $fullpath)!=1) {
3322: mkdir($fullpath,0777);
3323: }
3324: }
3325: open(my $fh,'>'.$fullpath.'/'.$fname);
3326: print $fh $env{'form.'.$formname};
3327: close($fh);
1.1090 raeburn 3328: if ($context eq 'existingfile') {
3329: my @info = stat($fullpath.'/'.$fname);
3330: return ($fullpath.'/'.$fname,$info[9]);
3331: } else {
3332: return $fullpath.'/'.$fname;
3333: }
1.523 raeburn 3334: }
1.995 raeburn 3335: if ($subdir eq 'scantron') {
3336: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3337: } else {
1.995 raeburn 3338: $fname="$subdir/$fname";
3339: }
1.1090 raeburn 3340: if ($context eq 'coursedoc') {
1.638 albertel 3341: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3342: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3343: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3344: return &finishuserfileupload($docuname,$docudom,
3345: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3346: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3347: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3348: } else {
1.1218 raeburn 3349: if ($env{'form.folder'}) {
3350: $fname=$env{'form.folder'}.'/'.$fname;
3351: }
1.638 albertel 3352: return &process_coursefile('uploaddoc',$docuname,$docudom,
3353: $fname,$formname,$parser,
1.1095 raeburn 3354: $allfiles,$codebase,$mimetype);
1.481 raeburn 3355: }
1.719 banghart 3356: } elsif (defined($destuname)) {
3357: my $docuname=$destuname;
3358: my $docudom=$destudom;
1.860 raeburn 3359: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3360: $parser,$allfiles,$codebase,
1.1051 raeburn 3361: $thumbwidth,$thumbheight,
1.1095 raeburn 3362: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3363: } else {
1.638 albertel 3364: my $docuname=$env{'user.name'};
3365: my $docudom=$env{'user.domain'};
1.1220 raeburn 3366: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3367: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3368: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3369: }
1.860 raeburn 3370: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3371: $parser,$allfiles,$codebase,
1.1051 raeburn 3372: $thumbwidth,$thumbheight,
1.1095 raeburn 3373: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3374: }
1.271 www 3375: }
3376:
3377: sub finishuserfileupload {
1.860 raeburn 3378: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3379: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3380: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3381: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3382:
1.860 raeburn 3383: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3384: $file=$fname;
3385: if ($fname=~m|/|) {
3386: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3387: $path.=$fnamepath.'/';
3388: }
1.259 www 3389: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3390: my $count;
3391: for ($count=4;$count<=$#parts;$count++) {
3392: $filepath.="/$parts[$count]";
3393: if ((-e $filepath)!=1) {
3394: mkdir($filepath,0777);
3395: }
3396: }
1.984 neumanie 3397:
1.258 www 3398: # Save the file
3399: {
1.701 albertel 3400: if (!open(FH,'>'.$filepath.'/'.$file)) {
3401: &logthis('Failed to create '.$filepath.'/'.$file);
3402: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3403: return '/adm/notfound.html';
3404: }
1.1090 raeburn 3405: if ($context eq 'overwrite') {
1.1117 foxr 3406: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3407: my $target = $filepath.'/'.$file;
3408: if (-e $source) {
3409: my @info = stat($source);
3410: if ($info[9] eq $env{'form.timestamp'}) {
3411: unless (&File::Copy::move($source,$target)) {
3412: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3413: return "Moving from $source failed";
3414: }
3415: } else {
3416: return "Temporary file: $source had unexpected date/time for last modification";
3417: }
3418: } else {
3419: return "Temporary file: $source missing";
3420: }
3421: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3422: &logthis('Failed to write to '.$filepath.'/'.$file);
3423: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3424: return '/adm/notfound.html';
3425: }
1.570 albertel 3426: close(FH);
1.1051 raeburn 3427: if ($resizewidth && $resizeheight) {
3428: my $mm = new File::MMagic;
3429: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3430: if ($mime_type =~ m{^image/}) {
3431: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3432: }
1.977 amueller 3433: }
1.258 www 3434: }
1.1152 raeburn 3435: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3436: if (ref($mimetype)) {
3437: if ($$mimetype eq '') {
3438: my $mm = new File::MMagic;
3439: my $type = $mm->checktype_filename($filepath.'/'.$file);
3440: $$mimetype = $type;
3441: }
3442: }
3443: }
1.637 raeburn 3444: if ($parser eq 'parse') {
1.1152 raeburn 3445: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3446: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3447: $allfiles,$codebase);
3448: unless ($parse_result eq 'ok') {
3449: &logthis('Failed to parse '.$filepath.$file.
3450: ' for embedded media: '.$parse_result);
3451: }
1.637 raeburn 3452: }
3453: }
1.860 raeburn 3454: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3455: my $input = $filepath.'/'.$file;
3456: my $output = $filepath.'/'.'tn-'.$file;
3457: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3458: system("convert -sample $thumbsize $input $output");
3459: if (-e $filepath.'/'.'tn-'.$file) {
3460: $fetchthumb = 1;
3461: }
3462: }
1.858 raeburn 3463:
1.259 www 3464: # Notify homeserver to grep it
3465: #
1.984 neumanie 3466: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3467: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3468: if ($fetchresult eq 'ok') {
1.860 raeburn 3469: if ($fetchthumb) {
3470: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3471: if ($thumbresult ne 'ok') {
3472: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3473: $docuhome.': '.$thumbresult);
3474: }
3475: }
1.259 www 3476: #
1.258 www 3477: # Return the URL to it
1.494 albertel 3478: return '/uploaded/'.$path.$file;
1.263 www 3479: } else {
1.494 albertel 3480: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3481: ': '.$fetchresult);
1.263 www 3482: return '/adm/notfound.html';
1.858 raeburn 3483: }
1.493 albertel 3484: }
3485:
1.637 raeburn 3486: sub extract_embedded_items {
1.961 raeburn 3487: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3488: my @state = ();
1.1164 raeburn 3489: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3490: my %javafiles = (
3491: codebase => '',
3492: code => '',
3493: archive => ''
3494: );
3495: my %mediafiles = (
3496: src => '',
3497: movie => '',
3498: );
1.648 raeburn 3499: my $p;
3500: if ($content) {
3501: $p = HTML::LCParser->new($content);
3502: } else {
1.961 raeburn 3503: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3504: }
1.641 albertel 3505: while (my $t=$p->get_token()) {
1.640 albertel 3506: if ($t->[0] eq 'S') {
3507: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3508: push(@state, $tagname);
1.648 raeburn 3509: if (lc($tagname) eq 'allow') {
3510: &add_filetype($allfiles,$attr->{'src'},'src');
3511: }
1.640 albertel 3512: if (lc($tagname) eq 'img') {
3513: &add_filetype($allfiles,$attr->{'src'},'src');
3514: }
1.886 albertel 3515: if (lc($tagname) eq 'a') {
1.1222 raeburn 3516: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3517: &add_filetype($allfiles,$attr->{'href'},'href');
3518: }
1.886 albertel 3519: }
1.645 raeburn 3520: if (lc($tagname) eq 'script') {
1.1164 raeburn 3521: my $src;
1.645 raeburn 3522: if ($attr->{'archive'} =~ /\.jar$/i) {
3523: &add_filetype($allfiles,$attr->{'archive'},'archive');
3524: } else {
1.1164 raeburn 3525: if ($attr->{'src'} ne '') {
3526: $src = $attr->{'src'};
3527: &add_filetype($allfiles,$src,'src');
3528: }
3529: }
3530: my $text = $p->get_trimmed_text();
3531: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3532: my @swfargs = split(/,/,$1);
3533: foreach my $item (@swfargs) {
3534: $item =~ s/["']//g;
3535: $item =~ s/^\s+//;
3536: $item =~ s/\s+$//;
3537: }
3538: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3539: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3540: push(@{$related{$swfargs[0]}},$swfargs[2]);
3541: } else {
3542: $related{$swfargs[0]} = [$swfargs[2]];
3543: }
3544: }
1.645 raeburn 3545: }
3546: }
3547: if (lc($tagname) eq 'link') {
3548: if (lc($attr->{'rel'}) eq 'stylesheet') {
3549: &add_filetype($allfiles,$attr->{'href'},'href');
3550: }
3551: }
1.640 albertel 3552: if (lc($tagname) eq 'object' ||
3553: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3554: foreach my $item (keys(%javafiles)) {
3555: $javafiles{$item} = '';
3556: }
1.1164 raeburn 3557: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3558: $lastids{lc($tagname)} = $attr->{'id'};
3559: }
1.640 albertel 3560: }
3561: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3562: my $name = lc($attr->{'name'});
3563: foreach my $item (keys(%javafiles)) {
3564: if ($name eq $item) {
3565: $javafiles{$item} = $attr->{'value'};
3566: last;
3567: }
3568: }
1.1164 raeburn 3569: my $pathfrom;
1.640 albertel 3570: foreach my $item (keys(%mediafiles)) {
3571: if ($name eq $item) {
1.1164 raeburn 3572: $pathfrom = $attr->{'value'};
3573: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3574: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3575: last;
3576: }
3577: }
1.1164 raeburn 3578: if ($name eq 'flashvars') {
3579: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3580: }
3581: if ($pathfrom ne '') {
3582: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3583: $pathfrom);
3584: }
1.640 albertel 3585: }
3586: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3587: foreach my $item (keys(%javafiles)) {
3588: if ($attr->{$item}) {
3589: $javafiles{$item} = $attr->{$item};
3590: last;
3591: }
3592: }
3593: foreach my $item (keys(%mediafiles)) {
3594: if ($attr->{$item}) {
3595: &add_filetype($allfiles,$attr->{$item},$item);
3596: last;
3597: }
3598: }
1.1164 raeburn 3599: if (lc($tagname) eq 'embed') {
3600: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3601: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3602: $attr->{'src'});
3603: }
3604: }
1.640 albertel 3605: }
1.1243 raeburn 3606: if (lc($tagname) eq 'iframe') {
3607: my $src = $attr->{'src'} ;
3608: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3609: &add_filetype($allfiles,$src,'src');
3610: } elsif ($src =~ m{^/}) {
3611: if ($env{'request.course.id'}) {
3612: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3613: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3614: my $url = &hreflocation('',$fullpath);
3615: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3616: my $relpath = $1;
3617: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3618: &add_filetype($allfiles,$1,'src');
3619: }
3620: }
3621: }
3622: }
3623: }
1.1164 raeburn 3624: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3625: pop(@state);
1.1164 raeburn 3626: }
1.640 albertel 3627: } elsif ($t->[0] eq 'E') {
3628: my ($tagname) = ($t->[1]);
3629: if ($javafiles{'codebase'} ne '') {
3630: $javafiles{'codebase'} .= '/';
3631: }
3632: if (lc($tagname) eq 'applet' ||
3633: lc($tagname) eq 'object' ||
3634: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3635: ) {
3636: foreach my $item (keys(%javafiles)) {
3637: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3638: my $file=$javafiles{'codebase'}.$javafiles{$item};
3639: &add_filetype($allfiles,$file,$item);
3640: }
3641: }
3642: }
3643: pop @state;
3644: }
3645: }
1.1164 raeburn 3646: foreach my $id (sort(keys(%flashvars))) {
3647: if ($shockwave{$id} ne '') {
3648: my @pairs = split(/\&/,$flashvars{$id});
3649: foreach my $pair (@pairs) {
3650: my ($key,$value) = split(/\=/,$pair);
3651: if ($key eq 'thumb') {
3652: &add_filetype($allfiles,$value,$key);
3653: } elsif ($key eq 'content') {
3654: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3655: my ($ext) = ($value =~ /\.([^.]+)$/);
3656: if ($ext ne '') {
3657: &add_filetype($allfiles,$path.$value,$ext);
3658: }
3659: }
3660: }
3661: }
3662: }
1.637 raeburn 3663: return 'ok';
3664: }
3665:
1.639 albertel 3666: sub add_filetype {
3667: my ($allfiles,$file,$type)=@_;
3668: if (exists($allfiles->{$file})) {
3669: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3670: push(@{$allfiles->{$file}}, &escape($type));
3671: }
3672: } else {
3673: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3674: }
3675: }
3676:
1.1164 raeburn 3677: sub embedded_dependency {
3678: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3679: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3680: if (($identifier ne '') &&
3681: (ref($related->{$identifier}) eq 'ARRAY') &&
3682: ($pathfrom ne '')) {
3683: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3684: foreach my $dep (@{$related->{$identifier}}) {
3685: &add_filetype($allfiles,$path.$dep,'object');
3686: }
3687: }
3688: }
3689: return;
3690: }
3691:
1.493 albertel 3692: sub removeuploadedurl {
1.984 neumanie 3693: my ($url)=@_;
3694: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3695: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3696: }
3697:
3698: sub removeuserfile {
3699: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3700: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3701: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3702: if ($result eq 'ok') {
1.798 raeburn 3703: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3704: my $metafile = $fname.'.meta';
3705: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3706: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3707: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3708: my $sqlresult =
1.823 albertel 3709: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3710: 'portfolio_metadata',$group,
3711: 'delete');
1.798 raeburn 3712: }
3713: }
3714: return $result;
1.257 www 3715: }
1.15 www 3716:
1.530 albertel 3717: sub mkdiruserfile {
3718: my ($docuname,$docudom,$dir)=@_;
3719: my $home=&homeserver($docuname,$docudom);
3720: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3721: }
3722:
1.531 albertel 3723: sub renameuserfile {
3724: my ($docuname,$docudom,$old,$new)=@_;
3725: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3726: my $result = &reply("renameuserfile:$docudom:$docuname:".
3727: &escape("$old").':'.&escape("$new"),$home);
3728: if ($result eq 'ok') {
3729: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3730: my $oldmeta = $old.'.meta';
3731: my $newmeta = $new.'.meta';
3732: my $metaresult =
3733: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3734: my $url = "/uploaded/$docudom/$docuname/$old";
3735: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3736: my $sqlresult =
1.823 albertel 3737: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3738: 'portfolio_metadata',$group,
3739: 'delete');
1.798 raeburn 3740: }
3741: }
3742: return $result;
1.531 albertel 3743: }
3744:
1.14 www 3745: # ------------------------------------------------------------------------- Log
3746:
3747: sub log {
3748: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3749: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3750: }
3751:
3752: # ------------------------------------------------------------------ Course Log
1.352 www 3753: #
3754: # This routine flushes several buffers of non-mission-critical nature
3755: #
1.157 www 3756:
3757: sub flushcourselogs {
1.352 www 3758: &logthis('Flushing log buffers');
3759: #
3760: # course logs
3761: # This is a log of all transactions in a course, which can be used
3762: # for data mining purposes
3763: #
3764: # It also collects the courseid database, which lists last transaction
3765: # times and course titles for all courseids
3766: #
3767: my %courseidbuffer=();
1.921 raeburn 3768: foreach my $crsid (keys(%courselogs)) {
1.352 www 3769: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3770: &escape($courselogs{$crsid}),
3771: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3772: delete $courselogs{$crsid};
3773: } else {
3774: &logthis('Failed to flush log buffer for '.$crsid);
3775: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3776: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3777: " exceeded maximum size, deleting.</font>");
3778: delete $courselogs{$crsid};
3779: }
1.352 www 3780: }
1.920 raeburn 3781: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3782: 'description' => $coursedescrbuf{$crsid},
3783: 'inst_code' => $courseinstcodebuf{$crsid},
3784: 'type' => $coursetypebuf{$crsid},
3785: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3786: };
1.191 harris41 3787: }
1.352 www 3788: #
3789: # Write course id database (reverse lookup) to homeserver of courses
3790: # Is used in pickcourse
3791: #
1.840 albertel 3792: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3793: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3794: $courseidbuffer{$crs_home},
3795: $crs_home,'timeonly');
1.352 www 3796: }
3797: #
3798: # File accesses
3799: # Writes to the dynamic metadata of resources to get hit counts, etc.
3800: #
1.449 matthew 3801: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3802: if ($entry =~ /___count$/) {
3803: my ($dom,$name);
1.807 albertel 3804: ($dom,$name,undef)=
1.811 albertel 3805: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3806: if (! defined($dom) || $dom eq '' ||
3807: ! defined($name) || $name eq '') {
1.620 albertel 3808: my $cid = $env{'request.course.id'};
3809: $dom = $env{'request.'.$cid.'.domain'};
3810: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3811: }
1.450 matthew 3812: my $value = $accesshash{$entry};
3813: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3814: my %temphash=($url => $value);
1.449 matthew 3815: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3816: if ($result eq 'ok') {
3817: delete $accesshash{$entry};
3818: }
3819: } else {
1.811 albertel 3820: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3821: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3822: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3823: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3824: delete $accesshash{$entry};
3825: }
1.185 www 3826: }
1.191 harris41 3827: }
1.352 www 3828: #
3829: # Roles
3830: # Reverse lookup of user roles for course faculty/staff and co-authorship
3831: #
1.800 albertel 3832: foreach my $entry (keys(%userrolehash)) {
1.351 www 3833: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3834: split(/\:/,$entry);
3835: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3836: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3837: $rudom,$runame) eq 'ok') {
3838: delete $userrolehash{$entry};
3839: }
3840: }
1.662 raeburn 3841: #
3842: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3843: #
3844: my %domrolebuffer = ();
1.1000 raeburn 3845: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3846: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3847: if ($domrolebuffer{$rudom}) {
3848: $domrolebuffer{$rudom}.='&'.&escape($entry).
3849: '='.&escape($domainrolehash{$entry});
3850: } else {
3851: $domrolebuffer{$rudom}.=&escape($entry).
3852: '='.&escape($domainrolehash{$entry});
3853: }
3854: delete $domainrolehash{$entry};
3855: }
3856: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3857: my %servers = &get_servers($dom,'library');
3858: foreach my $tryserver (keys(%servers)) {
3859: unless (&reply('domroleput:'.$dom.':'.
3860: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3861: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3862: }
1.662 raeburn 3863: }
3864: }
1.186 www 3865: $dumpcount++;
1.157 www 3866: }
3867:
3868: sub courselog {
3869: my $what=shift;
1.158 www 3870: $what=time.':'.$what;
1.620 albertel 3871: unless ($env{'request.course.id'}) { return ''; }
3872: $coursedombuf{$env{'request.course.id'}}=
3873: $env{'course.'.$env{'request.course.id'}.'.domain'};
3874: $coursenumbuf{$env{'request.course.id'}}=
3875: $env{'course.'.$env{'request.course.id'}.'.num'};
3876: $coursehombuf{$env{'request.course.id'}}=
3877: $env{'course.'.$env{'request.course.id'}.'.home'};
3878: $coursedescrbuf{$env{'request.course.id'}}=
3879: $env{'course.'.$env{'request.course.id'}.'.description'};
3880: $courseinstcodebuf{$env{'request.course.id'}}=
3881: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3882: $courseownerbuf{$env{'request.course.id'}}=
3883: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3884: $coursetypebuf{$env{'request.course.id'}}=
3885: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3886: if (defined $courselogs{$env{'request.course.id'}}) {
3887: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3888: } else {
1.620 albertel 3889: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3890: }
1.620 albertel 3891: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3892: &flushcourselogs();
3893: }
1.158 www 3894: }
3895:
3896: sub courseacclog {
3897: my $fnsymb=shift;
1.620 albertel 3898: unless ($env{'request.course.id'}) { return ''; }
3899: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3900: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3901: $what.=':POST';
1.583 matthew 3902: # FIXME: Probably ought to escape things....
1.800 albertel 3903: foreach my $key (keys(%env)) {
3904: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3905: my $formitem = $1;
3906: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3907: $what.=':'.$formitem.'='.$env{$key};
3908: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3909: $what.=':'.$formitem.'='.$env{$key};
3910: }
1.158 www 3911: }
1.191 harris41 3912: }
1.583 matthew 3913: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3914: # FIXME: We should not be depending on a form parameter that someone
3915: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3916: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3917: $what.= ':POST';
3918: # FIXME: Probably ought to escape things....
3919: foreach my $element ('courseexp','crsfulltext','crsrelated',
3920: 'crsdiscuss') {
1.620 albertel 3921: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3922: }
3923: }
1.158 www 3924: }
3925: &courselog($what);
1.149 www 3926: }
3927:
1.185 www 3928: sub countacc {
3929: my $url=&declutter(shift);
1.458 matthew 3930: return if (! defined($url) || $url eq '');
1.620 albertel 3931: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3932: #
3933: # Mark that this url was used in this course
3934: #
1.620 albertel 3935: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3936: #
3937: # Increase the access count for this resource in this child process
3938: #
1.281 www 3939: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3940: $accesshash{$key}++;
1.185 www 3941: }
1.349 www 3942:
1.361 www 3943: sub linklog {
3944: my ($from,$to)=@_;
3945: $from=&declutter($from);
3946: $to=&declutter($to);
3947: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3948: $accesshash{$to.'___'.$from.'___goto'}=1;
3949: }
1.1160 www 3950:
3951: sub statslog {
3952: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3953: if ($users<2) { return; }
3954: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3955: 'course' => $env{'request.course.id'},
3956: 'sections' => '"all"',
3957: 'num_students' => $users,
3958: 'part' => $part,
3959: 'symb' => $symb,
3960: 'mean_tries' => $av_attempts,
3961: 'deg_of_diff' => $degdiff});
3962: foreach my $key (keys(%dynstore)) {
3963: $accesshash{$key}=$dynstore{$key};
3964: }
3965: }
1.361 www 3966:
1.349 www 3967: sub userrolelog {
3968: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3969: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3970: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3971: $userrolehash
3972: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3973: =$tend.':'.$tstart;
1.662 raeburn 3974: }
1.1169 droeschl 3975: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3976: $userrolehash
3977: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3978: =$tend.':'.$tstart;
3979: }
1.1169 droeschl 3980: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3981: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3982: $domainrolehash
3983: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3984: = $tend.':'.$tstart;
3985: }
1.351 www 3986: }
3987:
1.957 raeburn 3988: sub courserolelog {
3989: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3990: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3991: my $cdom = $1;
3992: my $cnum = $2;
3993: my $sec = $3;
3994: my $namespace = 'rolelog';
3995: my %storehash = (
3996: role => $trole,
3997: start => $tstart,
3998: end => $tend,
3999: selfenroll => $selfenroll,
4000: context => $context,
4001: );
4002: if ($trole eq 'gr') {
4003: $namespace = 'groupslog';
4004: $storehash{'group'} = $sec;
4005: } else {
4006: $storehash{'section'} = $sec;
4007: }
1.1188 raeburn 4008: &write_log('course',$namespace,\%storehash,$delflag,$username,
4009: $domain,$cnum,$cdom);
1.1184 raeburn 4010: if (($trole ne 'st') || ($sec ne '')) {
4011: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4012: }
4013: }
4014: return;
4015: }
4016:
1.1184 raeburn 4017: sub domainrolelog {
4018: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4019: if ($area =~ m{^/($match_domain)/$}) {
4020: my $cdom = $1;
4021: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4022: my $namespace = 'rolelog';
4023: my %storehash = (
4024: role => $trole,
4025: start => $tstart,
4026: end => $tend,
4027: context => $context,
4028: );
1.1188 raeburn 4029: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4030: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4031: }
4032: return;
4033:
4034: }
4035:
4036: sub coauthorrolelog {
4037: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4038: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4039: my $audom = $1;
4040: my $auname = $2;
4041: my $namespace = 'rolelog';
4042: my %storehash = (
4043: role => $trole,
4044: start => $tstart,
4045: end => $tend,
4046: context => $context,
4047: );
1.1188 raeburn 4048: &write_log('author',$namespace,\%storehash,$delflag,$username,
4049: $domain,$auname,$audom);
1.1184 raeburn 4050: }
4051: return;
4052: }
4053:
1.351 www 4054: sub get_course_adv_roles {
1.948 raeburn 4055: my ($cid,$codes) = @_;
1.620 albertel 4056: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4057: my %coursehash=&coursedescription($cid);
1.988 raeburn 4058: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4059: my %nothide=();
1.800 albertel 4060: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4061: if ($user !~ /:/) {
4062: $nothide{join(':',split(/[\@]/,$user))}=1;
4063: } else {
4064: $nothide{$user}=1;
4065: }
1.470 www 4066: }
1.1219 raeburn 4067: my @possdoms = ($coursehash{'domain'});
4068: if ($coursehash{'checkforpriv'}) {
4069: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4070: }
1.351 www 4071: my %returnhash=();
4072: my %dumphash=
4073: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4074: my $now=time;
1.997 raeburn 4075: my %privileged;
1.1000 raeburn 4076: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4077: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4078: if (($tstart) && ($tstart<0)) { next; }
4079: if (($tend) && ($tend<$now)) { next; }
4080: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4081: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4082: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4083: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4084: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4085: if ($role eq 'cr') { next; }
1.948 raeburn 4086: if ($codes) {
4087: if ($section) { $role .= ':'.$section; }
4088: if ($returnhash{$role}) {
4089: $returnhash{$role}.=','.$username.':'.$domain;
4090: } else {
4091: $returnhash{$role}=$username.':'.$domain;
4092: }
1.351 www 4093: } else {
1.988 raeburn 4094: my $key=&plaintext($role,$crstype);
1.973 bisitz 4095: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4096: if ($returnhash{$key}) {
4097: $returnhash{$key}.=','.$username.':'.$domain;
4098: } else {
4099: $returnhash{$key}=$username.':'.$domain;
4100: }
1.351 www 4101: }
1.948 raeburn 4102: }
1.400 www 4103: return %returnhash;
4104: }
4105:
4106: sub get_my_roles {
1.937 raeburn 4107: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4108: unless (defined($uname)) { $uname=$env{'user.name'}; }
4109: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4110: my (%dumphash,%nothide);
1.1086 raeburn 4111: if ($context eq 'userroles') {
1.1166 raeburn 4112: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4113: } else {
1.1219 raeburn 4114: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4115: if ($hidepriv) {
4116: my %coursehash=&coursedescription($udom.'_'.$uname);
4117: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4118: if ($user !~ /:/) {
4119: $nothide{join(':',split(/[\@]/,$user))} = 1;
4120: } else {
4121: $nothide{$user} = 1;
4122: }
4123: }
4124: }
1.858 raeburn 4125: }
1.400 www 4126: my %returnhash=();
4127: my $now=time;
1.999 raeburn 4128: my %privileged;
1.800 albertel 4129: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4130: my ($role,$tend,$tstart);
4131: if ($context eq 'userroles') {
1.1149 raeburn 4132: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4133: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4134: } else {
4135: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4136: }
1.400 www 4137: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4138: my $status = 'active';
1.939 raeburn 4139: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4140: $status = 'previous';
4141: }
4142: if (($tstart) && ($now<$tstart)) {
4143: $status = 'future';
4144: }
4145: if (ref($types) eq 'ARRAY') {
4146: if (!grep(/^\Q$status\E$/,@{$types})) {
4147: next;
4148: }
4149: } else {
4150: if ($status ne 'active') {
4151: next;
4152: }
4153: }
1.867 raeburn 4154: my ($rolecode,$username,$domain,$section,$area);
4155: if ($context eq 'userroles') {
1.1186 raeburn 4156: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4157: (undef,$domain,$username,$section) = split(/\//,$area);
4158: } else {
4159: ($role,$username,$domain,$section) = split(/\:/,$entry);
4160: }
1.832 raeburn 4161: if (ref($roledoms) eq 'ARRAY') {
4162: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4163: next;
4164: }
4165: }
4166: if (ref($roles) eq 'ARRAY') {
4167: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4168: if ($role =~ /^cr\//) {
4169: if (!grep(/^cr$/,@{$roles})) {
4170: next;
4171: }
1.1104 raeburn 4172: } elsif ($role =~ /^gr\//) {
4173: if (!grep(/^gr$/,@{$roles})) {
4174: next;
4175: }
1.922 raeburn 4176: } else {
4177: next;
4178: }
1.832 raeburn 4179: }
1.867 raeburn 4180: }
1.937 raeburn 4181: if ($hidepriv) {
1.1219 raeburn 4182: my @privroles = ('dc','su');
1.999 raeburn 4183: if ($context eq 'userroles') {
1.1219 raeburn 4184: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4185: } else {
1.1219 raeburn 4186: my $possdoms = [$domain];
4187: if (ref($roledoms) eq 'ARRAY') {
4188: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4189: }
1.1219 raeburn 4190: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4191: if (!$nothide{$username.':'.$domain}) {
4192: next;
4193: }
4194: }
1.937 raeburn 4195: }
4196: }
1.933 raeburn 4197: if ($withsec) {
4198: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4199: $tstart.':'.$tend;
4200: } else {
4201: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4202: }
1.832 raeburn 4203: }
1.373 www 4204: return %returnhash;
1.399 www 4205: }
4206:
4207: # ----------------------------------------------------- Frontpage Announcements
4208: #
4209: #
4210:
4211: sub postannounce {
4212: my ($server,$text)=@_;
1.844 albertel 4213: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4214: unless ($text=~/\w/) { $text=''; }
4215: return &reply('setannounce:'.&escape($text),$server);
4216: }
4217:
4218: sub getannounce {
1.448 albertel 4219:
4220: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4221: my $announcement='';
1.800 albertel 4222: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4223: close($fh);
1.399 www 4224: if ($announcement=~/\w/) {
4225: return
4226: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4227: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4228: } else {
4229: return '';
4230: }
4231: } else {
4232: return '';
4233: }
1.351 www 4234: }
1.353 www 4235:
4236: # ---------------------------------------------------------- Course ID routines
4237: # Deal with domain's nohist_courseid.db files
4238: #
4239:
4240: sub courseidput {
1.921 raeburn 4241: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4242: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4243: my $outcome;
4244: if ($caller eq 'timeonly') {
4245: my $cids = '';
4246: foreach my $item (keys(%$storehash)) {
4247: $cids.=&escape($item).'&';
4248: }
4249: $cids=~s/\&$//;
4250: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4251: $coursehome);
4252: } else {
4253: my $items = '';
4254: foreach my $item (keys(%$storehash)) {
4255: $items.= &escape($item).'='.
4256: &freeze_escape($$storehash{$item}).'&';
4257: }
4258: $items=~s/\&$//;
4259: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4260: $coursehome);
1.918 raeburn 4261: }
4262: if ($outcome eq 'unknown_cmd') {
4263: my $what;
4264: foreach my $cid (keys(%$storehash)) {
4265: $what .= &escape($cid).'=';
1.921 raeburn 4266: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4267: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4268: }
4269: $what =~ s/\:$/&/;
4270: }
4271: $what =~ s/\&$//;
4272: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4273: } else {
4274: return $outcome;
4275: }
1.353 www 4276: }
4277:
4278: sub courseiddump {
1.921 raeburn 4279: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4280: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4281: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4282: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4283: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4284: my $as_hash = 1;
4285: my %returnhash;
4286: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4287: my %libserv = &all_library();
4288: foreach my $tryserver (keys(%libserv)) {
4289: if ( ( $hostidflag == 1
4290: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4291: || (!defined($hostidflag)) ) {
4292:
1.918 raeburn 4293: if (($domfilter eq '') ||
4294: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4295: my $rep;
4296: if (grep { $_ eq $tryserver } current_machine_ids()) {
4297: $rep = LONCAPA::Lond::dump_course_id_handler(
4298: join(":", (&host_domain($tryserver), $sincefilter,
4299: &escape($descfilter), &escape($instcodefilter),
4300: &escape($ownerfilter), &escape($coursefilter),
4301: &escape($typefilter), &escape($regexp_ok),
4302: $as_hash, &escape($selfenrollonly),
4303: &escape($catfilter), $showhidden, $caller,
4304: &escape($cloner), &escape($cc_clone), $cloneonly,
4305: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4306: &escape($creationcontext),$domcloner,$hasuniquecode,
4307: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4308: } else {
4309: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4310: $sincefilter.':'.&escape($descfilter).':'.
4311: &escape($instcodefilter).':'.&escape($ownerfilter).
4312: ':'.&escape($coursefilter).':'.&escape($typefilter).
4313: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4314: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4315: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4316: &escape($cc_clone).':'.$cloneonly.':'.
4317: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4318: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4319: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4320: }
4321:
1.918 raeburn 4322: my @pairs=split(/\&/,$rep);
4323: foreach my $item (@pairs) {
4324: my ($key,$value)=split(/\=/,$item,2);
4325: $key = &unescape($key);
4326: next if ($key =~ /^error: 2 /);
4327: my $result = &thaw_unescape($value);
4328: if (ref($result) eq 'HASH') {
4329: $returnhash{$key}=$result;
4330: } else {
1.921 raeburn 4331: my @responses = split(/:/,$value);
4332: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4333: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4334: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4335: }
1.1008 raeburn 4336: }
1.353 www 4337: }
4338: }
4339: }
4340: }
4341: return %returnhash;
4342: }
4343:
1.1055 raeburn 4344: sub courselastaccess {
4345: my ($cdom,$cnum,$hostidref) = @_;
4346: my %returnhash;
4347: if ($cdom && $cnum) {
4348: my $chome = &homeserver($cnum,$cdom);
4349: if ($chome ne 'no_host') {
4350: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4351: &extract_lastaccess(\%returnhash,$rep);
4352: }
4353: } else {
4354: if (!$cdom) { $cdom=''; }
4355: my %libserv = &all_library();
4356: foreach my $tryserver (keys(%libserv)) {
4357: if (ref($hostidref) eq 'ARRAY') {
4358: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4359: }
4360: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4361: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4362: &extract_lastaccess(\%returnhash,$rep);
4363: }
4364: }
4365: }
4366: return %returnhash;
4367: }
4368:
4369: sub extract_lastaccess {
4370: my ($returnhash,$rep) = @_;
4371: if (ref($returnhash) eq 'HASH') {
4372: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4373: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4374: $rep eq '') {
4375: my @pairs=split(/\&/,$rep);
4376: foreach my $item (@pairs) {
4377: my ($key,$value)=split(/\=/,$item,2);
4378: $key = &unescape($key);
4379: next if ($key =~ /^error: 2 /);
4380: $returnhash->{$key} = &thaw_unescape($value);
4381: }
4382: }
4383: }
4384: return;
4385: }
4386:
1.658 raeburn 4387: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4388:
4389: sub dcmailput {
1.685 raeburn 4390: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4391: my $status = &Apache::lonnet::critical(
1.740 www 4392: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4393: &escape($message),$server);
1.662 raeburn 4394: return $status;
4395: }
4396:
1.658 raeburn 4397: sub dcmaildump {
4398: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4399: my %returnhash=();
1.846 albertel 4400:
4401: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4402: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4403: &escape($enddate).':';
4404: my @esc_senders=map { &escape($_)} @$senders;
4405: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4406: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4407: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4408: if (($key) && ($value)) {
4409: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4410: }
4411: }
4412: }
4413: return %returnhash;
4414: }
1.662 raeburn 4415: # ---------------------------------------------------------- Domain roles
4416:
4417: sub get_domain_roles {
4418: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4419: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4420: $startdate = '.';
4421: }
1.1018 raeburn 4422: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4423: $enddate = '.';
4424: }
1.922 raeburn 4425: my $rolelist;
4426: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4427: $rolelist = join('&',@{$roles});
1.922 raeburn 4428: }
1.662 raeburn 4429: my %personnel = ();
1.841 albertel 4430:
4431: my %servers = &get_servers($dom,'library');
4432: foreach my $tryserver (keys(%servers)) {
4433: %{$personnel{$tryserver}}=();
4434: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4435: &escape($startdate).':'.
4436: &escape($enddate).':'.
4437: &escape($rolelist), $tryserver))) {
4438: my ($key,$value) = split(/\=/,$line,2);
4439: if (($key) && ($value)) {
4440: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4441: }
4442: }
1.662 raeburn 4443: }
4444: return %personnel;
4445: }
1.658 raeburn 4446:
1.1057 www 4447: # ----------------------------------------------------------- Interval timing
1.149 www 4448:
1.1153 www 4449: {
4450: # Caches needed for speedup of navmaps
4451: # We don't want to cache this for very long at all (5 seconds at most)
4452: #
4453: # The user for whom we cache
4454: my $cachedkey='';
4455: # The cached times for this user
4456: my %cachedtimes=();
4457: # When this was last done
1.1282 raeburn 4458: my $cachedtime='';
1.1153 www 4459:
4460: sub load_all_first_access {
1.1154 raeburn 4461: my ($uname,$udom)=@_;
1.1156 www 4462: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4463: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4464: return;
4465: }
4466: $cachedtime=time;
4467: $cachedkey=$uname.':'.$udom;
4468: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4469: }
4470:
1.504 albertel 4471: sub get_first_access {
1.1162 raeburn 4472: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4473: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4474: if ($argsymb) { $symb=$argsymb; }
4475: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4476: if ($argmap) { $map = $argmap; }
1.926 albertel 4477: if ($type eq 'course') {
4478: $res='course';
4479: } elsif ($type eq 'map') {
1.588 albertel 4480: $res=&symbread($map);
4481: } else {
4482: $res=$symb;
4483: }
1.1153 www 4484: &load_all_first_access($uname,$udom);
4485: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4486: }
4487:
4488: sub set_first_access {
1.1162 raeburn 4489: my ($type,$interval)=@_;
1.790 albertel 4490: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4491: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4492: if ($type eq 'course') {
4493: $res='course';
4494: } elsif ($type eq 'map') {
1.588 albertel 4495: $res=&symbread($map);
4496: } else {
4497: $res=$symb;
4498: }
1.1153 www 4499: $cachedkey='';
1.1162 raeburn 4500: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4501: if (!$firstaccess) {
1.1162 raeburn 4502: my $start = time;
4503: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4504: $udom,$uname);
4505: if ($putres eq 'ok') {
4506: &put('timerinterval',{"$courseid\0$res"=>$interval},
4507: $udom,$uname);
4508: &appenv(
4509: {
4510: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4511: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4512: }
4513: );
4514: }
4515: return $putres;
1.505 albertel 4516: }
4517: return 'already_set';
1.504 albertel 4518: }
1.1153 www 4519: }
1.1282 raeburn 4520:
1.110 www 4521: # --------------------------------------------- Set Expire Date for Spreadsheet
4522:
4523: sub expirespread {
4524: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4525: my $cid=$env{'request.course.id'};
1.110 www 4526: if ($cid) {
4527: my $now=time;
4528: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4529: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4530: $env{'course.'.$cid.'.num'}.
1.110 www 4531: ':nohist_expirationdates:'.
4532: &escape($key).'='.$now,
1.620 albertel 4533: $env{'course.'.$cid.'.home'})
1.110 www 4534: }
4535: return 'ok';
1.14 www 4536: }
4537:
1.109 www 4538: # ----------------------------------------------------- Devalidate Spreadsheets
4539:
4540: sub devalidate {
1.325 www 4541: my ($symb,$uname,$udom)=@_;
1.620 albertel 4542: my $cid=$env{'request.course.id'};
1.109 www 4543: if ($cid) {
1.391 matthew 4544: # delete the stored spreadsheets for
4545: # - the student level sheet of this user in course's homespace
4546: # - the assessment level sheet for this resource
4547: # for this user in user's homespace
1.553 albertel 4548: # - current conditional state info
1.325 www 4549: my $key=$uname.':'.$udom.':';
1.109 www 4550: my $status=
1.299 matthew 4551: &del('nohist_calculatedsheets',
1.391 matthew 4552: [$key.'studentcalc:'],
1.620 albertel 4553: $env{'course.'.$cid.'.domain'},
4554: $env{'course.'.$cid.'.num'})
1.133 albertel 4555: .' '.
4556: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4557: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4558: unless ($status eq 'ok ok') {
4559: &logthis('Could not devalidate spreadsheet '.
1.325 www 4560: $uname.' at '.$udom.' for '.
1.109 www 4561: $symb.': '.$status);
1.133 albertel 4562: }
1.553 albertel 4563: &delenv('user.state.'.$cid);
1.109 www 4564: }
4565: }
4566:
1.265 albertel 4567: sub get_scalar {
4568: my ($string,$end) = @_;
4569: my $value;
4570: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4571: $value = $1;
4572: } elsif ($$string =~ s/^([^&]*?)&//) {
4573: $value = $1;
4574: }
4575: return &unescape($value);
4576: }
4577:
4578: sub array2str {
4579: my (@array) = @_;
4580: my $result=&arrayref2str(\@array);
4581: $result=~s/^__ARRAY_REF__//;
4582: $result=~s/__END_ARRAY_REF__$//;
4583: return $result;
4584: }
4585:
1.204 albertel 4586: sub arrayref2str {
4587: my ($arrayref) = @_;
1.265 albertel 4588: my $result='__ARRAY_REF__';
1.204 albertel 4589: foreach my $elem (@$arrayref) {
1.265 albertel 4590: if(ref($elem) eq 'ARRAY') {
4591: $result.=&arrayref2str($elem).'&';
4592: } elsif(ref($elem) eq 'HASH') {
4593: $result.=&hashref2str($elem).'&';
4594: } elsif(ref($elem)) {
4595: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4596: } else {
4597: $result.=&escape($elem).'&';
4598: }
4599: }
4600: $result=~s/\&$//;
1.265 albertel 4601: $result .= '__END_ARRAY_REF__';
1.204 albertel 4602: return $result;
4603: }
4604:
1.168 albertel 4605: sub hash2str {
1.204 albertel 4606: my (%hash) = @_;
4607: my $result=&hashref2str(\%hash);
1.265 albertel 4608: $result=~s/^__HASH_REF__//;
4609: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4610: return $result;
4611: }
4612:
4613: sub hashref2str {
4614: my ($hashref)=@_;
1.265 albertel 4615: my $result='__HASH_REF__';
1.800 albertel 4616: foreach my $key (sort(keys(%$hashref))) {
4617: if (ref($key) eq 'ARRAY') {
4618: $result.=&arrayref2str($key).'=';
4619: } elsif (ref($key) eq 'HASH') {
4620: $result.=&hashref2str($key).'=';
4621: } elsif (ref($key)) {
1.265 albertel 4622: $result.='=';
1.800 albertel 4623: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4624: } else {
1.1132 raeburn 4625: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4626: }
4627:
1.800 albertel 4628: if(ref($hashref->{$key}) eq 'ARRAY') {
4629: $result.=&arrayref2str($hashref->{$key}).'&';
4630: } elsif(ref($hashref->{$key}) eq 'HASH') {
4631: $result.=&hashref2str($hashref->{$key}).'&';
4632: } elsif(ref($hashref->{$key})) {
1.265 albertel 4633: $result.='&';
1.800 albertel 4634: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4635: } else {
1.800 albertel 4636: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4637: }
4638: }
1.168 albertel 4639: $result=~s/\&$//;
1.265 albertel 4640: $result .= '__END_HASH_REF__';
1.168 albertel 4641: return $result;
4642: }
4643:
4644: sub str2hash {
1.265 albertel 4645: my ($string)=@_;
4646: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4647: return %$hash;
4648: }
4649:
4650: sub str2hashref {
1.168 albertel 4651: my ($string) = @_;
1.265 albertel 4652:
4653: my %hash;
4654:
4655: if($string !~ /^__HASH_REF__/) {
4656: if (! ($string eq '' || !defined($string))) {
4657: $hash{'error'}='Not hash reference';
4658: }
4659: return (\%hash, $string);
4660: }
4661:
4662: $string =~ s/^__HASH_REF__//;
4663:
4664: while($string !~ /^__END_HASH_REF__/) {
4665: #key
4666: my $key='';
4667: if($string =~ /^__HASH_REF__/) {
4668: ($key, $string)=&str2hashref($string);
4669: if(defined($key->{'error'})) {
4670: $hash{'error'}='Bad data';
4671: return (\%hash, $string);
4672: }
4673: } elsif($string =~ /^__ARRAY_REF__/) {
4674: ($key, $string)=&str2arrayref($string);
4675: if($key->[0] eq 'Array reference error') {
4676: $hash{'error'}='Bad data';
4677: return (\%hash, $string);
4678: }
4679: } else {
4680: $string =~ s/^(.*?)=//;
1.267 albertel 4681: $key=&unescape($1);
1.265 albertel 4682: }
4683: $string =~ s/^=//;
4684:
4685: #value
4686: my $value='';
4687: if($string =~ /^__HASH_REF__/) {
4688: ($value, $string)=&str2hashref($string);
4689: if(defined($value->{'error'})) {
4690: $hash{'error'}='Bad data';
4691: return (\%hash, $string);
4692: }
4693: } elsif($string =~ /^__ARRAY_REF__/) {
4694: ($value, $string)=&str2arrayref($string);
4695: if($value->[0] eq 'Array reference error') {
4696: $hash{'error'}='Bad data';
4697: return (\%hash, $string);
4698: }
4699: } else {
4700: $value=&get_scalar(\$string,'__END_HASH_REF__');
4701: }
4702: $string =~ s/^&//;
4703:
4704: $hash{$key}=$value;
1.204 albertel 4705: }
1.265 albertel 4706:
4707: $string =~ s/^__END_HASH_REF__//;
4708:
4709: return (\%hash, $string);
1.204 albertel 4710: }
4711:
4712: sub str2array {
1.265 albertel 4713: my ($string)=@_;
4714: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4715: return @$array;
4716: }
4717:
4718: sub str2arrayref {
1.204 albertel 4719: my ($string) = @_;
1.265 albertel 4720: my @array;
4721:
4722: if($string !~ /^__ARRAY_REF__/) {
4723: if (! ($string eq '' || !defined($string))) {
4724: $array[0]='Array reference error';
4725: }
4726: return (\@array, $string);
4727: }
4728:
4729: $string =~ s/^__ARRAY_REF__//;
4730:
4731: while($string !~ /^__END_ARRAY_REF__/) {
4732: my $value='';
4733: if($string =~ /^__HASH_REF__/) {
4734: ($value, $string)=&str2hashref($string);
4735: if(defined($value->{'error'})) {
4736: $array[0] ='Array reference error';
4737: return (\@array, $string);
4738: }
4739: } elsif($string =~ /^__ARRAY_REF__/) {
4740: ($value, $string)=&str2arrayref($string);
4741: if($value->[0] eq 'Array reference error') {
4742: $array[0] ='Array reference error';
4743: return (\@array, $string);
4744: }
4745: } else {
4746: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4747: }
4748: $string =~ s/^&//;
4749:
4750: push(@array, $value);
1.191 harris41 4751: }
1.265 albertel 4752:
4753: $string =~ s/^__END_ARRAY_REF__//;
4754:
4755: return (\@array, $string);
1.168 albertel 4756: }
4757:
1.167 albertel 4758: # -------------------------------------------------------------------Temp Store
4759:
1.168 albertel 4760: sub tmpreset {
4761: my ($symb,$namespace,$domain,$stuname) = @_;
4762: if (!$symb) {
4763: $symb=&symbread();
1.620 albertel 4764: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4765: }
4766: $symb=escape($symb);
4767:
1.620 albertel 4768: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4769: $namespace=~s/\//\_/g;
4770: $namespace=~s/\W//g;
4771:
1.620 albertel 4772: if (!$domain) { $domain=$env{'user.domain'}; }
4773: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4774: if ($domain eq 'public' && $stuname eq 'public') {
4775: $stuname=$ENV{'REMOTE_ADDR'};
4776: }
1.1117 foxr 4777: my $path=LONCAPA::tempdir();
1.168 albertel 4778: my %hash;
4779: if (tie(%hash,'GDBM_File',
4780: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4781: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4782: foreach my $key (keys(%hash)) {
1.180 albertel 4783: if ($key=~ /:$symb/) {
1.168 albertel 4784: delete($hash{$key});
4785: }
4786: }
4787: }
4788: }
4789:
1.167 albertel 4790: sub tmpstore {
1.168 albertel 4791: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4792:
4793: if (!$symb) {
4794: $symb=&symbread();
1.620 albertel 4795: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4796: }
4797: $symb=escape($symb);
4798:
4799: if (!$namespace) {
4800: # I don't think we would ever want to store this for a course.
4801: # it seems this will only be used if we don't have a course.
1.620 albertel 4802: #$namespace=$env{'request.course.id'};
1.168 albertel 4803: #if (!$namespace) {
1.620 albertel 4804: $namespace=$env{'request.state'};
1.168 albertel 4805: #}
4806: }
4807: $namespace=~s/\//\_/g;
4808: $namespace=~s/\W//g;
1.620 albertel 4809: if (!$domain) { $domain=$env{'user.domain'}; }
4810: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4811: if ($domain eq 'public' && $stuname eq 'public') {
4812: $stuname=$ENV{'REMOTE_ADDR'};
4813: }
1.168 albertel 4814: my $now=time;
4815: my %hash;
1.1117 foxr 4816: my $path=LONCAPA::tempdir();
1.168 albertel 4817: if (tie(%hash,'GDBM_File',
4818: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4819: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4820: $hash{"version:$symb"}++;
4821: my $version=$hash{"version:$symb"};
4822: my $allkeys='';
4823: foreach my $key (keys(%$storehash)) {
4824: $allkeys.=$key.':';
1.591 albertel 4825: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4826: }
4827: $hash{"$version:$symb:timestamp"}=$now;
4828: $allkeys.='timestamp';
4829: $hash{"$version:keys:$symb"}=$allkeys;
4830: if (untie(%hash)) {
4831: return 'ok';
4832: } else {
4833: return "error:$!";
4834: }
4835: } else {
4836: return "error:$!";
4837: }
4838: }
1.167 albertel 4839:
1.168 albertel 4840: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4841:
1.168 albertel 4842: sub tmprestore {
4843: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4844:
1.168 albertel 4845: if (!$symb) {
4846: $symb=&symbread();
1.620 albertel 4847: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4848: }
4849: $symb=escape($symb);
4850:
1.620 albertel 4851: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4852:
1.620 albertel 4853: if (!$domain) { $domain=$env{'user.domain'}; }
4854: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4855: if ($domain eq 'public' && $stuname eq 'public') {
4856: $stuname=$ENV{'REMOTE_ADDR'};
4857: }
1.168 albertel 4858: my %returnhash;
4859: $namespace=~s/\//\_/g;
4860: $namespace=~s/\W//g;
4861: my %hash;
1.1117 foxr 4862: my $path=LONCAPA::tempdir();
1.168 albertel 4863: if (tie(%hash,'GDBM_File',
4864: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4865: &GDBM_READER(),0640)) {
1.168 albertel 4866: my $version=$hash{"version:$symb"};
4867: $returnhash{'version'}=$version;
4868: my $scope;
4869: for ($scope=1;$scope<=$version;$scope++) {
4870: my $vkeys=$hash{"$scope:keys:$symb"};
4871: my @keys=split(/:/,$vkeys);
4872: my $key;
4873: $returnhash{"$scope:keys"}=$vkeys;
4874: foreach $key (@keys) {
1.591 albertel 4875: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4876: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4877: }
4878: }
1.168 albertel 4879: if (!(untie(%hash))) {
4880: return "error:$!";
4881: }
4882: } else {
4883: return "error:$!";
4884: }
4885: return %returnhash;
1.167 albertel 4886: }
4887:
1.9 www 4888: # ----------------------------------------------------------------------- Store
4889:
4890: sub store {
1.1269 raeburn 4891: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4892: my $home='';
4893:
1.168 albertel 4894: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4895:
1.213 www 4896: $symb=&symbclean($symb);
1.122 albertel 4897: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4898:
1.620 albertel 4899: if (!$domain) { $domain=$env{'user.domain'}; }
4900: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4901:
4902: &devalidate($symb,$stuname,$domain);
1.109 www 4903:
4904: $symb=escape($symb);
1.187 www 4905: if (!$namespace) {
1.620 albertel 4906: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4907: return '';
4908: }
4909: }
1.620 albertel 4910: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4911:
4912: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4913: $$storehash{'host'}=$perlvar{'lonHostID'};
4914:
1.12 www 4915: my $namevalue='';
1.800 albertel 4916: foreach my $key (keys(%$storehash)) {
4917: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4918: }
1.12 www 4919: $namevalue=~s/\&$//;
1.187 www 4920: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4921: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4922: }
4923:
1.47 www 4924: # -------------------------------------------------------------- Critical Store
4925:
4926: sub cstore {
1.1269 raeburn 4927: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4928: my $home='';
4929:
1.168 albertel 4930: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4931:
1.213 www 4932: $symb=&symbclean($symb);
1.122 albertel 4933: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4934:
1.620 albertel 4935: if (!$domain) { $domain=$env{'user.domain'}; }
4936: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4937:
4938: &devalidate($symb,$stuname,$domain);
1.109 www 4939:
4940: $symb=escape($symb);
1.187 www 4941: if (!$namespace) {
1.620 albertel 4942: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4943: return '';
4944: }
4945: }
1.620 albertel 4946: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4947:
4948: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4949: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4950:
1.47 www 4951: my $namevalue='';
1.800 albertel 4952: foreach my $key (keys(%$storehash)) {
4953: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4954: }
1.47 www 4955: $namevalue=~s/\&$//;
1.187 www 4956: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4957: return critical
1.1269 raeburn 4958: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4959: }
4960:
1.9 www 4961: # --------------------------------------------------------------------- Restore
4962:
4963: sub restore {
1.124 www 4964: my ($symb,$namespace,$domain,$stuname) = @_;
4965: my $home='';
4966:
1.168 albertel 4967: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4968:
1.122 albertel 4969: if (!$symb) {
1.1224 raeburn 4970: return if ($namespace eq 'courserequests');
4971: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4972: } else {
1.1224 raeburn 4973: unless ($namespace eq 'courserequests') {
4974: $symb=&escape(&symbclean($symb));
4975: }
1.122 albertel 4976: }
1.188 www 4977: if (!$namespace) {
1.620 albertel 4978: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4979: return '';
4980: }
4981: }
1.620 albertel 4982: if (!$domain) { $domain=$env{'user.domain'}; }
4983: if (!$stuname) { $stuname=$env{'user.name'}; }
4984: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4985: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4986:
1.12 www 4987: my %returnhash=();
1.800 albertel 4988: foreach my $line (split(/\&/,$answer)) {
4989: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4990: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4991: }
1.75 www 4992: my $version;
4993: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4994: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4995: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4996: }
1.75 www 4997: }
1.13 www 4998: return %returnhash;
1.34 www 4999: }
5000:
5001: # ---------------------------------------------------------- Course Description
1.1118 foxr 5002: #
5003: #
1.34 www 5004:
5005: sub coursedescription {
1.731 albertel 5006: my ($courseid,$args)=@_;
1.34 www 5007: $courseid=~s/^\///;
1.49 www 5008: $courseid=~s/\_/\//g;
1.34 www 5009: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5010: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5011: my $normalid=$cdomain.'_'.$cnum;
5012: # need to always cache even if we get errors otherwise we keep
5013: # trying and trying and trying to get the course description.
5014: my %envhash=();
5015: my %returnhash=();
1.731 albertel 5016:
5017: my $expiretime=600;
5018: if ($env{'request.course.id'} eq $normalid) {
5019: $expiretime=120;
5020: }
5021:
5022: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5023: if (!$args->{'freshen_cache'}
5024: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5025: foreach my $key (keys(%env)) {
5026: next if ($key !~ /^\Q$prefix\E(.*)/);
5027: my ($setting) = $1;
5028: $returnhash{$setting} = $env{$key};
5029: }
5030: return %returnhash;
5031: }
5032:
1.1118 foxr 5033: # get the data again
5034:
1.731 albertel 5035: if (!$args->{'one_time'}) {
5036: $envhash{'course.'.$normalid.'.last_cache'}=time;
5037: }
1.811 albertel 5038:
1.34 www 5039: if ($chome ne 'no_host') {
1.302 albertel 5040: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5041: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5042: my $username = $env{'user.name'}; # Defult username
5043: if(defined $args->{'user'}) {
5044: $username = $args->{'user'};
5045: }
1.129 albertel 5046: $returnhash{'home'}= $chome;
5047: $returnhash{'domain'} = $cdomain;
5048: $returnhash{'num'} = $cnum;
1.741 raeburn 5049: if (!defined($returnhash{'type'})) {
5050: $returnhash{'type'} = 'Course';
5051: }
1.130 albertel 5052: while (my ($name,$value) = each %returnhash) {
1.53 www 5053: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5054: }
1.270 www 5055: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5056: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5057: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5058: $envhash{'course.'.$normalid.'.home'}=$chome;
5059: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5060: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5061: }
5062: }
1.731 albertel 5063: if (!$args->{'one_time'}) {
1.949 raeburn 5064: &appenv(\%envhash);
1.731 albertel 5065: }
1.302 albertel 5066: return %returnhash;
1.461 www 5067: }
5068:
1.1080 raeburn 5069: sub update_released_required {
5070: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5071: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5072: $cid = $env{'request.course.id'};
5073: $cdom = $env{'course.'.$cid.'.domain'};
5074: $cnum = $env{'course.'.$cid.'.num'};
5075: $chome = $env{'course.'.$cid.'.home'};
5076: }
5077: if ($needsrelease) {
5078: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5079: my $needsupdate;
5080: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5081: $needsupdate = 1;
5082: } else {
5083: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5084: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5085: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5086: $needsupdate = 1;
5087: }
5088: }
5089: if ($needsupdate) {
5090: my %needshash = (
5091: 'internal.releaserequired' => $needsrelease,
5092: );
5093: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5094: if ($putresult eq 'ok') {
5095: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5096: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5097: if (ref($crsinfo{$cid}) eq 'HASH') {
5098: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5099: &courseidput($cdom,\%crsinfo,$chome,'notime');
5100: }
5101: }
5102: }
5103: }
5104: return;
5105: }
5106:
1.461 www 5107: # -------------------------------------------------See if a user is privileged
5108:
5109: sub privileged {
1.1219 raeburn 5110: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5111: my $now = time;
1.1219 raeburn 5112: my $roles;
5113: if (ref($possroles) eq 'ARRAY') {
5114: $roles = $possroles;
5115: } else {
5116: $roles = ['dc','su'];
5117: }
5118: if (ref($possdomains) eq 'ARRAY') {
5119: my %privileged = &privileged_by_domain($possdomains,$roles);
5120: foreach my $dom (@{$possdomains}) {
5121: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5122: (ref($privileged{$dom}) eq 'HASH')) {
5123: foreach my $role (@{$roles}) {
5124: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5125: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5126: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5127: return 1 unless (($end && $end < $now) ||
5128: ($start && $start > $now));
5129: }
5130: }
5131: }
5132: }
5133: }
5134: } else {
5135: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5136: my $now = time;
1.1170 droeschl 5137:
1.1275 musolffc 5138: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5139: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5140: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5141: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5142: or ($tstart && $tstart > $now);
1.1170 droeschl 5143: }
1.1219 raeburn 5144: }
5145: }
5146: return 0;
5147: }
1.1170 droeschl 5148:
1.1219 raeburn 5149: sub privileged_by_domain {
5150: my ($domains,$roles) = @_;
5151: my %privileged = ();
5152: my $cachetime = 60*60*24;
5153: my $now = time;
5154: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5155: return %privileged;
5156: }
5157: foreach my $dom (@{$domains}) {
5158: next if (ref($privileged{$dom}) eq 'HASH');
5159: my $needroles;
5160: foreach my $role (@{$roles}) {
5161: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5162: if (defined($cached)) {
5163: if (ref($result) eq 'HASH') {
5164: $privileged{$dom}{$role} = $result;
5165: }
5166: } else {
5167: $needroles = 1;
5168: }
5169: }
5170: if ($needroles) {
5171: my %dompersonnel = &get_domain_roles($dom,$roles);
5172: $privileged{$dom} = {};
5173: foreach my $server (keys(%dompersonnel)) {
5174: if (ref($dompersonnel{$server}) eq 'HASH') {
5175: foreach my $item (keys(%{$dompersonnel{$server}})) {
5176: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5177: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5178: next if ($end && $end < $now);
5179: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5180: $dompersonnel{$server}{$item};
5181: }
5182: }
5183: }
5184: if (ref($privileged{$dom}) eq 'HASH') {
5185: foreach my $role (@{$roles}) {
5186: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5187: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5188: } else {
5189: my %hash = ();
5190: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5191: }
5192: }
5193: }
5194: }
5195: }
5196: return %privileged;
1.9 www 5197: }
1.1 albertel 5198:
1.103 harris41 5199: # -------------------------------------------------------- Get user privileges
1.11 www 5200:
5201: sub rolesinit {
1.1169 droeschl 5202: my ($domain, $username) = @_;
5203: my %userroles = ('user.login.time' => time);
5204: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5205:
5206: # firstaccess and timerinterval are related to timed maps/resources.
5207: # also, blocking can be triggered by an activating timer
5208: # it's saved in the user's %env.
5209: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5210: my %timerinterval = &dump('timerinterval', $domain, $username);
5211: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5212: %timerintchk, %timerintenv);
5213:
1.1162 raeburn 5214: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5215: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5216: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5217: }
1.1169 droeschl 5218:
1.1162 raeburn 5219: foreach my $key (keys(%timerinterval)) {
5220: my ($cid,$rest) = split(/\0/,$key);
5221: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5222: }
1.1169 droeschl 5223:
1.11 www 5224: my %allroles=();
1.1162 raeburn 5225: my %allgroups=();
1.11 www 5226:
1.1274 raeburn 5227: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5228: my $role = $rolesdump{$area};
5229: $area =~ s/\_\w\w$//;
5230:
5231: my ($trole, $tend, $tstart, $group_privs);
5232:
5233: if ($role =~ /^cr/) {
5234: # Custom role, defined by a user
5235: # e.g., user.role.cr/msu/smith/mynewrole
5236: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5237: $trole = $1;
5238: ($tend, $tstart) = split('_', $2);
5239: } else {
5240: $trole = $role;
5241: }
5242: } elsif ($role =~ m|^gr/|) {
5243: # Role of member in a group, defined within a course/community
5244: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5245: ($trole, $tend, $tstart) = split(/_/, $role);
5246: next if $tstart eq '-1';
5247: ($trole, $group_privs) = split(/\//, $trole);
5248: $group_privs = &unescape($group_privs);
5249: } else {
5250: # Just a normal role, defined in roles.tab
5251: ($trole, $tend, $tstart) = split(/_/,$role);
5252: }
5253:
5254: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5255: $username);
5256: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5257:
5258: # role expired or not available yet?
5259: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5260: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5261:
5262: next if $area eq '' or $trole eq '';
5263:
5264: my $spec = "$trole.$area";
5265: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5266:
5267: if ($trole =~ /^cr\//) {
5268: # Custom role, defined by a user
5269: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5270: } elsif ($trole eq 'gr') {
5271: # Role of a member in a group, defined within a course/community
5272: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5273: next;
5274: } else {
5275: # Normal role, defined in roles.tab
5276: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5277: }
5278:
5279: my $cid = $tdomain.'_'.$trest;
5280: unless ($firstaccchk{$cid}) {
5281: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5282: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5283: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5284: $coursetimerstarts{$cid}{$item};
5285: }
5286: }
5287: $firstaccchk{$cid} = 1;
5288: }
5289: unless ($timerintchk{$cid}) {
5290: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5291: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5292: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5293: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5294: }
1.12 www 5295: }
1.1169 droeschl 5296: $timerintchk{$cid} = 1;
1.191 harris41 5297: }
1.11 www 5298: }
1.1169 droeschl 5299:
5300: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5301: \%allroles, \%allgroups);
5302: $env{'user.adv'} = $userroles{'user.adv'};
5303:
1.1162 raeburn 5304: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5305: }
5306:
1.567 raeburn 5307: sub set_arearole {
1.1215 raeburn 5308: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5309: unless ($nolog) {
1.567 raeburn 5310: # log the associated role with the area
1.1215 raeburn 5311: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5312: }
1.743 albertel 5313: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5314: }
5315:
5316: sub custom_roleprivs {
5317: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5318: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5319: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5320: if (&hostname($homsvr) ne '') {
1.567 raeburn 5321: my ($rdummy,$roledef)=
5322: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5323: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5324: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5325: if (defined($syspriv)) {
1.1043 raeburn 5326: if ($trest =~ /^$match_community$/) {
5327: $syspriv =~ s/bre\&S//;
5328: }
1.567 raeburn 5329: $$allroles{'cm./'}.=':'.$syspriv;
5330: $$allroles{$spec.'./'}.=':'.$syspriv;
5331: }
5332: if ($tdomain ne '') {
5333: if (defined($dompriv)) {
5334: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5335: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5336: }
5337: if (($trest ne '') && (defined($coursepriv))) {
5338: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5339: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5340: }
5341: }
5342: }
5343: }
5344: }
5345:
1.678 raeburn 5346: sub group_roleprivs {
5347: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5348: my $access = 1;
5349: my $now = time;
5350: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5351: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5352: if ($access) {
1.811 albertel 5353: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5354: $$allgroups{$course}{$group} .=':'.$group_privs;
5355: }
5356: }
1.567 raeburn 5357:
5358: sub standard_roleprivs {
5359: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5360: if (defined($pr{$trole.':s'})) {
5361: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5362: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5363: }
5364: if ($tdomain ne '') {
5365: if (defined($pr{$trole.':d'})) {
5366: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5367: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5368: }
5369: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5370: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5371: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5372: }
5373: }
5374: }
5375:
5376: sub set_userprivs {
1.1064 raeburn 5377: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5378: my $author=0;
5379: my $adv=0;
1.678 raeburn 5380: my %grouproles = ();
5381: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5382: my @groupkeys;
1.1000 raeburn 5383: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5384: push(@groupkeys,$role);
5385: }
5386: if (ref($groups_roles) eq 'HASH') {
5387: foreach my $key (keys(%{$groups_roles})) {
5388: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5389: push(@groupkeys,$key);
5390: }
5391: }
5392: }
5393: if (@groupkeys > 0) {
5394: foreach my $role (@groupkeys) {
5395: my ($trole,$area,$sec,$extendedarea);
5396: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5397: $trole = $1;
5398: $area = $2;
5399: $sec = $3;
5400: $extendedarea = $area.$sec;
5401: if (exists($$allgroups{$area})) {
5402: foreach my $group (keys(%{$$allgroups{$area}})) {
5403: my $spec = $trole.'.'.$extendedarea;
5404: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5405: $$allgroups{$area}{$group};
1.1064 raeburn 5406: }
1.678 raeburn 5407: }
5408: }
5409: }
5410: }
5411: }
1.800 albertel 5412: foreach my $group (keys(%grouproles)) {
5413: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5414: }
1.800 albertel 5415: foreach my $role (keys(%{$allroles})) {
5416: my %thesepriv;
1.941 raeburn 5417: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5418: foreach my $item (split(/:/,$$allroles{$role})) {
5419: if ($item ne '') {
5420: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5421: if ($restrictions eq '') {
5422: $thesepriv{$privilege}='F';
5423: } elsif ($thesepriv{$privilege} ne 'F') {
5424: $thesepriv{$privilege}.=$restrictions;
5425: }
5426: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5427: }
5428: }
5429: my $thesestr='';
1.1104 raeburn 5430: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5431: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5432: }
5433: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5434: }
5435: return ($author,$adv);
5436: }
5437:
1.994 raeburn 5438: sub role_status {
1.1104 raeburn 5439: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5440: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5441: my ($one,$two) = split(m{\./},$rolekey,2);
5442: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5443: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5444: $$where = '/'.$two;
1.994 raeburn 5445: $$trolecode=$$role.'.'.$$where;
5446: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5447: $$tstatus='is';
1.1104 raeburn 5448: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5449: $$tstatus='future';
1.1034 raeburn 5450: if ($$tstart<$now) {
5451: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5452: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5453: my (%allroles,%allgroups,$group_privs,
5454: %groups_roles,@rolecodes);
1.1002 raeburn 5455: my %userroles = (
5456: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5457: );
1.1064 raeburn 5458: @rolecodes = ('cm');
1.1002 raeburn 5459: my $spec=$$role.'.'.$$where;
5460: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5461: if ($$role =~ /^cr\//) {
5462: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5463: push(@rolecodes,'cr');
1.1002 raeburn 5464: } elsif ($$role eq 'gr') {
1.1064 raeburn 5465: push(@rolecodes,$$role);
1.1002 raeburn 5466: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5467: $env{'user.name'});
1.1064 raeburn 5468: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5469: (undef,my $group_privs) = split(/\//,$trole);
5470: $group_privs = &unescape($group_privs);
5471: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5472: 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 5473: &get_groups_roles($tdomain,$trest,
5474: \%course_roles,\@rolecodes,
5475: \%groups_roles);
1.1002 raeburn 5476: } else {
1.1064 raeburn 5477: push(@rolecodes,$$role);
1.1002 raeburn 5478: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5479: }
1.1064 raeburn 5480: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5481: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5482: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5483: }
5484: }
1.1034 raeburn 5485: $$tstatus = 'is';
1.1002 raeburn 5486: }
1.994 raeburn 5487: }
5488: if ($$tend) {
1.1104 raeburn 5489: if ($$tend<$update) {
1.994 raeburn 5490: $$tstatus='expired';
5491: } elsif ($$tend<$now) {
5492: $$tstatus='will_not';
5493: }
5494: }
5495: }
5496: }
5497: }
5498:
1.1104 raeburn 5499: sub get_groups_roles {
5500: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5501: return unless((ref($cdom_courseroles) eq 'HASH') &&
5502: (ref($rolecodes) eq 'ARRAY') &&
5503: (ref($groups_roles) eq 'HASH'));
5504: if (keys(%{$cdom_courseroles}) > 0) {
5505: my ($cnum) = ($rest =~ /^($match_courseid)/);
5506: if ($cdom ne '' && $cnum ne '') {
5507: foreach my $key (keys(%{$cdom_courseroles})) {
5508: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5509: my $crsrole = $1;
5510: my $crssec = $2;
5511: if ($crsrole =~ /^cr/) {
5512: unless (grep(/^cr$/,@{$rolecodes})) {
5513: push(@{$rolecodes},'cr');
5514: }
5515: } else {
5516: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5517: push(@{$rolecodes},$crsrole);
5518: }
5519: }
5520: my $rolekey = "$crsrole./$cdom/$cnum";
5521: if ($crssec ne '') {
5522: $rolekey .= "/$crssec";
5523: }
5524: $rolekey .= './';
5525: $groups_roles->{$rolekey} = $rolecodes;
5526: }
5527: }
5528: }
5529: }
5530: return;
5531: }
5532:
5533: sub delete_env_groupprivs {
5534: my ($where,$courseroles,$possroles) = @_;
5535: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5536: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5537: unless (ref($courseroles->{$udom}) eq 'HASH') {
5538: %{$courseroles->{$udom}} =
5539: &get_my_roles('','','userroles',['active'],
5540: $possroles,[$udom],1);
5541: }
5542: if (ref($courseroles->{$udom}) eq 'HASH') {
5543: foreach my $item (keys(%{$courseroles->{$udom}})) {
5544: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5545: my $area = '/'.$cdom.'/'.$cnum;
5546: my $privkey = "user.priv.$crsrole.$area";
5547: if ($crssec ne '') {
5548: $privkey .= '/'.$crssec;
5549: }
5550: $privkey .= ".$area/$group";
5551: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5552: }
5553: }
5554: return;
5555: }
5556:
1.994 raeburn 5557: sub check_adhoc_privs {
1.1104 raeburn 5558: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5559: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5560: my $setprivs;
1.994 raeburn 5561: if ($env{$cckey}) {
5562: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5563: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5564: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5565: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5566: $setprivs = 1;
1.994 raeburn 5567: }
5568: } else {
1.1088 raeburn 5569: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5570: $setprivs = 1;
1.994 raeburn 5571: }
1.1185 raeburn 5572: return $setprivs;
1.994 raeburn 5573: }
5574:
5575: sub set_adhoc_privileges {
5576: # role can be cc or ca
1.1088 raeburn 5577: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5578: my $area = '/'.$dcdom.'/'.$pickedcourse;
5579: my $spec = $role.'.'.$area;
5580: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5581: $env{'user.name'},1);
1.994 raeburn 5582: my %ccrole = ();
5583: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5584: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5585: &appenv(\%userroles,[$role,'cm']);
5586: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5587: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5588: &appenv( {'request.role' => $spec,
5589: 'request.role.domain' => $dcdom,
5590: 'request.course.sec' => ''
5591: }
5592: );
5593: my $tadv=0;
5594: if (&allowed('adv') eq 'F') { $tadv=1; }
5595: &appenv({'request.role.adv' => $tadv});
5596: }
1.994 raeburn 5597: }
5598:
1.12 www 5599: # --------------------------------------------------------------- get interface
5600:
5601: sub get {
1.131 albertel 5602: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5603: my $items='';
1.800 albertel 5604: foreach my $item (@$storearr) {
5605: $items.=&escape($item).'&';
1.191 harris41 5606: }
1.12 www 5607: $items=~s/\&$//;
1.620 albertel 5608: if (!$udomain) { $udomain=$env{'user.domain'}; }
5609: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5610: my $uhome=&homeserver($uname,$udomain);
5611:
1.133 albertel 5612: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5613: my @pairs=split(/\&/,$rep);
1.273 albertel 5614: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5615: return @pairs;
5616: }
1.15 www 5617: my %returnhash=();
1.42 www 5618: my $i=0;
1.800 albertel 5619: foreach my $item (@$storearr) {
5620: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5621: $i++;
1.191 harris41 5622: }
1.15 www 5623: return %returnhash;
1.27 www 5624: }
5625:
5626: # --------------------------------------------------------------- del interface
5627:
5628: sub del {
1.133 albertel 5629: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5630: my $items='';
1.800 albertel 5631: foreach my $item (@$storearr) {
5632: $items.=&escape($item).'&';
1.191 harris41 5633: }
1.984 neumanie 5634:
1.27 www 5635: $items=~s/\&$//;
1.620 albertel 5636: if (!$udomain) { $udomain=$env{'user.domain'}; }
5637: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5638: my $uhome=&homeserver($uname,$udomain);
5639: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5640: }
5641:
5642: # -------------------------------------------------------------- dump interface
5643:
1.1180 droeschl 5644: sub unserialize {
5645: my ($rep, $escapedkeys) = @_;
5646:
5647: return {} if $rep =~ /^error/;
5648:
5649: my %returnhash=();
1.1252 raeburn 5650: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5651: my ($key, $value) = split(/=/, $item, 2);
5652: $key = unescape($key) unless $escapedkeys;
5653: next if $key =~ /^error: 2 /;
1.1252 raeburn 5654: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5655: }
5656: #return %returnhash;
5657: return \%returnhash;
5658: }
5659:
5660: # see Lond::dump_with_regexp
5661: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5662: sub dump {
1.1180 droeschl 5663: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5664: if (!$udomain) { $udomain=$env{'user.domain'}; }
5665: if (!$uname) { $uname=$env{'user.name'}; }
5666: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5667:
1.1266 raeburn 5668: if ($regexp) {
5669: $regexp=&escape($regexp);
5670: } else {
5671: $regexp='.';
5672: }
1.1180 droeschl 5673: if (grep { $_ eq $uhome } current_machine_ids()) {
5674: # user is hosted on this machine
1.1266 raeburn 5675: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5676: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5677: return %{unserialize($reply, $escapedkeys)};
5678: }
1.1166 raeburn 5679: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5680: my @pairs=split(/\&/,$rep);
5681: my %returnhash=();
1.1098 foxr 5682: if (!($rep =~ /^error/ )) {
5683: foreach my $item (@pairs) {
5684: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5685: $key = unescape($key) unless $escapedkeys;
5686: #$key = &unescape($key);
1.1098 foxr 5687: next if ($key =~ /^error: 2 /);
5688: $returnhash{$key}=&thaw_unescape($value);
5689: }
1.755 albertel 5690: }
5691: return %returnhash;
1.407 www 5692: }
5693:
1.1098 foxr 5694:
1.717 albertel 5695: # --------------------------------------------------------- dumpstore interface
5696:
5697: sub dumpstore {
5698: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5699: # same as dump but keys must be escaped. They may contain colon separated
5700: # lists of values that may themself contain colons (e.g. symbs).
5701: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5702: }
5703:
1.407 www 5704: # -------------------------------------------------------------- keys interface
5705:
5706: sub getkeys {
5707: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5708: if (!$udomain) { $udomain=$env{'user.domain'}; }
5709: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5710: my $uhome=&homeserver($uname,$udomain);
5711: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5712: my @keyarray=();
1.800 albertel 5713: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5714: next if ($key =~ /^error: 2 /);
1.800 albertel 5715: push(@keyarray,&unescape($key));
1.407 www 5716: }
5717: return @keyarray;
1.318 matthew 5718: }
5719:
1.319 matthew 5720: # --------------------------------------------------------------- currentdump
5721: sub currentdump {
1.328 matthew 5722: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5723: $courseid = $env{'request.course.id'} if (! defined($courseid));
5724: $sdom = $env{'user.domain'} if (! defined($sdom));
5725: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5726: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5727: my $rep;
5728:
5729: if (grep { $_ eq $uhome } current_machine_ids()) {
5730: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5731: $courseid)));
5732: } else {
5733: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5734: }
5735:
1.318 matthew 5736: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5737: #
1.318 matthew 5738: my %returnhash=();
1.319 matthew 5739: #
5740: if ($rep eq "unknown_cmd") {
5741: # an old lond will not know currentdump
5742: # Do a dump and make it look like a currentdump
1.822 albertel 5743: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5744: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5745: my %hash = @tmp;
5746: @tmp=();
1.424 matthew 5747: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5748: } else {
5749: my @pairs=split(/\&/,$rep);
1.800 albertel 5750: foreach my $pair (@pairs) {
5751: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5752: my ($symb,$param) = split(/:/,$key);
5753: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5754: &thaw_unescape($value);
1.319 matthew 5755: }
1.191 harris41 5756: }
1.12 www 5757: return %returnhash;
1.424 matthew 5758: }
5759:
5760: sub convert_dump_to_currentdump{
5761: my %hash = %{shift()};
5762: my %returnhash;
5763: # Code ripped from lond, essentially. The only difference
5764: # here is the unescaping done by lonnet::dump(). Conceivably
5765: # we might run in to problems with parameter names =~ /^v\./
5766: while (my ($key,$value) = each(%hash)) {
5767: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5768: $symb = &unescape($symb);
5769: $param = &unescape($param);
1.424 matthew 5770: next if ($v eq 'version' || $symb eq 'keys');
5771: next if (exists($returnhash{$symb}) &&
5772: exists($returnhash{$symb}->{$param}) &&
5773: $returnhash{$symb}->{'v.'.$param} > $v);
5774: $returnhash{$symb}->{$param}=$value;
5775: $returnhash{$symb}->{'v.'.$param}=$v;
5776: }
5777: #
5778: # Remove all of the keys in the hashes which keep track of
5779: # the version of the parameter.
5780: while (my ($symb,$param_hash) = each(%returnhash)) {
5781: # use a foreach because we are going to delete from the hash.
5782: foreach my $key (keys(%$param_hash)) {
5783: delete($param_hash->{$key}) if ($key =~ /^v\./);
5784: }
5785: }
5786: return \%returnhash;
1.12 www 5787: }
5788:
1.627 albertel 5789: # ------------------------------------------------------ critical inc interface
5790:
5791: sub cinc {
5792: return &inc(@_,'critical');
5793: }
5794:
1.449 matthew 5795: # --------------------------------------------------------------- inc interface
5796:
5797: sub inc {
1.627 albertel 5798: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5799: if (!$udomain) { $udomain=$env{'user.domain'}; }
5800: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5801: my $uhome=&homeserver($uname,$udomain);
5802: my $items='';
5803: if (! ref($store)) {
5804: # got a single value, so use that instead
5805: $items = &escape($store).'=&';
5806: } elsif (ref($store) eq 'SCALAR') {
5807: $items = &escape($$store).'=&';
5808: } elsif (ref($store) eq 'ARRAY') {
5809: $items = join('=&',map {&escape($_);} @{$store});
5810: } elsif (ref($store) eq 'HASH') {
5811: while (my($key,$value) = each(%{$store})) {
5812: $items.= &escape($key).'='.&escape($value).'&';
5813: }
5814: }
5815: $items=~s/\&$//;
1.627 albertel 5816: if ($critical) {
5817: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5818: } else {
5819: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5820: }
1.449 matthew 5821: }
5822:
1.12 www 5823: # --------------------------------------------------------------- put interface
5824:
5825: sub put {
1.134 albertel 5826: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5827: if (!$udomain) { $udomain=$env{'user.domain'}; }
5828: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5829: my $uhome=&homeserver($uname,$udomain);
1.12 www 5830: my $items='';
1.800 albertel 5831: foreach my $item (keys(%$storehash)) {
5832: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5833: }
1.12 www 5834: $items=~s/\&$//;
1.134 albertel 5835: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5836: }
5837:
1.631 albertel 5838: # ------------------------------------------------------------ newput interface
5839:
5840: sub newput {
5841: my ($namespace,$storehash,$udomain,$uname)=@_;
5842: if (!$udomain) { $udomain=$env{'user.domain'}; }
5843: if (!$uname) { $uname=$env{'user.name'}; }
5844: my $uhome=&homeserver($uname,$udomain);
5845: my $items='';
5846: foreach my $key (keys(%$storehash)) {
5847: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5848: }
5849: $items=~s/\&$//;
5850: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5851: }
5852:
5853: # --------------------------------------------------------- putstore interface
5854:
1.524 raeburn 5855: sub putstore {
1.1269 raeburn 5856: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5857: if (!$udomain) { $udomain=$env{'user.domain'}; }
5858: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5859: my $uhome=&homeserver($uname,$udomain);
5860: my $items='';
1.715 albertel 5861: foreach my $key (keys(%$storehash)) {
5862: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5863: }
1.715 albertel 5864: $items=~s/\&$//;
1.716 albertel 5865: my $esc_symb=&escape($symb);
5866: my $esc_v=&escape($version);
1.715 albertel 5867: my $reply =
1.716 albertel 5868: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5869: $uhome);
1.1269 raeburn 5870: if (($tolog) && ($reply eq 'ok')) {
5871: my $namevalue='';
5872: foreach my $key (keys(%{$storehash})) {
5873: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5874: }
5875: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5876: '&host='.&escape($perlvar{'lonHostID'}).
5877: '&version='.$esc_v.
5878: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5879: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5880: }
1.715 albertel 5881: if ($reply eq 'unknown_cmd') {
1.716 albertel 5882: # gfall back to way things use to be done
1.715 albertel 5883: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5884: $uname);
1.524 raeburn 5885: }
1.715 albertel 5886: return $reply;
5887: }
5888:
5889: sub old_putstore {
1.716 albertel 5890: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5891: if (!$udomain) { $udomain=$env{'user.domain'}; }
5892: if (!$uname) { $uname=$env{'user.name'}; }
5893: my $uhome=&homeserver($uname,$udomain);
5894: my %newstorehash;
1.800 albertel 5895: foreach my $item (keys(%$storehash)) {
5896: my $key = $version.':'.&escape($symb).':'.$item;
5897: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5898: }
5899: my $items='';
5900: my %allitems = ();
1.800 albertel 5901: foreach my $item (keys(%newstorehash)) {
5902: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5903: my $key = $1.':keys:'.$2;
5904: $allitems{$key} .= $3.':';
5905: }
1.800 albertel 5906: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5907: }
1.800 albertel 5908: foreach my $item (keys(%allitems)) {
5909: $allitems{$item} =~ s/\:$//;
5910: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5911: }
5912: $items=~s/\&$//;
5913: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5914: }
5915:
1.47 www 5916: # ------------------------------------------------------ critical put interface
5917:
5918: sub cput {
1.134 albertel 5919: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5920: if (!$udomain) { $udomain=$env{'user.domain'}; }
5921: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5922: my $uhome=&homeserver($uname,$udomain);
1.47 www 5923: my $items='';
1.800 albertel 5924: foreach my $item (keys(%$storehash)) {
5925: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5926: }
1.47 www 5927: $items=~s/\&$//;
1.134 albertel 5928: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5929: }
5930:
5931: # -------------------------------------------------------------- eget interface
5932:
5933: sub eget {
1.133 albertel 5934: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5935: my $items='';
1.800 albertel 5936: foreach my $item (@$storearr) {
5937: $items.=&escape($item).'&';
1.191 harris41 5938: }
1.12 www 5939: $items=~s/\&$//;
1.620 albertel 5940: if (!$udomain) { $udomain=$env{'user.domain'}; }
5941: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5942: my $uhome=&homeserver($uname,$udomain);
5943: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5944: my @pairs=split(/\&/,$rep);
5945: my %returnhash=();
1.42 www 5946: my $i=0;
1.800 albertel 5947: foreach my $item (@$storearr) {
5948: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5949: $i++;
1.191 harris41 5950: }
1.12 www 5951: return %returnhash;
5952: }
5953:
1.667 albertel 5954: # ------------------------------------------------------------ tmpput interface
5955: sub tmpput {
1.802 raeburn 5956: my ($storehash,$server,$context)=@_;
1.667 albertel 5957: my $items='';
1.800 albertel 5958: foreach my $item (keys(%$storehash)) {
5959: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5960: }
5961: $items=~s/\&$//;
1.802 raeburn 5962: if (defined($context)) {
5963: $items .= ':'.&escape($context);
5964: }
1.667 albertel 5965: return &reply("tmpput:$items",$server);
5966: }
5967:
5968: # ------------------------------------------------------------ tmpget interface
5969: sub tmpget {
1.688 albertel 5970: my ($token,$server)=@_;
5971: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5972: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5973: my %returnhash;
5974: foreach my $item (split(/\&/,$rep)) {
5975: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5976: next if ($key =~ /^error: 2 /);
1.667 albertel 5977: $returnhash{&unescape($key)}=&thaw_unescape($value);
5978: }
5979: return %returnhash;
5980: }
5981:
1.1113 raeburn 5982: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5983: sub tmpdel {
5984: my ($token,$server)=@_;
5985: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5986: return &reply("tmpdel:$token",$server);
5987: }
5988:
1.1198 raeburn 5989: # ------------------------------------------------------------ get_timebased_id
5990:
5991: sub get_timebased_id {
5992: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5993: $maxtries) = @_;
5994: my ($newid,$error,$dellock);
5995: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5996: return ('','ok','invalid call to get suffix');
5997: }
5998:
5999: # set defaults for any optional args for which values were not supplied
6000: if ($who eq '') {
6001: $who = $env{'user.name'}.':'.$env{'user.domain'};
6002: }
6003: if (!$locktries) {
6004: $locktries = 3;
6005: }
6006: if (!$maxtries) {
6007: $maxtries = 10;
6008: }
6009:
6010: if (($cdom eq '') || ($cnum eq '')) {
6011: if ($env{'request.course.id'}) {
6012: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6013: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6014: }
6015: if (($cdom eq '') || ($cnum eq '')) {
6016: return ('','ok','call to get suffix not in course context');
6017: }
6018: }
6019:
6020: # construct locking item
6021: my $lockhash = {
6022: $prefix."\0".'locked_'.$keyid => $who,
6023: };
6024: my $tries = 0;
6025:
6026: # attempt to get lock on nohist_$namespace file
6027: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6028: while (($gotlock ne 'ok') && $tries <$locktries) {
6029: $tries ++;
6030: sleep 1;
6031: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6032: }
6033:
6034: # attempt to get unique identifier, based on current timestamp
6035: if ($gotlock eq 'ok') {
6036: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6037: my $id = time;
6038: $newid = $id;
1.1268 raeburn 6039: if ($idtype eq 'addcode') {
6040: $newid .= &sixnum_code();
6041: }
1.1198 raeburn 6042: my $idtries = 0;
6043: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6044: if ($idtype eq 'concat') {
6045: $newid = $id.$idtries;
1.1268 raeburn 6046: } elsif ($idtype eq 'addcode') {
6047: $newid = $newid.&sixnum_code();
1.1198 raeburn 6048: } else {
6049: $newid ++;
6050: }
6051: $idtries ++;
6052: }
6053: if (!exists($inuse{$prefix."\0".$newid})) {
6054: my %new_item = (
6055: $prefix."\0".$newid => $who,
6056: );
6057: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6058: $cdom,$cnum);
6059: if ($putresult ne 'ok') {
6060: undef($newid);
6061: $error = 'error saving new item: '.$putresult;
6062: }
6063: } else {
1.1268 raeburn 6064: undef($newid);
1.1198 raeburn 6065: $error = ('error: no unique suffix available for the new item ');
6066: }
6067: # remove lock
6068: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6069: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6070: } else {
6071: $error = "error: could not obtain lockfile\n";
6072: $dellock = 'ok';
1.1276 raeburn 6073: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6074: $dellock = 'nolock';
6075: }
1.1198 raeburn 6076: }
6077: return ($newid,$dellock,$error);
6078: }
6079:
1.1268 raeburn 6080: sub sixnum_code {
6081: my $code;
6082: for (0..6) {
6083: $code .= int( rand(9) );
6084: }
6085: return $code;
6086: }
6087:
1.765 albertel 6088: # -------------------------------------------------- portfolio access checking
6089:
6090: sub portfolio_access {
1.1270 raeburn 6091: my ($requrl,$clientip) = @_;
1.765 albertel 6092: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6093: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6094: if ($result) {
6095: my %setters;
6096: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6097: my ($startblock,$endblock) =
6098: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6099: if ($startblock && $endblock) {
6100: return 'B';
6101: }
6102: } else {
6103: my ($startblock,$endblock) =
6104: &Apache::loncommon::blockcheck(\%setters,'port');
6105: if ($startblock && $endblock) {
6106: return 'B';
6107: }
6108: }
6109: }
1.765 albertel 6110: if ($result eq 'ok') {
1.766 albertel 6111: return 'F';
1.765 albertel 6112: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6113: return 'A';
1.765 albertel 6114: }
1.766 albertel 6115: return '';
1.765 albertel 6116: }
6117:
6118: sub get_portfolio_access {
1.1270 raeburn 6119: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6120:
6121: if (!ref($access_hash)) {
6122: my $current_perms = &get_portfile_permissions($udom,$unum);
6123: my %access_controls = &get_access_controls($current_perms,$group,
6124: $file_name);
6125: $access_hash = $access_controls{$file_name};
6126: }
6127:
1.1270 raeburn 6128: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6129: my $now = time;
6130: if (ref($access_hash) eq 'HASH') {
6131: foreach my $key (keys(%{$access_hash})) {
6132: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6133: if ($start > $now) {
6134: next;
6135: }
6136: if ($end && $end<$now) {
6137: next;
6138: }
6139: if ($scope eq 'public') {
6140: $public = $key;
6141: last;
6142: } elsif ($scope eq 'guest') {
6143: $guest = $key;
6144: } elsif ($scope eq 'domains') {
6145: push(@domains,$key);
6146: } elsif ($scope eq 'users') {
6147: push(@users,$key);
6148: } elsif ($scope eq 'course') {
6149: push(@courses,$key);
6150: } elsif ($scope eq 'group') {
6151: push(@groups,$key);
1.1270 raeburn 6152: } elsif ($scope eq 'ip') {
6153: push(@ips,$key);
1.765 albertel 6154: }
6155: }
6156: if ($public) {
6157: return 'ok';
1.1270 raeburn 6158: } elsif (@ips > 0) {
6159: my $allowed;
6160: foreach my $ipkey (@ips) {
6161: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6162: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6163: $allowed = 1;
6164: last;
6165: }
6166: }
6167: }
6168: if ($allowed) {
6169: return 'ok';
6170: }
1.765 albertel 6171: }
6172: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6173: if ($guest) {
6174: return $guest;
6175: }
6176: } else {
6177: if (@domains > 0) {
6178: foreach my $domkey (@domains) {
6179: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6180: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6181: return 'ok';
6182: }
6183: }
6184: }
6185: }
6186: if (@users > 0) {
6187: foreach my $userkey (@users) {
1.865 raeburn 6188: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6189: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6190: if (ref($item) eq 'HASH') {
6191: if (($item->{'uname'} eq $env{'user.name'}) &&
6192: ($item->{'udom'} eq $env{'user.domain'})) {
6193: return 'ok';
6194: }
6195: }
6196: }
6197: }
1.765 albertel 6198: }
6199: }
6200: my %roleshash;
6201: my @courses_and_groups = @courses;
6202: push(@courses_and_groups,@groups);
6203: if (@courses_and_groups > 0) {
6204: my (%allgroups,%allroles);
6205: my ($start,$end,$role,$sec,$group);
6206: foreach my $envkey (%env) {
1.1060 raeburn 6207: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6208: my $cid = $2.'_'.$3;
6209: if ($1 eq 'gr') {
6210: $group = $4;
6211: $allgroups{$cid}{$group} = $env{$envkey};
6212: } else {
6213: if ($4 eq '') {
6214: $sec = 'none';
6215: } else {
6216: $sec = $4;
6217: }
6218: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6219: }
1.811 albertel 6220: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6221: my $cid = $2.'_'.$3;
6222: if ($4 eq '') {
6223: $sec = 'none';
6224: } else {
6225: $sec = $4;
6226: }
6227: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6228: }
6229: }
6230: if (keys(%allroles) == 0) {
6231: return;
6232: }
6233: foreach my $key (@courses_and_groups) {
6234: my %content = %{$$access_hash{$key}};
6235: my $cnum = $content{'number'};
6236: my $cdom = $content{'domain'};
6237: my $cid = $cdom.'_'.$cnum;
6238: if (!exists($allroles{$cid})) {
6239: next;
6240: }
6241: foreach my $role_id (keys(%{$content{'roles'}})) {
6242: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6243: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6244: my @status = @{$content{'roles'}{$role_id}{'access'}};
6245: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6246: foreach my $role (keys(%{$allroles{$cid}})) {
6247: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6248: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6249: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6250: if (grep/^all$/,@sections) {
6251: return 'ok';
6252: } else {
6253: if (grep/^$sec$/,@sections) {
6254: return 'ok';
6255: }
6256: }
6257: }
6258: }
6259: if (keys(%{$allgroups{$cid}}) == 0) {
6260: if (grep/^none$/,@groups) {
6261: return 'ok';
6262: }
6263: } else {
6264: if (grep/^all$/,@groups) {
6265: return 'ok';
6266: }
6267: foreach my $group (keys(%{$allgroups{$cid}})) {
6268: if (grep/^$group$/,@groups) {
6269: return 'ok';
6270: }
6271: }
6272: }
6273: }
6274: }
6275: }
6276: }
6277: }
6278: if ($guest) {
6279: return $guest;
6280: }
6281: }
6282: }
6283: return;
6284: }
6285:
6286: sub course_group_datechecker {
6287: my ($dates,$now,$status) = @_;
6288: my ($start,$end) = split(/\./,$dates);
6289: if (!$start && !$end) {
6290: return 'ok';
6291: }
6292: if (grep/^active$/,@{$status}) {
6293: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6294: return 'ok';
6295: }
6296: }
6297: if (grep/^previous$/,@{$status}) {
6298: if ($end > $now ) {
6299: return 'ok';
6300: }
6301: }
6302: if (grep/^future$/,@{$status}) {
6303: if ($start > $now) {
6304: return 'ok';
6305: }
6306: }
6307: return;
6308: }
6309:
6310: sub parse_portfolio_url {
6311: my ($url) = @_;
6312:
6313: my ($type,$udom,$unum,$group,$file_name);
6314:
1.823 albertel 6315: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6316: $type = 1;
6317: $udom = $1;
6318: $unum = $2;
6319: $file_name = $3;
1.823 albertel 6320: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6321: $type = 2;
6322: $udom = $1;
6323: $unum = $2;
6324: $group = $3;
6325: $file_name = $3.'/'.$4;
6326: }
6327: if (wantarray) {
6328: return ($type,$udom,$unum,$file_name,$group);
6329: }
6330: return $type;
6331: }
6332:
6333: sub is_portfolio_url {
6334: my ($url) = @_;
6335: return scalar(&parse_portfolio_url($url));
6336: }
6337:
1.798 raeburn 6338: sub is_portfolio_file {
6339: my ($file) = @_;
1.820 raeburn 6340: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6341: return 1;
6342: }
6343: return;
6344: }
6345:
1.976 raeburn 6346: sub usertools_access {
1.1084 raeburn 6347: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6348: my ($access,%tools);
6349: if ($context eq '') {
6350: $context = 'tools';
6351: }
6352: if ($context eq 'requestcourses') {
6353: %tools = (
6354: official => 1,
6355: unofficial => 1,
1.1006 raeburn 6356: community => 1,
1.1246 raeburn 6357: textbook => 1,
1.985 raeburn 6358: );
1.1183 raeburn 6359: } elsif ($context eq 'requestauthor') {
6360: %tools = (
6361: requestauthor => 1,
6362: );
1.985 raeburn 6363: } else {
6364: %tools = (
6365: aboutme => 1,
6366: blog => 1,
1.1177 raeburn 6367: webdav => 1,
1.985 raeburn 6368: portfolio => 1,
6369: );
6370: }
1.976 raeburn 6371: return if (!defined($tools{$tool}));
6372:
1.1242 raeburn 6373: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6374: $udom = $env{'user.domain'};
6375: $uname = $env{'user.name'};
6376: }
6377:
1.978 raeburn 6378: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6379: if ($action ne 'reload') {
1.985 raeburn 6380: if ($context eq 'requestcourses') {
6381: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6382: } elsif ($context eq 'requestauthor') {
6383: return $env{'environment.canrequest.author'};
1.985 raeburn 6384: } else {
6385: return $env{'environment.availabletools.'.$tool};
6386: }
6387: }
1.976 raeburn 6388: }
6389:
1.1183 raeburn 6390: my ($toolstatus,$inststatus,$envkey);
6391: if ($context eq 'requestauthor') {
6392: $envkey = $context;
6393: } else {
6394: $envkey = $context.'.'.$tool;
6395: }
1.976 raeburn 6396:
1.985 raeburn 6397: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6398: ($action ne 'reload')) {
1.1183 raeburn 6399: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6400: $inststatus = $env{'environment.inststatus'};
6401: } else {
1.1084 raeburn 6402: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6403: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6404: $inststatus = $userenvref->{'inststatus'};
6405: } else {
1.1183 raeburn 6406: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6407: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6408: $inststatus = $userenv{'inststatus'};
6409: }
1.976 raeburn 6410: }
6411:
6412: if ($toolstatus ne '') {
6413: if ($toolstatus) {
6414: $access = 1;
6415: } else {
6416: $access = 0;
6417: }
6418: return $access;
6419: }
6420:
1.1084 raeburn 6421: my ($is_adv,%domdef);
6422: if (ref($is_advref) eq 'HASH') {
6423: $is_adv = $is_advref->{'is_adv'};
6424: } else {
6425: $is_adv = &is_advanced_user($udom,$uname);
6426: }
6427: if (ref($domdefref) eq 'HASH') {
6428: %domdef = %{$domdefref};
6429: } else {
6430: %domdef = &get_domain_defaults($udom);
6431: }
1.976 raeburn 6432: if (ref($domdef{$tool}) eq 'HASH') {
6433: if ($is_adv) {
6434: if ($domdef{$tool}{'_LC_adv'} ne '') {
6435: if ($domdef{$tool}{'_LC_adv'}) {
6436: $access = 1;
6437: } else {
6438: $access = 0;
6439: }
6440: return $access;
6441: }
6442: }
6443: if ($inststatus ne '') {
6444: my ($hasaccess,$hasnoaccess);
6445: foreach my $affiliation (split(/:/,$inststatus)) {
6446: if ($domdef{$tool}{$affiliation} ne '') {
6447: if ($domdef{$tool}{$affiliation}) {
6448: $hasaccess = 1;
6449: } else {
6450: $hasnoaccess = 1;
6451: }
6452: }
6453: }
6454: if ($hasaccess || $hasnoaccess) {
6455: if ($hasaccess) {
6456: $access = 1;
6457: } elsif ($hasnoaccess) {
6458: $access = 0;
6459: }
6460: return $access;
6461: }
6462: } else {
6463: if ($domdef{$tool}{'default'} ne '') {
6464: if ($domdef{$tool}{'default'}) {
6465: $access = 1;
6466: } elsif ($domdef{$tool}{'default'} == 0) {
6467: $access = 0;
6468: }
6469: return $access;
6470: }
6471: }
6472: } else {
1.1177 raeburn 6473: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6474: $access = 1;
6475: } else {
6476: $access = 0;
6477: }
1.976 raeburn 6478: return $access;
6479: }
6480: }
6481:
1.1050 raeburn 6482: sub is_course_owner {
6483: my ($cdom,$cnum,$udom,$uname) = @_;
6484: if (($udom eq '') || ($uname eq '')) {
6485: $udom = $env{'user.domain'};
6486: $uname = $env{'user.name'};
6487: }
6488: unless (($udom eq '') || ($uname eq '')) {
6489: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6490: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6491: return 1;
6492: } else {
6493: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6494: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6495: return 1;
6496: }
6497: }
6498: }
6499: }
6500: return;
6501: }
6502:
1.976 raeburn 6503: sub is_advanced_user {
6504: my ($udom,$uname) = @_;
1.1085 raeburn 6505: if ($udom ne '' && $uname ne '') {
6506: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6507: if (wantarray) {
6508: return ($env{'user.adv'},$env{'user.author'});
6509: } else {
6510: return $env{'user.adv'};
6511: }
1.1085 raeburn 6512: }
6513: }
1.976 raeburn 6514: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6515: my %allroles;
1.1128 raeburn 6516: my ($is_adv,$is_author);
1.976 raeburn 6517: foreach my $role (keys(%roleshash)) {
6518: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6519: my $area = '/'.$tdomain.'/'.$trest;
6520: if ($sec ne '') {
6521: $area .= '/'.$sec;
6522: }
6523: if (($area ne '') && ($trole ne '')) {
6524: my $spec=$trole.'.'.$area;
6525: if ($trole =~ /^cr\//) {
6526: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6527: } elsif ($trole ne 'gr') {
6528: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6529: }
1.1128 raeburn 6530: if ($trole eq 'au') {
6531: $is_author = 1;
6532: }
1.976 raeburn 6533: }
6534: }
6535: foreach my $role (keys(%allroles)) {
6536: last if ($is_adv);
6537: foreach my $item (split(/:/,$allroles{$role})) {
6538: if ($item ne '') {
6539: my ($privilege,$restrictions)=split(/&/,$item);
6540: if ($privilege eq 'adv') {
6541: $is_adv = 1;
6542: last;
6543: }
6544: }
6545: }
6546: }
1.1128 raeburn 6547: if (wantarray) {
6548: return ($is_adv,$is_author);
6549: }
1.976 raeburn 6550: return $is_adv;
6551: }
1.798 raeburn 6552:
1.1035 raeburn 6553: sub check_can_request {
1.1036 raeburn 6554: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6555: my $canreq = 0;
6556: my ($types,$typename) = &Apache::loncommon::course_types();
6557: my @options = ('approval','validate','autolimit');
6558: my $optregex = join('|',@options);
6559: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6560: foreach my $type (@{$types}) {
6561: if (&usertools_access($env{'user.name'},
6562: $env{'user.domain'},
6563: $type,undef,'requestcourses')) {
6564: $canreq ++;
1.1036 raeburn 6565: if (ref($request_domains) eq 'HASH') {
6566: push(@{$request_domains->{$type}},$env{'user.domain'});
6567: }
1.1035 raeburn 6568: if ($dom eq $env{'user.domain'}) {
6569: $can_request->{$type} = 1;
6570: }
6571: }
6572: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6573: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6574: if (@curr > 0) {
1.1036 raeburn 6575: foreach my $item (@curr) {
6576: if (ref($request_domains) eq 'HASH') {
6577: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6578: if ($otherdom ne '') {
6579: if (ref($request_domains->{$type}) eq 'ARRAY') {
6580: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6581: push(@{$request_domains->{$type}},$otherdom);
6582: }
6583: } else {
6584: push(@{$request_domains->{$type}},$otherdom);
6585: }
6586: }
6587: }
6588: }
6589: unless($dom eq $env{'user.domain'}) {
6590: $canreq ++;
1.1035 raeburn 6591: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6592: $can_request->{$type} = 1;
6593: }
6594: }
6595: }
6596: }
6597: }
6598: }
6599: return $canreq;
6600: }
6601:
1.341 www 6602: # ---------------------------------------------- Custom access rule evaluation
6603:
6604: sub customaccess {
6605: my ($priv,$uri)=@_;
1.807 albertel 6606: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6607: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6608: $udom = &LONCAPA::clean_domain($udom);
6609: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6610: my $access=0;
1.800 albertel 6611: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6612: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6613: if ($type eq 'user') {
6614: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6615: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6616: if ($tdom) {
6617: if ($tdom ne $env{'user.domain'}) { next; }
6618: }
1.896 albertel 6619: if ($tuname) {
6620: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6621: }
6622: $access=($effect eq 'allow');
6623: last;
6624: }
6625: } else {
6626: if ($role) {
6627: if ($role ne $urole) { next; }
6628: }
6629: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6630: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6631: if ($tdom) {
6632: if ($tdom ne $udom) { next; }
6633: }
6634: if ($tcrs) {
6635: if ($tcrs ne $ucrs) { next; }
6636: }
6637: if ($tsec) {
6638: if ($tsec ne $usec) { next; }
6639: }
6640: $access=($effect eq 'allow');
6641: last;
6642: }
6643: if ($realm eq '' && $role eq '') {
6644: $access=($effect eq 'allow');
6645: }
1.402 bowersj2 6646: }
1.341 www 6647: }
6648: return $access;
6649: }
6650:
1.103 harris41 6651: # ------------------------------------------------- Check for a user privilege
1.12 www 6652:
6653: sub allowed {
1.1281 raeburn 6654: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6655: my $ver_orguri=$uri;
1.439 www 6656: $uri=&deversion($uri);
1.152 www 6657: my $orguri=$uri;
1.52 www 6658: $uri=&declutter($uri);
1.809 raeburn 6659:
1.810 raeburn 6660: if ($priv eq 'evb') {
6661: # Evade communication block restrictions for specified role in a course
6662: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6663: return $1;
6664: } else {
6665: return;
6666: }
6667: }
6668:
1.620 albertel 6669: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6670: # Free bre access to adm and meta resources
1.775 albertel 6671: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6672: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6673: && ($priv eq 'bre')) {
1.14 www 6674: return 'F';
1.159 www 6675: }
6676:
1.545 banghart 6677: # Free bre access to user's own portfolio contents
1.714 raeburn 6678: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6679: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6680: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6681: my %setters;
6682: my ($startblock,$endblock) =
6683: &Apache::loncommon::blockcheck(\%setters,'port');
6684: if ($startblock && $endblock) {
6685: return 'B';
6686: } else {
6687: return 'F';
6688: }
1.545 banghart 6689: }
6690:
1.762 raeburn 6691: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6692: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6693: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6694: if (exists($env{'request.course.id'})) {
6695: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6696: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6697: if (($domain eq $cdom) && ($name eq $cnum)) {
6698: my $courseprivid=$env{'request.course.id'};
6699: $courseprivid=~s/\_/\//;
6700: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6701: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6702: return $1;
1.762 raeburn 6703: } else {
6704: if ($env{'request.course.sec'}) {
6705: $courseprivid.='/'.$env{'request.course.sec'};
6706: }
6707: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6708: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6709: return $2;
6710: }
1.714 raeburn 6711: }
6712: }
6713: }
6714: }
6715:
1.159 www 6716: # Free bre to public access
6717:
6718: if ($priv eq 'bre') {
1.238 www 6719: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6720: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6721: return 'F';
6722: }
1.238 www 6723: if ($copyright eq 'priv') {
6724: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6725: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6726: return '';
6727: }
6728: }
6729: if ($copyright eq 'domain') {
6730: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6731: unless (($env{'user.domain'} eq $1) ||
6732: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6733: return '';
6734: }
1.262 matthew 6735: }
1.620 albertel 6736: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6737: # Library role, so allow browsing of resources in this domain.
6738: return 'F';
1.238 www 6739: }
1.341 www 6740: if ($copyright eq 'custom') {
6741: unless (&customaccess($priv,$uri)) { return ''; }
6742: }
1.14 www 6743: }
1.264 matthew 6744: # Domain coordinator is trying to create a course
1.620 albertel 6745: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6746: # uri is the requested domain in this case.
6747: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6748: # a role of dc for the domain in question.
1.620 albertel 6749: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6750: }
1.29 www 6751:
1.52 www 6752: my $thisallowed='';
6753: my $statecond=0;
6754: my $courseprivid='';
6755:
1.1039 raeburn 6756: my $ownaccess;
1.1043 raeburn 6757: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6758: if (($priv eq 'bro') && ($env{'user.author'})) {
6759: if ($uri eq '') {
6760: $ownaccess = 1;
6761: } else {
6762: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6763: my $udom = $env{'user.domain'};
6764: my $uname = $env{'user.name'};
6765: if ($uri =~ m{^\Q$udom\E/?$}) {
6766: $ownaccess = 1;
1.1040 raeburn 6767: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6768: unless ($uri =~ m{\.\./}) {
6769: $ownaccess = 1;
6770: }
6771: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6772: my $now = time;
6773: if ($uri =~ m{^([^/]+)/?$}) {
6774: my $adom = $1;
6775: foreach my $key (keys(%env)) {
1.1042 raeburn 6776: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6777: my ($start,$end) = split('.',$env{$key});
6778: if (($now >= $start) && (!$end || $end < $now)) {
6779: $ownaccess = 1;
6780: last;
6781: }
6782: }
6783: }
6784: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6785: my $adom = $1;
6786: my $aname = $2;
1.1042 raeburn 6787: foreach my $role ('ca','aa') {
6788: if ($env{"user.role.$role./$adom/$aname"}) {
6789: my ($start,$end) =
6790: split('.',$env{"user.role.$role./$adom/$aname"});
6791: if (($now >= $start) && (!$end || $end < $now)) {
6792: $ownaccess = 1;
6793: last;
6794: }
1.1039 raeburn 6795: }
6796: }
6797: }
6798: }
6799: }
6800: }
6801: }
6802:
1.52 www 6803: # Course
6804:
1.620 albertel 6805: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6806: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6807: $thisallowed.=$1;
6808: }
1.52 www 6809: }
1.29 www 6810:
1.52 www 6811: # Domain
6812:
1.620 albertel 6813: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6814: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6815: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6816: $thisallowed.=$1;
6817: }
1.12 www 6818: }
1.52 www 6819:
1.1141 raeburn 6820: # User who is not author or co-author might still be able to edit
6821: # resource of an author in the domain (e.g., if Domain Coordinator).
6822: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6823: (&allowed('mdc',$env{'request.course.id'}))) {
6824: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6825: $thisallowed.=$1;
6826: }
6827: }
6828:
1.52 www 6829: # Course: uri itself is a course
1.66 www 6830: my $courseuri=$uri;
6831: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6832: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6833:
1.620 albertel 6834: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6835: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6836: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6837: $thisallowed.=$1;
6838: }
1.12 www 6839: }
1.29 www 6840:
1.665 albertel 6841: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6842: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6843: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6844: $thisallowed='';
1.671 raeburn 6845: my ($match)=&is_on_map($uri);
6846: if ($match) {
6847: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6848: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 6849: my $value = $1;
6850: if ($noblockcheck) {
6851: $thisallowed.=$value;
1.1162 raeburn 6852: } else {
1.1281 raeburn 6853: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6854: if (@blockers > 0) {
6855: $thisallowed = 'B';
6856: } else {
6857: $thisallowed.=$value;
6858: }
1.1162 raeburn 6859: }
1.671 raeburn 6860: }
6861: } else {
1.705 albertel 6862: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6863: if ($refuri) {
6864: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6865: $thisallowed='F';
1.671 raeburn 6866: } else {
6867: $refuri=&declutter($refuri);
6868: my ($match) = &is_on_map($refuri);
6869: if ($match) {
1.1281 raeburn 6870: if ($noblockcheck) {
6871: $thisallowed='F';
1.1162 raeburn 6872: } else {
1.1281 raeburn 6873: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6874: if (@blockers > 0) {
6875: $thisallowed = 'B';
6876: } else {
6877: $thisallowed='F';
6878: }
1.1162 raeburn 6879: }
1.671 raeburn 6880: }
1.669 raeburn 6881: }
1.671 raeburn 6882: }
6883: }
1.314 www 6884: }
1.492 albertel 6885:
1.766 albertel 6886: if ($priv eq 'bre'
6887: && $thisallowed ne 'F'
6888: && $thisallowed ne '2'
6889: && &is_portfolio_url($uri)) {
1.1270 raeburn 6890: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6891: }
1.1250 raeburn 6892:
1.52 www 6893: # Full access at system, domain or course-wide level? Exit.
1.29 www 6894: if ($thisallowed=~/F/) {
6895: return 'F';
6896: }
6897:
1.52 www 6898: # If this is generating or modifying users, exit with special codes
1.29 www 6899:
1.643 www 6900: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6901: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6902: my ($audom,$auname)=split('/',$uri);
1.643 www 6903: # no author name given, so this just checks on the general right to make a co-author in this domain
6904: unless ($auname) { return $thisallowed; }
6905: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6906: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6907: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6908: ($audom ne $env{'request.role.domain'}))) { return ''; }
6909: }
1.52 www 6910: return $thisallowed;
6911: }
6912: #
1.103 harris41 6913: # Gathered so far: system, domain and course wide privileges
1.52 www 6914: #
6915: # Course: See if uri or referer is an individual resource that is part of
6916: # the course
6917:
1.620 albertel 6918: if ($env{'request.course.id'}) {
1.232 www 6919:
1.620 albertel 6920: $courseprivid=$env{'request.course.id'};
6921: if ($env{'request.course.sec'}) {
6922: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6923: }
6924: $courseprivid=~s/\_/\//;
6925: my $checkreferer=1;
1.232 www 6926: my ($match,$cond)=&is_on_map($uri);
6927: if ($match) {
6928: $statecond=$cond;
1.620 albertel 6929: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6930: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6931: my $value = $1;
6932: if ($priv eq 'bre') {
1.1281 raeburn 6933: if ($noblockcheck) {
6934: $thisallowed.=$value;
1.1162 raeburn 6935: } else {
1.1281 raeburn 6936: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6937: if (@blockers > 0) {
6938: $thisallowed = 'B';
6939: } else {
6940: $thisallowed.=$value;
6941: }
1.1162 raeburn 6942: }
6943: } else {
6944: $thisallowed.=$value;
6945: }
1.52 www 6946: $checkreferer=0;
6947: }
1.29 www 6948: }
1.83 www 6949:
1.148 www 6950: if ($checkreferer) {
1.620 albertel 6951: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6952: unless ($refuri) {
1.800 albertel 6953: foreach my $key (keys(%env)) {
6954: if ($key=~/^httpref\..*\*/) {
6955: my $pattern=$key;
1.156 www 6956: $pattern=~s/^httpref\.\/res\///;
1.148 www 6957: $pattern=~s/\*/\[\^\/\]\+/g;
6958: $pattern=~s/\//\\\//g;
1.152 www 6959: if ($orguri=~/$pattern/) {
1.800 albertel 6960: $refuri=$env{$key};
1.148 www 6961: }
6962: }
1.191 harris41 6963: }
1.148 www 6964: }
1.232 www 6965:
1.148 www 6966: if ($refuri) {
1.152 www 6967: $refuri=&declutter($refuri);
1.232 www 6968: my ($match,$cond)=&is_on_map($refuri);
6969: if ($match) {
6970: my $refstatecond=$cond;
1.620 albertel 6971: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6972: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6973: my $value = $1;
6974: if ($priv eq 'bre') {
1.1281 raeburn 6975: if ($noblockcheck) {
6976: $thisallowed.=$value;
1.1162 raeburn 6977: } else {
1.1281 raeburn 6978: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6979: if (@blockers > 0) {
6980: $thisallowed = 'B';
6981: } else {
6982: $thisallowed.=$value;
6983: }
1.1162 raeburn 6984: }
6985: } else {
6986: $thisallowed.=$value;
6987: }
1.53 www 6988: $uri=$refuri;
6989: $statecond=$refstatecond;
1.52 www 6990: }
6991: }
1.148 www 6992: }
1.29 www 6993: }
1.52 www 6994: }
1.29 www 6995:
1.52 www 6996: #
1.103 harris41 6997: # Gathered now: all privileges that could apply, and condition number
1.52 www 6998: #
6999: #
7000: # Full or no access?
7001: #
1.29 www 7002:
1.52 www 7003: if ($thisallowed=~/F/) {
7004: return 'F';
7005: }
1.29 www 7006:
1.52 www 7007: unless ($thisallowed) {
7008: return '';
7009: }
1.29 www 7010:
1.52 www 7011: # Restrictions exist, deal with them
7012: #
7013: # C:according to course preferences
7014: # R:according to resource settings
7015: # L:unless locked
7016: # X:according to user session state
7017: #
7018:
7019: # Possibly locked functionality, check all courses
1.54 www 7020: # Locks might take effect only after 10 minutes cache expiration for other
7021: # courses, and 2 minutes for current course
1.52 www 7022:
7023: my $envkey;
7024: if ($thisallowed=~/L/) {
1.1000 raeburn 7025: foreach $envkey (keys(%env)) {
1.54 www 7026: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7027: my $courseid=$2;
7028: my $roleid=$1.'.'.$2;
1.92 www 7029: $courseid=~s/^\///;
1.54 www 7030: my $expiretime=600;
1.620 albertel 7031: if ($env{'request.role'} eq $roleid) {
1.54 www 7032: $expiretime=120;
7033: }
7034: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7035: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7036: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7037: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7038: }
1.620 albertel 7039: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7040: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7041: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7042: &log($env{'user.domain'},$env{'user.name'},
7043: $env{'user.home'},
1.57 www 7044: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7045: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7046: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7047: return '';
7048: }
7049: }
1.620 albertel 7050: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7051: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7052: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7053: &log($env{'user.domain'},$env{'user.name'},
7054: $env{'user.home'},
1.57 www 7055: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7056: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7057: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7058: return '';
7059: }
7060: }
7061: }
1.29 www 7062: }
1.52 www 7063: }
7064:
7065: #
7066: # Rest of the restrictions depend on selected course
7067: #
7068:
1.620 albertel 7069: unless ($env{'request.course.id'}) {
1.766 albertel 7070: if ($thisallowed eq 'A') {
7071: return 'A';
1.814 raeburn 7072: } elsif ($thisallowed eq 'B') {
7073: return 'B';
1.766 albertel 7074: } else {
7075: return '1';
7076: }
1.52 www 7077: }
1.29 www 7078:
1.52 www 7079: #
7080: # Now user is definitely in a course
7081: #
1.53 www 7082:
7083:
7084: # Course preferences
7085:
7086: if ($thisallowed=~/C/) {
1.620 albertel 7087: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7088: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7089: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7090: =~/\Q$rolecode\E/) {
1.1103 raeburn 7091: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7092: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7093: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7094: $env{'request.course.id'});
7095: }
1.237 www 7096: return '';
7097: }
7098:
1.620 albertel 7099: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7100: =~/\Q$unamedom\E/) {
1.1103 raeburn 7101: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7102: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7103: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7104: $env{'request.course.id'});
7105: }
1.54 www 7106: return '';
7107: }
1.53 www 7108: }
7109:
7110: # Resource preferences
7111:
7112: if ($thisallowed=~/R/) {
1.620 albertel 7113: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7114: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7115: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7116: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7117: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7118: }
7119: return '';
1.54 www 7120: }
1.53 www 7121: }
1.30 www 7122:
1.246 www 7123: # Restricted by state or randomout?
1.30 www 7124:
1.52 www 7125: if ($thisallowed=~/X/) {
1.620 albertel 7126: if ($env{'acc.randomout'}) {
1.579 albertel 7127: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7128: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7129: return '';
7130: }
1.247 www 7131: }
7132: if (&condval($statecond)) {
1.52 www 7133: return '2';
7134: } else {
7135: return '';
7136: }
7137: }
1.30 www 7138:
1.766 albertel 7139: if ($thisallowed eq 'A') {
7140: return 'A';
1.814 raeburn 7141: } elsif ($thisallowed eq 'B') {
7142: return 'B';
1.766 albertel 7143: }
1.52 www 7144: return 'F';
1.232 www 7145: }
1.1162 raeburn 7146:
1.1192 raeburn 7147: # ------------------------------------------- Check construction space access
7148:
7149: sub constructaccess {
7150: my ($url,$setpriv)=@_;
7151:
7152: # We do not allow editing of previous versions of files
7153: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7154:
7155: # Get username and domain from URL
7156: my ($ownername,$ownerdomain,$ownerhome);
7157:
7158: ($ownerdomain,$ownername) =
7159: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7160:
7161: # The URL does not really point to any authorspace, forget it
7162: unless (($ownername) && ($ownerdomain)) { return ''; }
7163:
7164: # Now we need to see if the user has access to the authorspace of
7165: # $ownername at $ownerdomain
7166:
7167: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7168: # Real author for this?
7169: $ownerhome = $env{'user.home'};
7170: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7171: return ($ownername,$ownerdomain,$ownerhome);
7172: }
7173: } else {
7174: # Co-author for this?
7175: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7176: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7177: $ownerhome = &homeserver($ownername,$ownerdomain);
7178: return ($ownername,$ownerdomain,$ownerhome);
7179: }
7180: }
7181:
7182: # We don't have any access right now. If we are not possibly going to do anything about this,
7183: # we might as well leave
7184: unless ($setpriv) { return ''; }
7185:
7186: # Backdoor access?
7187: my $allowed=&allowed('eco',$ownerdomain);
7188: # Nope
7189: unless ($allowed) { return ''; }
7190: # Looks like we may have access, but could be locked by the owner of the construction space
7191: if ($allowed eq 'U') {
7192: my %blocked=&get('environment',['domcoord.author'],
7193: $ownerdomain,$ownername);
7194: # Is blocked by owner
7195: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7196: }
7197: if (($allowed eq 'F') || ($allowed eq 'U')) {
7198: # Grant temporary access
7199: my $then=$env{'user.login.time'};
1.1209 raeburn 7200: my $update=$env{'user.update.time'};
1.1192 raeburn 7201: if (!$update) { $update = $then; }
7202: my $refresh=$env{'user.refresh.time'};
7203: if (!$refresh) { $refresh = $update; }
7204: my $now = time;
7205: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7206: $now,'ca','constructaccess');
7207: $ownerhome = &homeserver($ownername,$ownerdomain);
7208: return($ownername,$ownerdomain,$ownerhome);
7209: }
7210: # No business here
7211: return '';
7212: }
7213:
1.1282 raeburn 7214: # ----------------------------------------------------------- Content Blocking
7215:
7216: {
7217: # Caches for faster Course Contents display where content blocking
7218: # is in operation (i.e., interval param set) for timed quiz.
7219: #
7220: # User for whom data are being temporarily cached.
7221: my $cacheduser='';
7222: # Cached blockers for this user (a hash of blocking items).
7223: my %cachedblockers=();
7224: # When the data were last cached.
7225: my $cachedlast='';
7226:
7227: sub load_all_blockers {
7228: my ($uname,$udom,$blocks)=@_;
7229: if (($uname ne '') && ($udom ne '')) {
7230: if (($cacheduser eq $uname.':'.$udom) &&
7231: (abs($cachedlast-time)<5)) {
7232: return;
7233: }
7234: }
7235: $cachedlast=time;
7236: $cacheduser=$uname.':'.$udom;
7237: %cachedblockers = &get_commblock_resources($blocks);
7238: }
7239:
1.1162 raeburn 7240: sub get_comm_blocks {
7241: my ($cdom,$cnum) = @_;
7242: if ($cdom eq '' || $cnum eq '') {
7243: return unless ($env{'request.course.id'});
7244: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7245: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7246: }
7247: my %commblocks;
7248: my $hashid=$cdom.'_'.$cnum;
7249: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7250: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7251: %commblocks = %{$blocksref};
7252: } else {
7253: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7254: my $cachetime = 600;
7255: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7256: }
7257: return %commblocks;
7258: }
7259:
1.1282 raeburn 7260: sub get_commblock_resources {
7261: my ($blocks) = @_;
7262: my %blockers = ();
7263: return %blockers unless ($env{'request.course.id'});
7264: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7265: my %commblocks;
7266: if (ref($blocks) eq 'HASH') {
7267: %commblocks = %{$blocks};
7268: } else {
7269: %commblocks = &get_comm_blocks();
7270: }
1.1282 raeburn 7271: return %blockers unless (keys(%commblocks) > 0);
7272: my $navmap = Apache::lonnavmaps::navmap->new();
7273: return %blockers unless (ref($navmap));
1.1162 raeburn 7274: my $now = time;
7275: foreach my $block (keys(%commblocks)) {
7276: if ($block =~ /^(\d+)____(\d+)$/) {
7277: my ($start,$end) = ($1,$2);
7278: if ($start <= $now && $end >= $now) {
7279: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7280: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7281: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7282: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7283: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7284: }
7285: }
7286: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7287: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7288: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7289: }
7290: }
7291: }
7292: }
7293: }
7294: } elsif ($block =~ /^firstaccess____(.+)$/) {
7295: my $item = $1;
1.1163 raeburn 7296: my @to_test;
1.1162 raeburn 7297: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7298: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7299: my @interval;
7300: my $type = 'map';
7301: if ($item eq 'course') {
7302: $type = 'course';
7303: @interval=&EXT("resource.0.interval");
7304: } else {
7305: if ($item =~ /___\d+___/) {
7306: $type = 'resource';
7307: @interval=&EXT("resource.0.interval",$item);
7308: if (ref($navmap)) {
7309: my $res = $navmap->getBySymb($item);
7310: push(@to_test,$res);
7311: }
1.1162 raeburn 7312: } else {
1.1282 raeburn 7313: my $mapsymb = &symbread($item,1);
7314: if ($mapsymb) {
7315: if (ref($navmap)) {
7316: my $mapres = $navmap->getBySymb($mapsymb);
7317: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7318: foreach my $res (@to_test) {
7319: my $symb = $res->symb();
7320: next if ($symb eq $mapsymb);
7321: if ($symb ne '') {
7322: @interval=&EXT("resource.0.interval",$symb);
7323: if ($interval[1] eq 'map') {
7324: last;
1.1162 raeburn 7325: }
7326: }
7327: }
7328: }
7329: }
7330: }
1.1282 raeburn 7331: }
7332: if ($interval[0] =~ /^\d+$/) {
7333: my $first_access;
7334: if ($type eq 'resource') {
7335: $first_access=&get_first_access($interval[1],$item);
7336: } elsif ($type eq 'map') {
7337: $first_access=&get_first_access($interval[1],undef,$item);
7338: } else {
7339: $first_access=&get_first_access($interval[1]);
7340: }
7341: if ($first_access) {
7342: my $timesup = $first_access+$interval[0];
7343: if ($timesup > $now) {
7344: my $activeblock;
7345: foreach my $res (@to_test) {
1.1283 raeburn 7346: if ($res->answerable()) {
1.1282 raeburn 7347: $activeblock = 1;
7348: last;
7349: }
7350: }
7351: if ($activeblock) {
7352: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7353: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7354: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7355: }
7356: }
7357: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7358: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7359: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7360: }
1.1162 raeburn 7361: }
7362: }
7363: }
7364: }
7365: }
7366: }
7367: }
7368: }
7369: }
1.1282 raeburn 7370: return %blockers;
1.1162 raeburn 7371: }
7372:
1.1282 raeburn 7373: sub has_comm_blocking {
7374: my ($priv,$symb,$uri,$blocks) = @_;
7375: my @blockers;
7376: return unless ($env{'request.course.id'});
7377: return unless ($priv eq 'bre');
7378: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7379: return if ($env{'request.state'} eq 'construct');
7380: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7381: return unless (keys(%cachedblockers) > 0);
7382: my (%possibles,@symbs);
7383: if (!$symb) {
7384: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7385: }
1.1282 raeburn 7386: if ($symb) {
7387: @symbs = ($symb);
7388: } elsif (keys(%possibles)) {
7389: @symbs = keys(%possibles);
7390: }
7391: my $noblock;
7392: foreach my $symb (@symbs) {
7393: last if ($noblock);
7394: my ($map,$resid,$resurl)=&decode_symb($symb);
7395: foreach my $block (keys(%cachedblockers)) {
7396: if ($block =~ /^firstaccess____(.+)$/) {
7397: my $item = $1;
7398: if (($item eq $map) || ($item eq $symb)) {
7399: $noblock = 1;
7400: last;
7401: }
7402: }
7403: if (ref($cachedblockers{$block}) eq 'HASH') {
7404: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7405: if ($cachedblockers{$block}{'resources'}{$symb}) {
7406: unless (grep(/^\Q$block\E$/,@blockers)) {
7407: push(@blockers,$block);
7408: }
7409: }
7410: }
1.1162 raeburn 7411: }
1.1282 raeburn 7412: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7413: if ($cachedblockers{$block}{'maps'}{$map}) {
7414: unless (grep(/^\Q$block\E$/,@blockers)) {
7415: push(@blockers,$block);
7416: }
7417: }
1.1162 raeburn 7418: }
7419: }
7420: }
1.1282 raeburn 7421: return if ($noblock);
7422: return @blockers;
7423: }
1.1162 raeburn 7424: }
7425:
1.1282 raeburn 7426: # -------------------------------- Deversion and split uri into path an filename
7427:
1.1133 foxr 7428: #
1.1282 raeburn 7429: # Removes the version from a URI and
1.1133 foxr 7430: # splits it in to its filename and path to the filename.
7431: # Seems like File::Basename could have done this more clearly.
7432: # Parameters:
7433: # $uri - input URI
7434: # Returns:
7435: # Two element list consisting of
7436: # $pathname - the URI up to and excluding the trailing /
7437: # $filename - The part of the URI following the last /
7438: # NOTE:
7439: # Another realization of this is simply:
7440: # use File::Basename;
7441: # ...
7442: # $uri = shift;
7443: # $filename = basename($uri);
7444: # $path = dirname($uri);
7445: # return ($filename, $path);
7446: #
7447: # The implementation below is probably faster however.
7448: #
1.710 albertel 7449: sub split_uri_for_cond {
7450: my $uri=&deversion(&declutter(shift));
7451: my @uriparts=split(/\//,$uri);
7452: my $filename=pop(@uriparts);
7453: my $pathname=join('/',@uriparts);
7454: return ($pathname,$filename);
7455: }
1.232 www 7456: # --------------------------------------------------- Is a resource on the map?
7457:
7458: sub is_on_map {
1.710 albertel 7459: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7460: #Trying to find the conditional for the file
1.620 albertel 7461: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7462: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7463: if ($match) {
1.289 bowersj2 7464: return (1,$1);
7465: } else {
1.434 www 7466: return (0,0);
1.289 bowersj2 7467: }
1.12 www 7468: }
7469:
1.427 www 7470: # --------------------------------------------------------- Get symb from alias
7471:
7472: sub get_symb_from_alias {
7473: my $symb=shift;
7474: my ($map,$resid,$url)=&decode_symb($symb);
7475: # Already is a symb
7476: if ($url) { return $symb; }
7477: # Must be an alias
7478: my $aliassymb='';
7479: my %bighash;
1.620 albertel 7480: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7481: &GDBM_READER(),0640)) {
7482: my $rid=$bighash{'mapalias_'.$symb};
7483: if ($rid) {
7484: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7485: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7486: $resid,$bighash{'src_'.$rid});
1.427 www 7487: }
7488: untie %bighash;
7489: }
7490: return $aliassymb;
7491: }
7492:
1.12 www 7493: # ----------------------------------------------------------------- Define Role
7494:
7495: sub definerole {
7496: if (allowed('mcr','/')) {
7497: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7498: foreach my $role (split(':',$sysrole)) {
7499: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7500: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7501: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7502: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7503: return "refused:s:$crole&$cqual";
7504: }
7505: }
1.191 harris41 7506: }
1.800 albertel 7507: foreach my $role (split(':',$domrole)) {
7508: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7509: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7510: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7511: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7512: return "refused:d:$crole&$cqual";
7513: }
7514: }
1.191 harris41 7515: }
1.800 albertel 7516: foreach my $role (split(':',$courole)) {
7517: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7518: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7519: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7520: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7521: return "refused:c:$crole&$cqual";
7522: }
7523: }
1.191 harris41 7524: }
1.620 albertel 7525: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7526: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7527: "rolesdef_$rolename=".
7528: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7529: return reply($command,$env{'user.home'});
1.12 www 7530: } else {
7531: return 'refused';
7532: }
1.105 harris41 7533: }
7534:
7535: # ---------------- Make a metadata query against the network of library servers
7536:
7537: sub metadata_query {
1.1237 raeburn 7538: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7539: my %rhash;
1.845 albertel 7540: my %libserv = &all_library();
1.244 matthew 7541: my @server_list = (defined($server_array) ? @$server_array
7542: : keys(%libserv) );
7543: for my $server (@server_list) {
1.1237 raeburn 7544: my $domains = '';
7545: if (ref($domains_hash) eq 'HASH') {
7546: $domains = $domains_hash->{$server};
7547: }
1.118 harris41 7548: unless ($custom or $customshow) {
1.1237 raeburn 7549: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7550: $rhash{$server}=$reply;
7551: }
7552: else {
7553: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7554: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7555: $server);
7556: $rhash{$server}=$reply;
7557: }
1.112 harris41 7558: }
1.118 harris41 7559: return \%rhash;
1.240 www 7560: }
7561:
7562: # ----------------------------------------- Send log queries and wait for reply
7563:
7564: sub log_query {
7565: my ($uname,$udom,$query,%filters)=@_;
7566: my $uhome=&homeserver($uname,$udom);
7567: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7568: my $uhost=&hostname($uhome);
1.800 albertel 7569: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7570: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7571: $uhome);
1.479 albertel 7572: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7573: return get_query_reply($queryid);
7574: }
7575:
1.818 raeburn 7576: # -------------------------- Update MySQL table for portfolio file
7577:
7578: sub update_portfolio_table {
1.821 raeburn 7579: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7580: if ($group ne '') {
7581: $file_name =~s /^\Q$group\E//;
7582: }
1.818 raeburn 7583: my $homeserver = &homeserver($uname,$udom);
7584: my $queryid=
1.821 raeburn 7585: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7586: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7587: my $reply = &get_query_reply($queryid);
7588: return $reply;
7589: }
7590:
1.899 raeburn 7591: # -------------------------- Update MySQL allusers table
7592:
7593: sub update_allusers_table {
7594: my ($uname,$udom,$names) = @_;
7595: my $homeserver = &homeserver($uname,$udom);
7596: my $queryid=
7597: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7598: 'lastname='.&escape($names->{'lastname'}).'%%'.
7599: 'firstname='.&escape($names->{'firstname'}).'%%'.
7600: 'middlename='.&escape($names->{'middlename'}).'%%'.
7601: 'generation='.&escape($names->{'generation'}).'%%'.
7602: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7603: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7604: return;
1.899 raeburn 7605: }
7606:
1.508 raeburn 7607: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7608:
7609: sub fetch_enrollment_query {
1.511 raeburn 7610: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7611: my $homeserver;
1.547 raeburn 7612: my $maxtries = 1;
1.508 raeburn 7613: if ($context eq 'automated') {
7614: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7615: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7616: } else {
7617: $homeserver = &homeserver($cnum,$dom);
7618: }
1.838 albertel 7619: my $host=&hostname($homeserver);
1.506 raeburn 7620: my $cmd = '';
1.1000 raeburn 7621: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7622: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7623: }
7624: $cmd =~ s/%%$//;
7625: $cmd = &escape($cmd);
7626: my $query = 'fetchenrollment';
1.620 albertel 7627: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7628: unless ($queryid=~/^\Q$host\E\_/) {
7629: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7630: return 'error: '.$queryid;
7631: }
1.506 raeburn 7632: my $reply = &get_query_reply($queryid);
1.547 raeburn 7633: my $tries = 1;
7634: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7635: $reply = &get_query_reply($queryid);
7636: $tries ++;
7637: }
1.526 raeburn 7638: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7639: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7640: } else {
1.901 albertel 7641: my @responses = split(/:/,$reply);
1.515 raeburn 7642: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7643: foreach my $line (@responses) {
7644: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7645: $$replyref{$key} = $value;
7646: }
7647: } else {
1.1117 foxr 7648: my $pathname = LONCAPA::tempdir();
1.800 albertel 7649: foreach my $line (@responses) {
7650: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7651: $$replyref{$key} = $value;
7652: if ($value > 0) {
1.800 albertel 7653: foreach my $item (@{$$affiliatesref{$key}}) {
7654: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7655: my $destname = $pathname.'/'.$filename;
7656: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7657: if ($xml_classlist =~ /^error/) {
7658: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7659: } else {
1.506 raeburn 7660: if ( open(FILE,">$destname") ) {
7661: print FILE &unescape($xml_classlist);
7662: close(FILE);
1.526 raeburn 7663: } else {
7664: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7665: }
7666: }
7667: }
7668: }
7669: }
7670: }
7671: return 'ok';
7672: }
7673: return 'error';
7674: }
7675:
1.242 www 7676: sub get_query_reply {
7677: my $queryid=shift;
1.1117 foxr 7678: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7679: my $reply='';
7680: for (1..100) {
1.1289 ! damieng 7681: sleep(0.2);
1.240 www 7682: if (-e $replyfile.'.end') {
1.448 albertel 7683: if (open(my $fh,$replyfile)) {
1.904 albertel 7684: $reply = join('',<$fh>);
7685: close($fh);
1.240 www 7686: } else { return 'error: reply_file_error'; }
1.242 www 7687: return &unescape($reply);
7688: }
1.240 www 7689: }
1.242 www 7690: return 'timeout:'.$queryid;
1.240 www 7691: }
7692:
7693: sub courselog_query {
1.241 www 7694: #
7695: # possible filters:
7696: # url: url or symb
7697: # username
7698: # domain
7699: # action: view, submit, grade
7700: # start: timestamp
7701: # end: timestamp
7702: #
1.240 www 7703: my (%filters)=@_;
1.620 albertel 7704: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7705: if ($filters{'url'}) {
7706: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7707: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7708: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7709: }
1.620 albertel 7710: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7711: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7712: return &log_query($cname,$cdom,'courselog',%filters);
7713: }
7714:
7715: sub userlog_query {
1.858 raeburn 7716: #
7717: # possible filters:
7718: # action: log check role
7719: # start: timestamp
7720: # end: timestamp
7721: #
1.240 www 7722: my ($uname,$udom,%filters)=@_;
7723: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7724: }
7725:
1.506 raeburn 7726: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7727:
7728: sub auto_run {
1.508 raeburn 7729: my ($cnum,$cdom) = @_;
1.876 raeburn 7730: my $response = 0;
7731: my $settings;
7732: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7733: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7734: $settings = $domconfig{'autoenroll'};
7735: if ($settings->{'run'} eq '1') {
7736: $response = 1;
7737: }
7738: } else {
1.934 raeburn 7739: my $homeserver;
7740: if (&is_course($cdom,$cnum)) {
7741: $homeserver = &homeserver($cnum,$cdom);
7742: } else {
7743: $homeserver = &domain($cdom,'primary');
7744: }
7745: if ($homeserver ne 'no_host') {
7746: $response = &reply('autorun:'.$cdom,$homeserver);
7747: }
1.876 raeburn 7748: }
1.506 raeburn 7749: return $response;
7750: }
1.776 albertel 7751:
1.506 raeburn 7752: sub auto_get_sections {
1.508 raeburn 7753: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7754: my $homeserver;
7755: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7756: $homeserver = &homeserver($cnum,$cdom);
7757: }
7758: if (!defined($homeserver)) {
7759: if ($cdom =~ /^$match_domain$/) {
7760: $homeserver = &domain($cdom,'primary');
7761: }
7762: }
7763: my @secs;
7764: if (defined($homeserver)) {
7765: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7766: unless ($response eq 'refused') {
7767: @secs = split(/:/,$response);
7768: }
1.506 raeburn 7769: }
7770: return @secs;
7771: }
1.776 albertel 7772:
1.506 raeburn 7773: sub auto_new_course {
1.1099 raeburn 7774: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7775: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7776: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7777: return $response;
7778: }
1.776 albertel 7779:
1.506 raeburn 7780: sub auto_validate_courseID {
1.508 raeburn 7781: my ($cnum,$cdom,$inst_course_id) = @_;
7782: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7783: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7784: return $response;
7785: }
1.776 albertel 7786:
1.1007 raeburn 7787: sub auto_validate_instcode {
1.1020 raeburn 7788: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7789: my ($homeserver,$response);
7790: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7791: $homeserver = &homeserver($cnum,$cdom);
7792: }
7793: if (!defined($homeserver)) {
7794: if ($cdom =~ /^$match_domain$/) {
7795: $homeserver = &domain($cdom,'primary');
7796: }
7797: }
1.1065 raeburn 7798: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7799: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7800: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7801: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7802: }
7803:
1.506 raeburn 7804: sub auto_create_password {
1.873 raeburn 7805: my ($cnum,$cdom,$authparam,$udom) = @_;
7806: my ($homeserver,$response);
1.506 raeburn 7807: my $create_passwd = 0;
7808: my $authchk = '';
1.873 raeburn 7809: if ($udom =~ /^$match_domain$/) {
7810: $homeserver = &domain($udom,'primary');
7811: }
7812: if ($homeserver eq '') {
7813: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7814: $homeserver = &homeserver($cnum,$cdom);
7815: }
7816: }
7817: if ($homeserver eq '') {
7818: $authchk = 'nodomain';
1.506 raeburn 7819: } else {
1.873 raeburn 7820: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7821: if ($response eq 'refused') {
7822: $authchk = 'refused';
7823: } else {
1.901 albertel 7824: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7825: }
1.506 raeburn 7826: }
7827: return ($authparam,$create_passwd,$authchk);
7828: }
7829:
1.706 raeburn 7830: sub auto_photo_permission {
7831: my ($cnum,$cdom,$students) = @_;
7832: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7833: my ($outcome,$perm_reqd,$conditions) =
7834: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7835: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7836: return (undef,undef);
7837: }
1.706 raeburn 7838: return ($outcome,$perm_reqd,$conditions);
7839: }
7840:
7841: sub auto_checkphotos {
7842: my ($uname,$udom,$pid) = @_;
7843: my $homeserver = &homeserver($uname,$udom);
7844: my ($result,$resulttype);
7845: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7846: &escape($uname).':'.&escape($pid),
7847: $homeserver));
1.709 albertel 7848: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7849: return (undef,undef);
7850: }
1.706 raeburn 7851: if ($outcome) {
7852: ($result,$resulttype) = split(/:/,$outcome);
7853: }
7854: return ($result,$resulttype);
7855: }
7856:
7857: sub auto_photochoice {
7858: my ($cnum,$cdom) = @_;
7859: my $homeserver = &homeserver($cnum,$cdom);
7860: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7861: &escape($cdom),
7862: $homeserver)));
1.709 albertel 7863: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7864: return (undef,undef);
7865: }
1.706 raeburn 7866: return ($update,$comment);
7867: }
7868:
7869: sub auto_photoupdate {
7870: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7871: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7872: my $host=&hostname($homeserver);
1.706 raeburn 7873: my $cmd = '';
7874: my $maxtries = 1;
1.800 albertel 7875: foreach my $affiliate (keys(%{$affiliatesref})) {
7876: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7877: }
7878: $cmd =~ s/%%$//;
7879: $cmd = &escape($cmd);
7880: my $query = 'institutionalphotos';
7881: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7882: unless ($queryid=~/^\Q$host\E\_/) {
7883: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7884: return 'error: '.$queryid;
7885: }
7886: my $reply = &get_query_reply($queryid);
7887: my $tries = 1;
7888: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7889: $reply = &get_query_reply($queryid);
7890: $tries ++;
7891: }
7892: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7893: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7894: } else {
7895: my @responses = split(/:/,$reply);
7896: my $outcome = shift(@responses);
7897: foreach my $item (@responses) {
7898: my ($key,$value) = split(/=/,$item);
7899: $$photo{$key} = $value;
7900: }
7901: return $outcome;
7902: }
7903: return 'error';
7904: }
7905:
1.521 raeburn 7906: sub auto_instcode_format {
1.793 albertel 7907: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7908: $cat_order) = @_;
1.521 raeburn 7909: my $courses = '';
1.772 raeburn 7910: my @homeservers;
1.521 raeburn 7911: if ($caller eq 'global') {
1.841 albertel 7912: my %servers = &get_servers($codedom,'library');
7913: foreach my $tryserver (keys(%servers)) {
7914: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7915: push(@homeservers,$tryserver);
7916: }
1.584 raeburn 7917: }
1.1022 raeburn 7918: } elsif ($caller eq 'requests') {
7919: if ($codedom =~ /^$match_domain$/) {
7920: my $chome = &domain($codedom,'primary');
7921: unless ($chome eq 'no_host') {
7922: push(@homeservers,$chome);
7923: }
7924: }
1.521 raeburn 7925: } else {
1.772 raeburn 7926: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7927: }
1.793 albertel 7928: foreach my $code (keys(%{$instcodes})) {
7929: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7930: }
7931: chop($courses);
1.772 raeburn 7932: my $ok_response = 0;
7933: my $response;
7934: while (@homeservers > 0 && $ok_response == 0) {
7935: my $server = shift(@homeservers);
7936: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7937: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7938: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7939: split(/:/,$response);
1.772 raeburn 7940: %{$codes} = (%{$codes},&str2hash($codes_str));
7941: push(@{$codetitles},&str2array($codetitles_str));
7942: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7943: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7944: $ok_response = 1;
7945: }
7946: }
7947: if ($ok_response) {
1.521 raeburn 7948: return 'ok';
1.772 raeburn 7949: } else {
7950: return $response;
1.521 raeburn 7951: }
7952: }
7953:
1.792 raeburn 7954: sub auto_instcode_defaults {
7955: my ($domain,$returnhash,$code_order) = @_;
7956: my @homeservers;
1.841 albertel 7957:
7958: my %servers = &get_servers($domain,'library');
7959: foreach my $tryserver (keys(%servers)) {
7960: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7961: push(@homeservers,$tryserver);
7962: }
1.792 raeburn 7963: }
1.841 albertel 7964:
1.792 raeburn 7965: my $response;
1.841 albertel 7966: foreach my $server (@homeservers) {
1.792 raeburn 7967: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7968: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7969:
7970: foreach my $pair (split(/\&/,$response)) {
7971: my ($name,$value)=split(/\=/,$pair);
7972: if ($name eq 'code_order') {
7973: @{$code_order} = split(/\&/,&unescape($value));
7974: } else {
7975: $returnhash->{&unescape($name)}=&unescape($value);
7976: }
7977: }
7978: return 'ok';
1.792 raeburn 7979: }
1.841 albertel 7980:
7981: return $response;
1.1003 raeburn 7982: }
7983:
7984: sub auto_possible_instcodes {
1.1007 raeburn 7985: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7986: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7987: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7988: return;
7989: }
1.1003 raeburn 7990: my (@homeservers,$uhome);
7991: if (defined(&domain($domain,'primary'))) {
7992: $uhome=&domain($domain,'primary');
7993: push(@homeservers,&domain($domain,'primary'));
7994: } else {
7995: my %servers = &get_servers($domain,'library');
7996: foreach my $tryserver (keys(%servers)) {
7997: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7998: push(@homeservers,$tryserver);
7999: }
8000: }
8001: }
8002: my $response;
8003: foreach my $server (@homeservers) {
8004: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8005: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8006: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8007: split(':',$response);
8008: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8009: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8010: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8011: my ($name,$value)=split('=',$item);
8012: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8013: }
8014: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8015: my ($name,$value)=split('=',$item);
8016: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8017: }
8018: return 'ok';
8019: }
8020: return $response;
8021: }
1.792 raeburn 8022:
1.1010 raeburn 8023: sub auto_courserequest_checks {
8024: my ($dom) = @_;
1.1020 raeburn 8025: my ($homeserver,%validations);
8026: if ($dom =~ /^$match_domain$/) {
8027: $homeserver = &domain($dom,'primary');
8028: }
8029: unless ($homeserver eq 'no_host') {
8030: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8031: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8032: my @items = split(/&/,$response);
8033: foreach my $item (@items) {
8034: my ($key,$value) = split('=',$item);
8035: $validations{&unescape($key)} = &thaw_unescape($value);
8036: }
8037: }
8038: }
1.1010 raeburn 8039: return %validations;
8040: }
8041:
1.1020 raeburn 8042: sub auto_courserequest_validation {
1.1255 raeburn 8043: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8044: my ($homeserver,$response);
8045: if ($dom =~ /^$match_domain$/) {
8046: $homeserver = &domain($dom,'primary');
8047: }
1.1255 raeburn 8048: unless ($homeserver eq 'no_host') {
8049: my $customdata;
8050: if (ref($custominfo) eq 'HASH') {
8051: $customdata = &freeze_escape($custominfo);
8052: }
1.1020 raeburn 8053: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8054: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8055: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8056: $customdata,$homeserver));
1.1020 raeburn 8057: }
8058: return $response;
8059: }
8060:
1.777 albertel 8061: sub auto_validate_class_sec {
1.918 raeburn 8062: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8063: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8064: my $ownerlist;
8065: if (ref($owners) eq 'ARRAY') {
8066: $ownerlist = join(',',@{$owners});
8067: } else {
8068: $ownerlist = $owners;
8069: }
1.773 raeburn 8070: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8071: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8072: return $response;
8073: }
8074:
1.1248 raeburn 8075: sub auto_crsreq_update {
8076: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8077: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8078: my ($homeserver,%crsreqresponse);
8079: if ($cdom =~ /^$match_domain$/) {
8080: $homeserver = &domain($cdom,'primary');
8081: }
8082: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8083: my $info;
8084: if (ref($inbound) eq 'HASH') {
8085: $info = &freeze_escape($inbound);
8086: }
8087: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8088: ':'.&escape($action).':'.&escape($ownername).':'.
8089: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8090: &escape($title).':'.&escape($code).':'.
8091: &escape($accessstart).':'.&escape($accessend).':'.$info,
8092: $homeserver);
1.1248 raeburn 8093: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8094: my @items = split(/&/,$response);
8095: foreach my $item (@items) {
8096: my ($key,$value) = split('=',$item);
8097: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8098: }
8099: }
8100: }
8101: return \%crsreqresponse;
8102: }
8103:
1.1287 raeburn 8104: sub check_instcode_cloning {
8105: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8106: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8107: return;
8108: }
8109: my $canclone;
8110: if (@{$code_order} > 0) {
8111: my $instcoderegexp ='^';
8112: my @clonecodes = split(/\&/,$cloner);
8113: foreach my $item (@{$code_order}) {
8114: if (grep(/^\Q$item\E=/,@clonecodes)) {
8115: foreach my $pair (@clonecodes) {
8116: my ($key,$val) = split(/\=/,$pair,2);
8117: $val = &unescape($val);
8118: if ($key eq $item) {
8119: $instcoderegexp .= '('.$val.')';
8120: last;
8121: }
8122: }
8123: } else {
8124: $instcoderegexp .= $codedefaults->{$item};
8125: }
8126: }
8127: $instcoderegexp .= '$';
8128: my (@from,@to);
8129: eval {
8130: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8131: (@to) = ($clonetocode =~ /$instcoderegexp/);
8132: };
8133: if ((@from > 0) && (@to > 0)) {
8134: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8135: if (!@diffs) {
8136: $canclone = 1;
8137: }
8138: }
8139: }
8140: return $canclone;
8141: }
8142:
8143: sub default_instcode_cloning {
8144: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8145: my (%codedefaults,@code_order,$canclone);
8146: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8147: %codedefaults = %{$codedefaultsref};
8148: @code_order = @{$codeorderref};
8149: } elsif ($clonedom) {
8150: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8151: }
8152: if (($domdefclone) && (@code_order)) {
8153: my @clonecodes = split(/\+/,$domdefclone);
8154: my $instcoderegexp ='^';
8155: foreach my $item (@code_order) {
8156: if (grep(/^\Q$item\E$/,@clonecodes)) {
8157: $instcoderegexp .= '('.$codedefaults{$item}.')';
8158: } else {
8159: $instcoderegexp .= $codedefaults{$item};
8160: }
8161: }
8162: $instcoderegexp .= '$';
8163: my (@from,@to);
8164: eval {
8165: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8166: (@to) = ($clonetocode =~ /$instcoderegexp/);
8167: };
8168: if ((@from > 0) && (@to > 0)) {
8169: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8170: if (!@diffs) {
8171: $canclone = 1;
8172: }
8173: }
8174: }
8175: return $canclone;
8176: }
8177:
1.679 raeburn 8178: # ------------------------------------------------------- Course Group routines
8179:
8180: sub get_coursegroups {
1.809 raeburn 8181: my ($cdom,$cnum,$group,$namespace) = @_;
8182: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8183: }
8184:
1.679 raeburn 8185: sub modify_coursegroup {
8186: my ($cdom,$cnum,$groupsettings) = @_;
8187: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8188: }
8189:
1.809 raeburn 8190: sub toggle_coursegroup_status {
8191: my ($cdom,$cnum,$group,$action) = @_;
8192: my ($from_namespace,$to_namespace);
8193: if ($action eq 'delete') {
8194: $from_namespace = 'coursegroups';
8195: $to_namespace = 'deleted_groups';
8196: } else {
8197: $from_namespace = 'deleted_groups';
8198: $to_namespace = 'coursegroups';
8199: }
8200: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8201: if (my $tmp = &error(%curr_group)) {
8202: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8203: return ('read error',$tmp);
8204: } else {
8205: my %savedsettings = %curr_group;
1.809 raeburn 8206: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8207: my $deloutcome;
8208: if ($result eq 'ok') {
1.809 raeburn 8209: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8210: } else {
8211: return ('write error',$result);
8212: }
8213: if ($deloutcome eq 'ok') {
8214: return 'ok';
8215: } else {
8216: return ('delete error',$deloutcome);
8217: }
8218: }
8219: }
8220:
1.679 raeburn 8221: sub modify_group_roles {
1.957 raeburn 8222: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8223: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8224: my $role = 'gr/'.&escape($userprivs);
8225: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8226: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8227: if ($result eq 'ok') {
8228: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8229: }
1.679 raeburn 8230: return $result;
8231: }
8232:
8233: sub modify_coursegroup_membership {
8234: my ($cdom,$cnum,$membership) = @_;
8235: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8236: return $result;
8237: }
8238:
1.682 raeburn 8239: sub get_active_groups {
8240: my ($udom,$uname,$cdom,$cnum) = @_;
8241: my $now = time;
8242: my %groups = ();
8243: foreach my $key (keys(%env)) {
1.811 albertel 8244: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8245: my ($start,$end) = split(/\./,$env{$key});
8246: if (($end!=0) && ($end<$now)) { next; }
8247: if (($start!=0) && ($start>$now)) { next; }
8248: if ($1 eq $cdom && $2 eq $cnum) {
8249: $groups{$3} = $env{$key} ;
8250: }
8251: }
8252: }
8253: return %groups;
8254: }
8255:
1.683 raeburn 8256: sub get_group_membership {
8257: my ($cdom,$cnum,$group) = @_;
8258: return(&dump('groupmembership',$cdom,$cnum,$group));
8259: }
8260:
8261: sub get_users_groups {
8262: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8263: my @usersgroups;
1.683 raeburn 8264: my $cachetime=1800;
8265:
8266: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8267: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8268: if (defined($cached)) {
1.734 albertel 8269: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8270: } else {
8271: $grouplist = '';
1.816 raeburn 8272: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8273: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8274: my $access_end = $env{'course.'.$courseid.
8275: '.default_enrollment_end_date'};
8276: my $now = time;
8277: foreach my $key (keys(%roleshash)) {
8278: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8279: my $group = $1;
8280: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8281: my $start = $2;
8282: my $end = $1;
8283: if ($start == -1) { next; } # deleted from group
8284: if (($start!=0) && ($start>$now)) { next; }
8285: if (($end!=0) && ($end<$now)) {
8286: if ($access_end && $access_end < $now) {
8287: if ($access_end - $end < 86400) {
8288: push(@usersgroups,$group);
1.733 raeburn 8289: }
8290: }
1.817 raeburn 8291: next;
1.733 raeburn 8292: }
1.817 raeburn 8293: push(@usersgroups,$group);
1.683 raeburn 8294: }
8295: }
8296: }
1.817 raeburn 8297: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8298: $grouplist = join(':',@usersgroups);
8299: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8300: }
1.733 raeburn 8301: return @usersgroups;
1.683 raeburn 8302: }
8303:
8304: sub devalidate_getgroups_cache {
8305: my ($udom,$uname,$cdom,$cnum)=@_;
8306: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8307:
1.683 raeburn 8308: my $hashid="$udom:$uname:$courseid";
8309: &devalidate_cache_new('getgroups',$hashid);
8310: }
8311:
1.12 www 8312: # ------------------------------------------------------------------ Plain Text
8313:
8314: sub plaintext {
1.988 raeburn 8315: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8316: if ($short =~ m{^cr/}) {
1.758 albertel 8317: return (split('/',$short))[-1];
8318: }
1.742 raeburn 8319: if (!defined($cid)) {
8320: $cid = $env{'request.course.id'};
8321: }
8322: my %rolenames = (
1.1008 raeburn 8323: Course => 'std',
8324: Community => 'alt1',
1.742 raeburn 8325: );
1.1037 raeburn 8326: if ($cid ne '') {
8327: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8328: unless ($forcedefault) {
8329: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8330: &Apache::lonlocal::mt_escape(\$roletext);
8331: return &Apache::lonlocal::mt($roletext);
8332: }
8333: }
8334: }
8335: if ((defined($type)) && (defined($rolenames{$type})) &&
8336: (defined($rolenames{$type})) &&
8337: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8338: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8339: } elsif ($cid ne '') {
8340: my $crstype = $env{'course.'.$cid.'.type'};
8341: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8342: (defined($prp{$short}{$rolenames{$crstype}}))) {
8343: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8344: }
1.742 raeburn 8345: }
1.1037 raeburn 8346: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8347: }
8348:
8349: # ----------------------------------------------------------------- Assign Role
8350:
8351: sub assignrole {
1.957 raeburn 8352: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8353: $context)=@_;
1.21 www 8354: my $mrole;
8355: if ($role =~ /^cr\//) {
1.393 www 8356: my $cwosec=$url;
1.811 albertel 8357: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8358: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8359: my $refused = 1;
8360: if ($context eq 'requestcourses') {
8361: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8362: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8363: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8364: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8365: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8366: if ($crsenv{'internal.courseowner'} eq
8367: $env{'user.name'}.':'.$env{'user.domain'}) {
8368: $refused = '';
8369: }
8370: }
8371: }
8372: }
8373: }
8374: if ($refused) {
8375: &logthis('Refused custom assignrole: '.
8376: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8377: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8378: return 'refused';
8379: }
1.104 www 8380: }
1.21 www 8381: $mrole='cr';
1.678 raeburn 8382: } elsif ($role =~ /^gr\//) {
8383: my $cwogrp=$url;
1.811 albertel 8384: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8385: unless (&allowed('mdg',$cwogrp)) {
8386: &logthis('Refused group assignrole: '.
8387: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8388: $env{'user.name'}.' at '.$env{'user.domain'});
8389: return 'refused';
8390: }
8391: $mrole='gr';
1.21 www 8392: } else {
1.82 www 8393: my $cwosec=$url;
1.811 albertel 8394: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8395: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8396: my $refused;
8397: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8398: if (!(&allowed('c'.$role,$url))) {
8399: $refused = 1;
8400: }
8401: } else {
8402: $refused = 1;
8403: }
1.947 raeburn 8404: if ($refused) {
1.1045 raeburn 8405: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8406: if (!$selfenroll && $context eq 'course') {
8407: my %crsenv;
8408: if ($role eq 'cc' || $role eq 'co') {
8409: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8410: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8411: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8412: if ($crsenv{'internal.courseowner'} eq
8413: $env{'user.name'}.':'.$env{'user.domain'}) {
8414: $refused = '';
8415: }
8416: }
8417: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8418: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8419: if ($crsenv{'internal.courseowner'} eq
8420: $env{'user.name'}.':'.$env{'user.domain'}) {
8421: $refused = '';
8422: }
8423: }
8424: }
8425: }
8426: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8427: $refused = '';
1.1017 raeburn 8428: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8429: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8430: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8431: my $wrongcc;
8432: if ($cnum =~ /^$match_community$/) {
8433: $wrongcc = 1 if ($role eq 'cc');
8434: } else {
8435: $wrongcc = 1 if ($role eq 'co');
8436: }
8437: unless ($wrongcc) {
8438: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8439: if ($crsenv{'internal.courseowner'} eq
8440: $env{'user.name'}.':'.$env{'user.domain'}) {
8441: $refused = '';
8442: }
1.1017 raeburn 8443: }
8444: }
1.1183 raeburn 8445: } elsif ($context eq 'requestauthor') {
8446: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8447: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8448: if ($env{'environment.requestauthor'} eq 'automatic') {
8449: $refused = '';
8450: } else {
8451: my %domdefaults = &get_domain_defaults($udom);
8452: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8453: my $checkbystatus;
8454: if ($env{'user.adv'}) {
8455: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8456: if ($disposition eq 'automatic') {
8457: $refused = '';
8458: } elsif ($disposition eq '') {
8459: $checkbystatus = 1;
8460: }
8461: } else {
8462: $checkbystatus = 1;
8463: }
8464: if ($checkbystatus) {
8465: if ($env{'environment.inststatus'}) {
8466: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8467: foreach my $type (@inststatuses) {
8468: if (($type ne '') &&
8469: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8470: $refused = '';
8471: }
8472: }
8473: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8474: $refused = '';
8475: }
8476: }
8477: }
8478: }
8479: }
1.1017 raeburn 8480: }
8481: if ($refused) {
1.947 raeburn 8482: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8483: ' '.$role.' '.$end.' '.$start.' by '.
8484: $env{'user.name'}.' at '.$env{'user.domain'});
8485: return 'refused';
8486: }
1.932 raeburn 8487: }
1.1131 raeburn 8488: } elsif ($role eq 'au') {
8489: if ($url ne '/'.$udom.'/') {
8490: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8491: ' to assign author role for '.$uname.':'.$udom.
8492: ' in domain: '.$url.' refused (wrong domain).');
8493: return 'refused';
8494: }
1.104 www 8495: }
1.21 www 8496: $mrole=$role;
8497: }
1.620 albertel 8498: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8499: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8500: if ($end) { $command.='_'.$end; }
1.21 www 8501: if ($start) {
8502: if ($end) {
1.81 www 8503: $command.='_'.$start;
1.21 www 8504: } else {
1.81 www 8505: $command.='_0_'.$start;
1.21 www 8506: }
8507: }
1.739 raeburn 8508: my $origstart = $start;
8509: my $origend = $end;
1.957 raeburn 8510: my $delflag;
1.357 www 8511: # actually delete
8512: if ($deleteflag) {
1.373 www 8513: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8514: # modify command to delete the role
1.620 albertel 8515: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8516: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8517: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8518: # set start and finish to negative values for userrolelog
8519: $start=-1;
8520: $end=-1;
1.957 raeburn 8521: $delflag = 1;
1.357 www 8522: }
8523: }
8524: # send command
1.349 www 8525: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8526: # log new user role if status is ok
1.349 www 8527: if ($answer eq 'ok') {
1.663 raeburn 8528: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8529: if (($role eq 'cc') || ($role eq 'in') ||
8530: ($role eq 'ep') || ($role eq 'ad') ||
8531: ($role eq 'ta') || ($role eq 'st') ||
8532: ($role=~/^cr/) || ($role eq 'gr') ||
8533: ($role eq 'co')) {
1.1200 raeburn 8534: # for course roles, perform group memberships changes triggered by role change.
8535: unless ($role =~ /^gr/) {
8536: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8537: $origstart,$selfenroll,$context);
8538: }
1.1184 raeburn 8539: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8540: $selfenroll,$context);
8541: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8542: ($role eq 'au') || ($role eq 'dc')) {
8543: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8544: $context);
8545: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8546: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8547: $context);
8548: }
1.1053 raeburn 8549: if ($role eq 'cc') {
8550: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8551: }
1.349 www 8552: }
8553: return $answer;
1.169 harris41 8554: }
8555:
1.1053 raeburn 8556: sub autoupdate_coowners {
8557: my ($url,$end,$start,$uname,$udom) = @_;
8558: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8559: if (($cdom ne '') && ($cnum ne '')) {
8560: my $now = time;
8561: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8562: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8563: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8564: my $instcode = $coursehash{'internal.coursecode'};
8565: if ($instcode ne '') {
1.1056 raeburn 8566: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8567: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8568: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8569: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8570: if ($result eq 'valid') {
8571: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8572: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8573: push(@newcoowners,$coowner);
8574: }
8575: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8576: push(@newcoowners,$uname.':'.$udom);
8577: }
8578: @newcoowners = sort(@newcoowners);
8579: } else {
8580: push(@newcoowners,$uname.':'.$udom);
8581: }
8582: } else {
8583: if ($coursehash{'internal.co-owners'}) {
8584: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8585: unless ($coowner eq $uname.':'.$udom) {
8586: push(@newcoowners,$coowner);
8587: }
8588: }
8589: unless (@newcoowners > 0) {
8590: $delcoowners = 1;
8591: $coowners = '';
8592: }
8593: }
8594: }
8595: if (@newcoowners || $delcoowners) {
8596: &store_coowners($cdom,$cnum,$coursehash{'home'},
8597: $delcoowners,@newcoowners);
8598: }
8599: }
8600: }
8601: }
8602: }
8603: }
8604: }
8605:
8606: sub store_coowners {
8607: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8608: my $cid = $cdom.'_'.$cnum;
8609: my ($coowners,$delresult,$putresult);
8610: if (@newcoowners) {
8611: $coowners = join(',',@newcoowners);
8612: my %coownershash = (
8613: 'internal.co-owners' => $coowners,
8614: );
8615: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8616: if ($putresult eq 'ok') {
8617: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8618: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8619: }
8620: }
8621: }
8622: if ($delcoowners) {
8623: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8624: if ($delresult eq 'ok') {
8625: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8626: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8627: }
8628: }
8629: }
8630: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8631: my %crsinfo =
8632: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8633: if (ref($crsinfo{$cid}) eq 'HASH') {
8634: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8635: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8636: }
8637: }
8638: }
8639:
1.169 harris41 8640: # -------------------------------------------------- Modify user authentication
1.197 www 8641: # Overrides without validation
8642:
1.169 harris41 8643: sub modifyuserauth {
8644: my ($udom,$uname,$umode,$upass)=@_;
8645: my $uhome=&homeserver($uname,$udom);
1.197 www 8646: unless (&allowed('mau',$udom)) { return 'refused'; }
8647: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8648: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8649: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8650: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8651: &escape($upass),$uhome);
1.620 albertel 8652: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8653: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8654: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8655: &log($udom,,$uname,$uhome,
1.620 albertel 8656: 'Authentication changed by '.$env{'user.domain'}.', '.
8657: $env{'user.name'}.', '.$umode.
1.197 www 8658: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8659: unless ($reply eq 'ok') {
1.197 www 8660: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8661: return 'error: '.$reply;
8662: }
1.170 harris41 8663: return 'ok';
1.80 www 8664: }
8665:
1.81 www 8666: # --------------------------------------------------------------- Modify a user
1.80 www 8667:
1.81 www 8668: sub modifyuser {
1.206 matthew 8669: my ($udom, $uname, $uid,
8670: $umode, $upass, $first,
8671: $middle, $last, $gene,
1.1058 raeburn 8672: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8673: $udom= &LONCAPA::clean_domain($udom);
8674: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8675: my $showcandelete = 'none';
8676: if (ref($candelete) eq 'ARRAY') {
8677: if (@{$candelete} > 0) {
8678: $showcandelete = join(', ',@{$candelete});
8679: }
8680: }
1.81 www 8681: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8682: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8683: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8684: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8685: ' desiredhome not specified').
1.620 albertel 8686: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8687: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8688: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8689: my $newuser;
8690: if ($uhome eq 'no_host') {
8691: $newuser = 1;
8692: }
1.80 www 8693: # ----------------------------------------------------------------- Create User
1.406 albertel 8694: if (($uhome eq 'no_host') &&
8695: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8696: my $unhome='';
1.844 albertel 8697: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8698: $unhome = $desiredhome;
1.620 albertel 8699: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8700: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8701: } else { # load balancing routine for determining $unhome
1.81 www 8702: my $loadm=10000000;
1.841 albertel 8703: my %servers = &get_servers($udom,'library');
8704: foreach my $tryserver (keys(%servers)) {
8705: my $answer=reply('load',$tryserver);
8706: if (($answer=~/\d+/) && ($answer<$loadm)) {
8707: $loadm=$answer;
8708: $unhome=$tryserver;
8709: }
1.80 www 8710: }
8711: }
8712: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8713: return 'error: unable to find a home server for '.$uname.
8714: ' in domain '.$udom;
1.80 www 8715: }
8716: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8717: &escape($upass),$unhome);
8718: unless ($reply eq 'ok') {
8719: return 'error: '.$reply;
8720: }
1.230 stredwic 8721: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8722: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8723: return 'error: unable verify users home machine.';
1.80 www 8724: }
1.209 matthew 8725: } # End of creation of new user
1.80 www 8726: # ---------------------------------------------------------------------- Add ID
8727: if ($uid) {
8728: $uid=~tr/A-Z/a-z/;
8729: my %uidhash=&idrget($udom,$uname);
1.196 www 8730: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8731: && (!$forceid)) {
1.80 www 8732: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8733: return 'error: user id "'.$uid.'" does not match '.
8734: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8735: }
8736: } else {
8737: &idput($udom,($uname => $uid));
8738: }
8739: }
8740: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8741: my @tmp=&get('environment',
1.899 raeburn 8742: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8743: 'permanentemail','inststatus'],
1.134 albertel 8744: $udom,$uname);
1.1075 raeburn 8745: my (%names,%oldnames);
1.313 matthew 8746: if ($tmp[0] =~ m/^error:.*/) {
8747: %names=();
8748: } else {
8749: %names = @tmp;
1.1075 raeburn 8750: %oldnames = %names;
1.313 matthew 8751: }
1.388 www 8752: #
1.1058 raeburn 8753: # If name, email and/or uid are blank (e.g., because an uploaded file
8754: # of users did not contain them), do not overwrite existing values
8755: # unless field is in $candelete array ref.
8756: #
8757:
8758: my @fields = ('firstname','middlename','lastname','generation',
8759: 'permanentemail','id');
8760: my %newvalues;
8761: if (ref($candelete) eq 'ARRAY') {
8762: foreach my $field (@fields) {
8763: if (grep(/^\Q$field\E$/,@{$candelete})) {
8764: if ($field eq 'firstname') {
8765: $names{$field} = $first;
8766: } elsif ($field eq 'middlename') {
8767: $names{$field} = $middle;
8768: } elsif ($field eq 'lastname') {
8769: $names{$field} = $last;
8770: } elsif ($field eq 'generation') {
8771: $names{$field} = $gene;
8772: } elsif ($field eq 'permanentemail') {
8773: $names{$field} = $email;
8774: } elsif ($field eq 'id') {
8775: $names{$field} = $uid;
8776: }
8777: }
8778: }
8779: }
1.388 www 8780: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8781: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8782: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8783: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8784: if ($email) {
8785: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8786: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8787: }
1.899 raeburn 8788: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8789: if (defined($inststatus)) {
8790: $names{'inststatus'} = '';
8791: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8792: if (ref($usertypes) eq 'HASH') {
8793: my @okstatuses;
8794: foreach my $item (split(/:/,$inststatus)) {
8795: if (defined($usertypes->{$item})) {
8796: push(@okstatuses,$item);
8797: }
8798: }
8799: if (@okstatuses) {
8800: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8801: }
8802: }
8803: }
1.1075 raeburn 8804: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8805: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8806: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8807: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8808: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8809: } else {
8810: $logmsg .= ' during self creation';
8811: }
1.1075 raeburn 8812: my $changed;
8813: if ($newuser) {
8814: $changed = 1;
8815: } else {
8816: foreach my $field (@fields) {
8817: if ($names{$field} ne $oldnames{$field}) {
8818: $changed = 1;
8819: last;
8820: }
8821: }
8822: }
8823: unless ($changed) {
8824: $logmsg = 'No changes in user information needed for: '.$logmsg;
8825: &logthis($logmsg);
8826: return 'ok';
8827: }
8828: my $reply = &put('environment', \%names, $udom,$uname);
8829: if ($reply ne 'ok') {
8830: return 'error: '.$reply;
8831: }
1.1087 raeburn 8832: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8833: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8834: }
1.1075 raeburn 8835: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8836: &devalidate_cache_new('namescache',$uname.':'.$udom);
8837: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8838: &logthis($logmsg);
1.134 albertel 8839: return 'ok';
1.80 www 8840: }
8841:
1.81 www 8842: # -------------------------------------------------------------- Modify student
1.80 www 8843:
1.81 www 8844: sub modifystudent {
8845: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8846: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8847: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8848: if (!$cid) {
1.620 albertel 8849: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8850: return 'not_in_class';
8851: }
1.80 www 8852: }
8853: # --------------------------------------------------------------- Make the user
1.81 www 8854: my $reply=&modifyuser
1.209 matthew 8855: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8856: $desiredhome,$email,$inststatus);
1.80 www 8857: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8858: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8859: # student's environment
1.297 matthew 8860: $uid = undef if (!$forceid);
1.455 albertel 8861: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8862: $gene,$usec,$end,$start,$type,$locktype,
8863: $cid,$selfenroll,$context,$credits);
1.297 matthew 8864: return $reply;
8865: }
8866:
8867: sub modify_student_enrollment {
1.1216 raeburn 8868: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8869: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8870: my ($cdom,$cnum,$chome);
8871: if (!$cid) {
1.620 albertel 8872: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8873: return 'not_in_class';
8874: }
1.620 albertel 8875: $cdom=$env{'course.'.$cid.'.domain'};
8876: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8877: } else {
8878: ($cdom,$cnum)=split(/_/,$cid);
8879: }
1.620 albertel 8880: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8881: if (!$chome) {
1.457 raeburn 8882: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8883: }
1.455 albertel 8884: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8885: # Make sure the user exists
1.81 www 8886: my $uhome=&homeserver($uname,$udom);
8887: if (($uhome eq '') || ($uhome eq 'no_host')) {
8888: return 'error: no such user';
8889: }
1.297 matthew 8890: # Get student data if we were not given enough information
8891: if (!defined($first) || $first eq '' ||
8892: !defined($last) || $last eq '' ||
8893: !defined($uid) || $uid eq '' ||
8894: !defined($middle) || $middle eq '' ||
8895: !defined($gene) || $gene eq '') {
1.294 matthew 8896: # They did not supply us with enough data to enroll the student, so
8897: # we need to pick up more information.
1.297 matthew 8898: my %tmp = &get('environment',
1.294 matthew 8899: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8900: ,$udom,$uname);
8901:
1.800 albertel 8902: #foreach my $key (keys(%tmp)) {
8903: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8904: #}
1.294 matthew 8905: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8906: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8907: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8908: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8909: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8910: }
1.556 albertel 8911: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8912: my $user = "$uname:$udom";
8913: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8914: my $reply=cput('classlist',
1.1148 raeburn 8915: {$user =>
1.1216 raeburn 8916: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8917: $cdom,$cnum);
1.1148 raeburn 8918: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8919: &devalidate_getsection_cache($udom,$uname,$cid);
8920: } else {
1.81 www 8921: return 'error: '.$reply;
8922: }
1.297 matthew 8923: # Add student role to user
1.83 www 8924: my $uurl='/'.$cid;
1.81 www 8925: $uurl=~s/\_/\//g;
8926: if ($usec) {
8927: $uurl.='/'.$usec;
8928: }
1.1148 raeburn 8929: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8930: $selfenroll,$context);
8931: if ($result ne 'ok') {
8932: if ($old_entry{$user} ne '') {
8933: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8934: } else {
8935: $reply = &del('classlist',[$user],$cdom,$cnum);
8936: }
8937: }
8938: return $result;
1.21 www 8939: }
8940:
1.556 albertel 8941: sub format_name {
8942: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8943: my $name;
8944: if ($first ne 'lastname') {
8945: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8946: } else {
8947: if ($lastname=~/\S/) {
8948: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8949: $name=~s/\s+,/,/;
8950: } else {
8951: $name.= $firstname.' '.$middlename.' '.$generation;
8952: }
8953: }
8954: $name=~s/^\s+//;
8955: $name=~s/\s+$//;
8956: $name=~s/\s+/ /g;
8957: return $name;
8958: }
8959:
1.84 www 8960: # ------------------------------------------------- Write to course preferences
8961:
8962: sub writecoursepref {
8963: my ($courseid,%prefs)=@_;
8964: $courseid=~s/^\///;
8965: $courseid=~s/\_/\//g;
8966: my ($cdomain,$cnum)=split(/\//,$courseid);
8967: my $chome=homeserver($cnum,$cdomain);
8968: if (($chome eq '') || ($chome eq 'no_host')) {
8969: return 'error: no such course';
8970: }
8971: my $cstring='';
1.800 albertel 8972: foreach my $pref (keys(%prefs)) {
8973: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8974: }
1.84 www 8975: $cstring=~s/\&$//;
8976: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8977: }
8978:
8979: # ---------------------------------------------------------- Make/modify course
8980:
8981: sub createcourse {
1.741 raeburn 8982: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8983: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8984: $url=&declutter($url);
8985: my $cid='';
1.1028 raeburn 8986: if ($context eq 'requestcourses') {
8987: my $can_create = 0;
8988: my ($ownername,$ownerdom) = split(':',$course_owner);
8989: if ($udom eq $ownerdom) {
8990: if (&usertools_access($ownername,$ownerdom,$category,undef,
8991: $context)) {
8992: $can_create = 1;
8993: }
8994: } else {
8995: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8996: $category);
8997: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8998: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8999: if (@curr > 0) {
9000: my @options = qw(approval validate autolimit);
9001: my $optregex = join('|',@options);
9002: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9003: $can_create = 1;
9004: }
9005: }
9006: }
9007: }
9008: if ($can_create) {
9009: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9010: unless (&allowed('ccc',$udom)) {
9011: return 'refused';
9012: }
1.1017 raeburn 9013: }
9014: } else {
9015: return 'refused';
9016: }
1.1028 raeburn 9017: } elsif (!&allowed('ccc',$udom)) {
9018: return 'refused';
1.84 www 9019: }
1.1011 raeburn 9020: # --------------------------------------------------------------- Get Unique ID
9021: my $uname;
9022: if ($cnum =~ /^$match_courseid$/) {
9023: my $chome=&homeserver($cnum,$udom,'true');
9024: if (($chome eq '') || ($chome eq 'no_host')) {
9025: $uname = $cnum;
9026: } else {
1.1038 raeburn 9027: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9028: }
9029: } else {
1.1038 raeburn 9030: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9031: }
9032: return $uname if ($uname =~ /^error/);
9033: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9034: if (!defined($course_server)) {
9035: if (defined(&domain($udom,'primary'))) {
9036: $course_server = &domain($udom,'primary');
9037: } else {
9038: $course_server = $env{'user.home'};
9039: }
9040: }
9041: my %host_servers =
9042: &Apache::lonnet::get_servers($udom,'library');
9043: unless ($host_servers{$course_server}) {
9044: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9045: }
1.84 www 9046: # ------------------------------------------------------------- Make the course
9047: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9048: $course_server);
1.84 www 9049: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9050: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9051: if (($uhome eq '') || ($uhome eq 'no_host')) {
9052: return 'error: no such course';
9053: }
1.271 www 9054: # ----------------------------------------------------------------- Course made
1.516 raeburn 9055: # log existence
1.1029 raeburn 9056: my $now = time;
1.918 raeburn 9057: my $newcourse = {
9058: $udom.'_'.$uname => {
1.921 raeburn 9059: description => $description,
9060: inst_code => $inst_code,
9061: owner => $course_owner,
9062: type => $crstype,
1.1029 raeburn 9063: creator => $env{'user.name'}.':'.
9064: $env{'user.domain'},
9065: created => $now,
9066: context => $context,
1.918 raeburn 9067: },
9068: };
1.921 raeburn 9069: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9070: # set toplevel url
1.271 www 9071: my $topurl=$url;
9072: unless ($nonstandard) {
9073: # ------------------------------------------ For standard courses, make top url
9074: my $mapurl=&clutter($url);
1.278 www 9075: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9076: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9077: <map>
9078: <resource id="1" type="start"></resource>
9079: <resource id="2" src="$mapurl"></resource>
9080: <resource id="3" type="finish"></resource>
9081: <link index="1" from="1" to="2"></link>
9082: <link index="2" from="2" to="3"></link>
9083: </map>
9084: ENDINITMAP
9085: $topurl=&declutter(
1.638 albertel 9086: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9087: );
9088: }
9089: # ----------------------------------------------------------- Write preferences
1.84 www 9090: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9091: ('description' => $description,
9092: 'url' => $topurl,
9093: 'internal.creator' => $env{'user.name'}.':'.
9094: $env{'user.domain'},
9095: 'internal.created' => $now,
9096: 'internal.creationcontext' => $context)
9097: );
1.84 www 9098: return '/'.$udom.'/'.$uname;
9099: }
9100:
1.1011 raeburn 9101: # ------------------------------------------------------------------- Create ID
9102: sub generate_coursenum {
1.1038 raeburn 9103: my ($udom,$crstype) = @_;
1.1011 raeburn 9104: my $domdesc = &domain($udom);
9105: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9106: my $first;
9107: if ($crstype eq 'Community') {
9108: $first = '0';
9109: } else {
9110: $first = int(1+rand(9));
9111: }
9112: my $uname=$first.
1.1011 raeburn 9113: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9114: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9115: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9116: # ----------------------------------------------- Make sure that does not exist
9117: my $uhome=&homeserver($uname,$udom,'true');
9118: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9119: if ($crstype eq 'Community') {
9120: $first = '0';
9121: } else {
9122: $first = int(1+rand(9));
9123: }
9124: $uname=$first.
1.1011 raeburn 9125: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9126: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9127: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9128: $uhome=&homeserver($uname,$udom,'true');
9129: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9130: return 'error: unable to generate unique course-ID';
9131: }
9132: }
9133: return $uname;
9134: }
9135:
1.813 albertel 9136: sub is_course {
1.1167 droeschl 9137: my ($cdom, $cnum) = scalar(@_) == 1 ?
9138: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9139:
9140: return unless $cdom and $cnum;
9141:
9142: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9143: '.');
9144:
1.1219 raeburn 9145: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9146: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9147: }
9148:
1.1015 raeburn 9149: sub store_userdata {
9150: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9151: my $result;
1.1016 raeburn 9152: if ($datakey ne '') {
1.1013 raeburn 9153: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9154: if ($udom eq '' || $uname eq '') {
9155: $udom = $env{'user.domain'};
9156: $uname = $env{'user.name'};
9157: }
9158: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9159: if (($uhome eq '') || ($uhome eq 'no_host')) {
9160: $result = 'error: no_host';
9161: } else {
9162: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9163: $storehash->{'host'} = $perlvar{'lonHostID'};
9164:
9165: my $namevalue='';
9166: foreach my $key (keys(%{$storehash})) {
9167: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9168: }
9169: $namevalue=~s/\&$//;
1.1224 raeburn 9170: unless ($namespace eq 'courserequests') {
9171: $datakey = &escape($datakey);
9172: }
1.1105 raeburn 9173: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9174: $namevalue,$uhome);
1.1013 raeburn 9175: }
9176: } else {
9177: $result = 'error: data to store was not a hash reference';
9178: }
9179: } else {
9180: $result= 'error: invalid requestkey';
9181: }
9182: return $result;
9183: }
9184:
1.21 www 9185: # ---------------------------------------------------------- Assign Custom Role
9186:
9187: sub assigncustomrole {
1.957 raeburn 9188: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9189: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9190: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9191: }
9192:
9193: # ----------------------------------------------------------------- Revoke Role
9194:
9195: sub revokerole {
1.957 raeburn 9196: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9197: my $now=time;
1.965 raeburn 9198: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9199: }
9200:
9201: # ---------------------------------------------------------- Revoke Custom Role
9202:
9203: sub revokecustomrole {
1.957 raeburn 9204: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9205: my $now=time;
1.357 www 9206: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9207: $deleteflag,$selfenroll,$context);
1.17 www 9208: }
9209:
1.533 banghart 9210: # ------------------------------------------------------------ Disk usage
1.535 albertel 9211: sub diskusage {
1.955 raeburn 9212: my ($udom,$uname,$directorypath,$getpropath)=@_;
9213: $directorypath =~ s/\/$//;
9214: my $listing=&reply('du2:'.&escape($directorypath).':'
9215: .&escape($getpropath).':'.&escape($uname).':'
9216: .&escape($udom),homeserver($uname,$udom));
9217: if ($listing eq 'unknown_cmd') {
9218: if ($getpropath) {
9219: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9220: }
9221: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9222: }
1.514 albertel 9223: return $listing;
1.512 banghart 9224: }
9225:
1.566 banghart 9226: sub is_locked {
1.1096 raeburn 9227: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9228: my @check;
9229: my $is_locked;
1.1093 raeburn 9230: push (@check,$file_name);
1.613 albertel 9231: my %locked = &get('file_permissions',\@check,
1.620 albertel 9232: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9233: my ($tmp)=keys(%locked);
9234: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9235:
1.566 banghart 9236: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9237: $is_locked = 'false';
9238: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9239: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9240: $is_locked = 'true';
1.1096 raeburn 9241: if (ref($which) eq 'ARRAY') {
9242: push(@{$which},$entry);
9243: } else {
9244: last;
9245: }
1.745 raeburn 9246: }
9247: }
1.566 banghart 9248: } else {
9249: $is_locked = 'false';
9250: }
1.1093 raeburn 9251: return $is_locked;
1.566 banghart 9252: }
9253:
1.759 albertel 9254: sub declutter_portfile {
9255: my ($file) = @_;
1.833 albertel 9256: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9257: return $file;
9258: }
9259:
1.559 banghart 9260: # ------------------------------------------------------------- Mark as Read Only
9261:
9262: sub mark_as_readonly {
9263: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9264: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9265: my ($tmp)=keys(%current_permissions);
9266: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9267: foreach my $file (@{$files}) {
1.759 albertel 9268: $file = &declutter_portfile($file);
1.561 banghart 9269: push(@{$current_permissions{$file}},$what);
1.559 banghart 9270: }
1.613 albertel 9271: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9272: return;
9273: }
9274:
1.572 banghart 9275: # ------------------------------------------------------------Save Selected Files
9276:
9277: sub save_selected_files {
9278: my ($user, $path, @files) = @_;
9279: my $filename = $user."savedfiles";
1.573 banghart 9280: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9281: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9282: foreach my $file (@files) {
1.620 albertel 9283: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9284: }
9285: foreach my $file (@other_files) {
1.574 banghart 9286: print (OUT $file."\n");
1.572 banghart 9287: }
1.574 banghart 9288: close (OUT);
1.572 banghart 9289: return 'ok';
9290: }
9291:
1.574 banghart 9292: sub clear_selected_files {
9293: my ($user) = @_;
9294: my $filename = $user."savedfiles";
1.1117 foxr 9295: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9296: print (OUT undef);
9297: close (OUT);
9298: return ("ok");
9299: }
9300:
1.572 banghart 9301: sub files_in_path {
9302: my ($user, $path) = @_;
9303: my $filename = $user."savedfiles";
9304: my %return_files;
1.1117 foxr 9305: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9306: while (my $line_in = <IN>) {
1.574 banghart 9307: chomp ($line_in);
9308: my @paths_and_file = split (m!/!, $line_in);
9309: my $file_part = pop (@paths_and_file);
9310: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9311: $path_part.='/';
9312: my $path_and_file = $path_part.$file_part;
9313: if ($path_part eq $path) {
9314: $return_files{$file_part}= 'selected';
9315: }
9316: }
1.574 banghart 9317: close (IN);
9318: return (\%return_files);
1.572 banghart 9319: }
9320:
9321: # called in portfolio select mode, to show files selected NOT in current directory
9322: sub files_not_in_path {
9323: my ($user, $path) = @_;
9324: my $filename = $user."savedfiles";
9325: my @return_files;
9326: my $path_part;
1.1117 foxr 9327: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9328: while (my $line = <IN>) {
1.572 banghart 9329: #ok, I know it's clunky, but I want it to work
1.800 albertel 9330: my @paths_and_file = split(m|/|, $line);
9331: my $file_part = pop(@paths_and_file);
9332: chomp($file_part);
9333: my $path_part = join('/', @paths_and_file);
1.572 banghart 9334: $path_part .= '/';
9335: my $path_and_file = $path_part.$file_part;
9336: if ($path_part ne $path) {
1.800 albertel 9337: push(@return_files, ($path_and_file));
1.572 banghart 9338: }
9339: }
1.800 albertel 9340: close(OUT);
1.574 banghart 9341: return (@return_files);
1.572 banghart 9342: }
9343:
1.1273 raeburn 9344: #------------------------------Submitted/Handedback Portfolio Files Versioning
9345:
9346: sub portfiles_versioning {
9347: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9348: my $portfolio_root = '/userfiles/portfolio';
9349: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9350: foreach my $file (@{$portfiles}) {
9351: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9352: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9353: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9354: my $getpropath = 1;
9355: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9356: $stu_name,$getpropath);
9357: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9358: my $new_answer =
9359: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9360: if ($new_answer ne 'problem getting file') {
9361: push(@{$versioned_portfiles}, $directory.$new_answer);
9362: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9363: [$symb,$env{'request.course.id'},'graded']);
9364: }
9365: }
9366: }
9367:
9368: sub get_next_version {
9369: my ($answer_name, $answer_ext, $dir_list) = @_;
9370: my $version;
9371: if (ref($dir_list) eq 'ARRAY') {
9372: foreach my $row (@{$dir_list}) {
9373: my ($file) = split(/\&/,$row,2);
9374: my ($file_name,$file_version,$file_ext) =
9375: &file_name_version_ext($file);
9376: if (($file_name eq $answer_name) &&
9377: ($file_ext eq $answer_ext)) {
9378: # gets here if filename and extension match,
9379: # regardless of version
9380: if ($file_version ne '') {
9381: # a versioned file is found so save it for later
9382: if ($file_version > $version) {
9383: $version = $file_version;
9384: }
9385: }
9386: }
9387: }
9388: }
9389: $version ++;
9390: return($version);
9391: }
9392:
9393: sub version_selected_portfile {
9394: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9395: my ($answer_name,$answer_ver,$answer_ext) =
9396: &file_name_version_ext($file_name);
9397: my $new_answer;
9398: $env{'form.copy'} =
9399: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9400: if($env{'form.copy'} eq '-1') {
9401: $new_answer = 'problem getting file';
9402: } else {
9403: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9404: my $copy_result =
9405: &finishuserfileupload($stu_name,$domain,'copy',
9406: '/portfolio'.$directory.$new_answer);
9407: }
9408: undef($env{'form.copy'});
9409: return ($new_answer);
9410: }
9411:
9412: sub file_name_version_ext {
9413: my ($file)=@_;
9414: my @file_parts = split(/\./, $file);
9415: my ($name,$version,$ext);
9416: if (@file_parts > 1) {
9417: $ext=pop(@file_parts);
9418: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9419: $version=pop(@file_parts);
9420: }
9421: $name=join('.',@file_parts);
9422: } else {
9423: $name=join('.',@file_parts);
9424: }
9425: return($name,$version,$ext);
9426: }
9427:
1.745 raeburn 9428: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9429:
1.745 raeburn 9430: sub get_portfile_permissions {
9431: my ($domain,$user) = @_;
1.613 albertel 9432: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9433: my ($tmp)=keys(%current_permissions);
9434: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9435: return \%current_permissions;
9436: }
9437:
9438: #---------------------------------------------Get portfolio file access controls
9439:
1.749 raeburn 9440: sub get_access_controls {
1.745 raeburn 9441: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9442: my %access;
9443: my $real_file = $file;
9444: $file =~ s/\.meta$//;
1.745 raeburn 9445: if (defined($file)) {
1.749 raeburn 9446: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9447: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9448: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9449: }
9450: }
1.745 raeburn 9451: } else {
1.749 raeburn 9452: foreach my $key (keys(%{$current_permissions})) {
9453: if ($key =~ /\0accesscontrol$/) {
9454: if (defined($group)) {
9455: if ($key !~ m-^\Q$group\E/-) {
9456: next;
9457: }
9458: }
9459: my ($fullpath) = split(/\0/,$key);
9460: if (ref($$current_permissions{$key}) eq 'HASH') {
9461: foreach my $control (keys(%{$$current_permissions{$key}})) {
9462: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9463: }
9464: }
9465: }
9466: }
9467: }
9468: return %access;
9469: }
9470:
9471: sub modify_access_controls {
9472: my ($file_name,$changes,$domain,$user)=@_;
9473: my ($outcome,$deloutcome);
9474: my %store_permissions;
9475: my %new_values;
9476: my %new_control;
9477: my %translation;
9478: my @deletions = ();
9479: my $now = time;
9480: if (exists($$changes{'activate'})) {
9481: if (ref($$changes{'activate'}) eq 'HASH') {
9482: my @newitems = sort(keys(%{$$changes{'activate'}}));
9483: my $numnew = scalar(@newitems);
9484: for (my $i=0; $i<$numnew; $i++) {
9485: my $newkey = $newitems[$i];
9486: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9487: if ($newkey =~ /^\d+:/) {
9488: $newkey =~ s/^(\d+)/$newid/;
9489: $translation{$1} = $newid;
9490: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9491: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9492: $translation{$1} = $newid;
9493: }
1.749 raeburn 9494: $new_values{$file_name."\0".$newkey} =
9495: $$changes{'activate'}{$newitems[$i]};
9496: $new_control{$newkey} = $now;
9497: }
9498: }
9499: }
9500: my %todelete;
9501: my %changed_items;
9502: foreach my $action ('delete','update') {
9503: if (exists($$changes{$action})) {
9504: if (ref($$changes{$action}) eq 'HASH') {
9505: foreach my $key (keys(%{$$changes{$action}})) {
9506: my ($itemnum) = ($key =~ /^([^:]+):/);
9507: if ($action eq 'delete') {
9508: $todelete{$itemnum} = 1;
9509: } else {
9510: $changed_items{$itemnum} = $key;
9511: }
9512: }
1.745 raeburn 9513: }
9514: }
1.749 raeburn 9515: }
9516: # get lock on access controls for file.
9517: my $lockhash = {
9518: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9519: ':'.$env{'user.domain'},
9520: };
9521: my $tries = 0;
9522: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9523:
1.1288 damieng 9524: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9525: $tries ++;
1.1289 ! damieng 9526: sleep(0.1);
1.749 raeburn 9527: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9528: }
9529: if ($gotlock eq 'ok') {
9530: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9531: my ($tmp)=keys(%curr_permissions);
9532: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9533: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9534: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9535: if (ref($curr_controls) eq 'HASH') {
9536: foreach my $control_item (keys(%{$curr_controls})) {
9537: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9538: if (defined($todelete{$itemnum})) {
9539: push(@deletions,$file_name."\0".$control_item);
9540: } else {
9541: if (defined($changed_items{$itemnum})) {
9542: $new_control{$changed_items{$itemnum}} = $now;
9543: push(@deletions,$file_name."\0".$control_item);
9544: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9545: } else {
9546: $new_control{$control_item} = $$curr_controls{$control_item};
9547: }
9548: }
1.745 raeburn 9549: }
9550: }
9551: }
1.970 raeburn 9552: my ($group);
9553: if (&is_course($domain,$user)) {
9554: ($group,my $file) = split(/\//,$file_name,2);
9555: }
1.749 raeburn 9556: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9557: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9558: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9559: # remove lock
9560: my @del_lock = ($file_name."\0".'locked_access_records');
9561: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9562: my $sqlresult =
1.970 raeburn 9563: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9564: $group);
1.749 raeburn 9565: } else {
9566: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9567: }
1.749 raeburn 9568: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9569: }
9570:
1.827 raeburn 9571: sub make_public_indefinitely {
1.1271 raeburn 9572: my (@requrl) = @_;
9573: return &automated_portfile_access('public',\@requrl);
9574: }
9575:
9576: sub automated_portfile_access {
9577: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9578: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9579: return 'invalid';
9580: }
1.1271 raeburn 9581: my %urls;
9582: if (ref($addsref) eq 'ARRAY') {
9583: foreach my $requrl (@{$addsref}) {
9584: if (&is_portfolio_url($requrl)) {
9585: unless (exists($urls{$requrl})) {
9586: $urls{$requrl} = 'add';
9587: }
9588: }
9589: }
9590: }
9591: if (ref($delsref) eq 'ARRAY') {
9592: foreach my $requrl (@{$delsref}) {
9593: if (&is_portfolio_url($requrl)) {
9594: unless (exists($urls{$requrl})) {
9595: $urls{$requrl} = 'delete';
9596: }
9597: }
9598: }
9599: }
9600: unless (keys(%urls)) {
9601: return 'invalid';
9602: }
9603: my $ip;
9604: if ($accesstype eq 'ip') {
9605: if (ref($info) eq 'HASH') {
9606: if ($info->{'ip'} ne '') {
9607: $ip = $info->{'ip'};
9608: }
9609: }
9610: if ($ip eq '') {
9611: return 'invalid';
9612: }
9613: }
9614: my $errors;
1.827 raeburn 9615: my $now = time;
1.1271 raeburn 9616: my %current_perms;
9617: foreach my $requrl (sort(keys(%urls))) {
9618: my $action;
9619: if ($urls{$requrl} eq 'add') {
9620: $action = 'activate';
9621: } else {
9622: $action = 'none';
9623: }
9624: my $aclnum = 0;
1.827 raeburn 9625: my (undef,$udom,$unum,$file_name,$group) =
9626: &parse_portfolio_url($requrl);
1.1271 raeburn 9627: unless (exists($current_perms{$unum.':'.$udom})) {
9628: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9629: }
9630: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9631: $group,$file_name);
9632: foreach my $key (keys(%{$access_controls{$file_name}})) {
9633: my ($num,$scope,$end,$start) =
9634: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9635: if ($scope eq $accesstype) {
9636: if (($start <= $now) && ($end == 0)) {
9637: if ($accesstype eq 'ip') {
9638: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9639: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9640: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9641: if ($urls{$requrl} eq 'add') {
9642: $action = 'none';
9643: last;
9644: } else {
9645: $action = 'delete';
9646: $aclnum = $num;
9647: last;
9648: }
9649: }
9650: }
9651: }
9652: } elsif ($accesstype eq 'public') {
9653: if ($urls{$requrl} eq 'add') {
9654: $action = 'none';
9655: last;
9656: } else {
9657: $action = 'delete';
9658: $aclnum = $num;
9659: last;
9660: }
9661: }
9662: } elsif ($accesstype eq 'public') {
1.827 raeburn 9663: $action = 'update';
9664: $aclnum = $num;
1.1271 raeburn 9665: last;
1.827 raeburn 9666: }
9667: }
9668: }
9669: if ($action eq 'none') {
1.1271 raeburn 9670: next;
1.827 raeburn 9671: } else {
9672: my %changes;
9673: my $newend = 0;
9674: my $newstart = $now;
1.1271 raeburn 9675: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9676: $changes{$action}{$newkey} = {
1.1271 raeburn 9677: type => $accesstype,
1.827 raeburn 9678: time => {
9679: start => $newstart,
9680: end => $newend,
9681: },
9682: };
1.1271 raeburn 9683: if ($accesstype eq 'ip') {
9684: $changes{$action}{$newkey}{'ip'} = [$ip];
9685: }
1.827 raeburn 9686: my ($outcome,$deloutcome,$new_values,$translation) =
9687: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9688: unless ($outcome eq 'ok') {
9689: $errors .= $outcome.' ';
9690: }
1.827 raeburn 9691: }
1.1271 raeburn 9692: }
9693: if ($errors) {
9694: $errors =~ s/\s$//;
9695: return $errors;
1.827 raeburn 9696: } else {
1.1271 raeburn 9697: return 'ok';
1.827 raeburn 9698: }
9699: }
9700:
1.745 raeburn 9701: #------------------------------------------------------Get Marked as Read Only
9702:
9703: sub get_marked_as_readonly {
9704: my ($domain,$user,$what,$group) = @_;
9705: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9706: my @readonly_files;
1.629 banghart 9707: my $cmp1=$what;
9708: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9709: while (my ($file_name,$value) = each(%{$current_permissions})) {
9710: if (defined($group)) {
9711: if ($file_name !~ m-^\Q$group\E/-) {
9712: next;
9713: }
9714: }
1.561 banghart 9715: if (ref($value) eq "ARRAY"){
9716: foreach my $stored_what (@{$value}) {
1.629 banghart 9717: my $cmp2=$stored_what;
1.759 albertel 9718: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9719: $cmp2=join('',@{$stored_what});
1.745 raeburn 9720: }
1.629 banghart 9721: if ($cmp1 eq $cmp2) {
1.561 banghart 9722: push(@readonly_files, $file_name);
1.745 raeburn 9723: last;
1.563 banghart 9724: } elsif (!defined($what)) {
9725: push(@readonly_files, $file_name);
1.745 raeburn 9726: last;
1.561 banghart 9727: }
9728: }
1.745 raeburn 9729: }
1.561 banghart 9730: }
9731: return @readonly_files;
9732: }
1.577 banghart 9733: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9734:
1.577 banghart 9735: sub get_marked_as_readonly_hash {
1.745 raeburn 9736: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9737: my %readonly_files;
1.745 raeburn 9738: while (my ($file_name,$value) = each(%{$current_permissions})) {
9739: if (defined($group)) {
9740: if ($file_name !~ m-^\Q$group\E/-) {
9741: next;
9742: }
9743: }
1.577 banghart 9744: if (ref($value) eq "ARRAY"){
9745: foreach my $stored_what (@{$value}) {
1.745 raeburn 9746: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9747: foreach my $lock_descriptor(@{$stored_what}) {
9748: if ($lock_descriptor eq 'graded') {
9749: $readonly_files{$file_name} = 'graded';
9750: } elsif ($lock_descriptor eq 'handback') {
9751: $readonly_files{$file_name} = 'handback';
9752: } else {
9753: if (!exists($readonly_files{$file_name})) {
9754: $readonly_files{$file_name} = 'locked';
9755: }
9756: }
1.745 raeburn 9757: }
1.750 banghart 9758: }
1.577 banghart 9759: }
9760: }
9761: }
9762: return %readonly_files;
9763: }
1.559 banghart 9764: # ------------------------------------------------------------ Unmark as Read Only
9765:
9766: sub unmark_as_readonly {
1.629 banghart 9767: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9768: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9769: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9770: $file_name = &declutter_portfile($file_name);
1.634 albertel 9771: my $symb_crs = $what;
9772: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9773: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9774: my ($tmp)=keys(%current_permissions);
9775: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9776: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9777: foreach my $file (@readonly_files) {
1.759 albertel 9778: my $clean_file = &declutter_portfile($file);
9779: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9780: my $current_locks = $current_permissions{$file};
1.563 banghart 9781: my @new_locks;
9782: my @del_keys;
9783: if (ref($current_locks) eq "ARRAY"){
9784: foreach my $locker (@{$current_locks}) {
1.632 albertel 9785: my $compare=$locker;
1.749 raeburn 9786: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9787: $compare=join('',@{$locker});
1.746 raeburn 9788: if ($compare ne $symb_crs) {
9789: push(@new_locks, $locker);
9790: }
1.563 banghart 9791: }
9792: }
1.650 albertel 9793: if (scalar(@new_locks) > 0) {
1.563 banghart 9794: $current_permissions{$file} = \@new_locks;
9795: } else {
9796: push(@del_keys, $file);
1.613 albertel 9797: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9798: delete($current_permissions{$file});
1.563 banghart 9799: }
9800: }
1.561 banghart 9801: }
1.613 albertel 9802: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9803: return;
9804: }
1.512 banghart 9805:
1.17 www 9806: # ------------------------------------------------------------ Directory lister
9807:
9808: sub dirlist {
1.955 raeburn 9809: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9810: $uri=~s/^\///;
9811: $uri=~s/\/$//;
1.253 stredwic 9812: my ($udom, $uname);
1.955 raeburn 9813: if ($getuserdir) {
1.253 stredwic 9814: $udom = $userdomain;
9815: $uname = $username;
1.955 raeburn 9816: } else {
9817: (undef,$udom,$uname)=split(/\//,$uri);
9818: if(defined($userdomain)) {
9819: $udom = $userdomain;
9820: }
9821: if(defined($username)) {
9822: $uname = $username;
9823: }
1.253 stredwic 9824: }
1.955 raeburn 9825: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9826:
1.955 raeburn 9827: $dirRoot = $perlvar{'lonDocRoot'};
9828: if (defined($getpropath)) {
9829: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9830: $dirRoot =~ s/\/$//;
1.955 raeburn 9831: } elsif (defined($getuserdir)) {
9832: my $subdir=$uname.'__';
9833: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9834: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9835: ."/$udom/$subdir/$uname";
9836: } elsif (defined($alternateRoot)) {
9837: $dirRoot = $alternateRoot;
1.751 banghart 9838: }
1.253 stredwic 9839:
9840: if($udom) {
9841: if($uname) {
1.1135 raeburn 9842: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9843: if ($uhome eq 'no_host') {
9844: return ([],'no_host');
9845: }
1.955 raeburn 9846: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9847: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9848: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9849: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9850: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9851: } else {
9852: @listing_results = map { &unescape($_); } split(/:/,$listing);
9853: }
1.605 matthew 9854: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9855: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9856: @listing_results = split(/:/,$listing);
9857: } else {
9858: @listing_results = map { &unescape($_); } split(/:/,$listing);
9859: }
1.1135 raeburn 9860: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9861: ($listing eq 'rejected') || ($listing eq 'refused') ||
9862: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9863: return ([],$listing);
9864: } else {
9865: return (\@listing_results);
1.1135 raeburn 9866: }
1.955 raeburn 9867: } elsif(!$alternateRoot) {
1.1136 raeburn 9868: my (%allusers,%listerror);
1.841 albertel 9869: my %servers = &get_servers($udom,'library');
1.955 raeburn 9870: foreach my $tryserver (keys(%servers)) {
9871: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9872: &escape($udom),$tryserver);
9873: if ($listing eq 'unknown_cmd') {
9874: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9875: $udom, $tryserver);
9876: } else {
9877: @listing_results = map { &unescape($_); } split(/:/,$listing);
9878: }
1.841 albertel 9879: if ($listing eq 'unknown_cmd') {
9880: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9881: $udom, $tryserver);
9882: @listing_results = split(/:/,$listing);
9883: } else {
9884: @listing_results =
9885: map { &unescape($_); } split(/:/,$listing);
9886: }
1.1136 raeburn 9887: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9888: ($listing eq 'rejected') || ($listing eq 'refused') ||
9889: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9890: $listerror{$tryserver} = $listing;
9891: } else {
1.841 albertel 9892: foreach my $line (@listing_results) {
9893: my ($entry) = split(/&/,$line,2);
9894: $allusers{$entry} = 1;
9895: }
9896: }
1.253 stredwic 9897: }
1.1136 raeburn 9898: my @alluserslist=();
1.800 albertel 9899: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9900: push(@alluserslist,$user.'&user');
1.253 stredwic 9901: }
1.1136 raeburn 9902: return (\@alluserslist);
1.253 stredwic 9903: } else {
1.1136 raeburn 9904: return ([],'missing username');
1.253 stredwic 9905: }
1.955 raeburn 9906: } elsif(!defined($getpropath)) {
1.1136 raeburn 9907: my $path = $perlvar{'lonDocRoot'}.'/res/';
9908: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9909: return (\@all_domains);
1.955 raeburn 9910: } else {
1.1136 raeburn 9911: return ([],'missing domain');
1.275 stredwic 9912: }
9913: }
9914:
9915: # --------------------------------------------- GetFileTimestamp
9916: # This function utilizes dirlist and returns the date stamp for
9917: # when it was last modified. It will also return an error of -1
9918: # if an error occurs
9919:
9920: sub GetFileTimestamp {
1.955 raeburn 9921: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9922: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9923: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9924: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9925: undef,$getuserdir);
9926: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9927: return -1;
9928: }
9929: if (ref($fileref) eq 'ARRAY') {
9930: my @stats = split('&',$fileref->[0]);
1.375 matthew 9931: # @stats contains first the filename, then the stat output
9932: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9933: } else {
9934: return -1;
1.253 stredwic 9935: }
1.26 www 9936: }
9937:
1.712 albertel 9938: sub stat_file {
9939: my ($uri) = @_;
1.787 albertel 9940: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9941:
1.955 raeburn 9942: my ($udom,$uname,$file);
1.712 albertel 9943: if ($uri =~ m-^/(uploaded|editupload)/-) {
9944: ($udom,$uname,$file) =
1.811 albertel 9945: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9946: $file = 'userfiles/'.$file;
9947: }
9948: if ($uri =~ m-^/res/-) {
9949: ($udom,$uname) =
1.807 albertel 9950: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9951: $file = $uri;
9952: }
9953:
9954: if (!$udom || !$uname || !$file) {
9955: # unable to handle the uri
9956: return ();
9957: }
1.956 raeburn 9958: my $getpropath;
9959: if ($file =~ /^userfiles\//) {
9960: $getpropath = 1;
9961: }
1.1136 raeburn 9962: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9963: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9964: return ();
9965: } else {
9966: if (ref($listref) eq 'ARRAY') {
9967: my @stats = split('&',$listref->[0]);
9968: shift(@stats); #filename is first
9969: return @stats;
9970: }
1.712 albertel 9971: }
9972: return ();
9973: }
9974:
1.26 www 9975: # -------------------------------------------------------- Value of a Condition
9976:
1.713 albertel 9977: # gets the value of a specific preevaluated condition
9978: # stored in the string $env{user.state.<cid>}
9979: # or looks up a condition reference in the bighash and if if hasn't
9980: # already been evaluated recurses into docondval to get the value of
9981: # the condition, then memoizing it to
9982: # $env{user.state.<cid>.<condition>}
1.40 www 9983: sub directcondval {
9984: my $number=shift;
1.620 albertel 9985: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9986: &Apache::lonuserstate::evalstate();
9987: }
1.713 albertel 9988: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9989: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9990: } elsif ($number =~ /^_/) {
9991: my $sub_condition;
9992: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9993: &GDBM_READER(),0640)) {
9994: $sub_condition=$bighash{'conditions'.$number};
9995: untie(%bighash);
9996: }
9997: my $value = &docondval($sub_condition);
1.949 raeburn 9998: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9999: return $value;
10000: }
1.620 albertel 10001: if ($env{'user.state.'.$env{'request.course.id'}}) {
10002: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10003: } else {
10004: return 2;
10005: }
10006: }
10007:
1.713 albertel 10008: # get the collection of conditions for this resource
1.26 www 10009: sub condval {
10010: my $condidx=shift;
1.54 www 10011: my $allpathcond='';
1.713 albertel 10012: foreach my $cond (split(/\|/,$condidx)) {
10013: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10014: $allpathcond.=
10015: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10016: }
1.191 harris41 10017: }
1.54 www 10018: $allpathcond=~s/\|$//;
1.713 albertel 10019: return &docondval($allpathcond);
10020: }
10021:
10022: #evaluates an expression of conditions
10023: sub docondval {
10024: my ($allpathcond) = @_;
10025: my $result=0;
10026: if ($env{'request.course.id'}
10027: && defined($allpathcond)) {
10028: my $operand='|';
10029: my @stack;
10030: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10031: if ($chunk eq '(') {
10032: push @stack,($operand,$result);
10033: } elsif ($chunk eq ')') {
10034: my $before=pop @stack;
10035: if (pop @stack eq '&') {
10036: $result=$result>$before?$before:$result;
10037: } else {
10038: $result=$result>$before?$result:$before;
10039: }
10040: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10041: $operand=$chunk;
10042: } else {
10043: my $new=directcondval($chunk);
10044: if ($operand eq '&') {
10045: $result=$result>$new?$new:$result;
10046: } else {
10047: $result=$result>$new?$result:$new;
10048: }
10049: }
10050: }
1.26 www 10051: }
10052: return $result;
1.421 albertel 10053: }
10054:
10055: # ---------------------------------------------------- Devalidate courseresdata
10056:
10057: sub devalidatecourseresdata {
10058: my ($coursenum,$coursedomain)=@_;
10059: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10060: &devalidate_cache_new('courseres',$hashid);
1.28 www 10061: }
10062:
1.763 www 10063:
1.200 www 10064: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10065: #
10066: # Parameters:
10067: # $coursenum - Number of the course.
10068: # $coursedomain - Domain at which the course was created.
10069: # Returns:
10070: # A hash of the course parameters along (I think) with timestamps
10071: # and version info.
1.877 foxr 10072:
1.624 albertel 10073: sub get_courseresdata {
10074: my ($coursenum,$coursedomain)=@_;
1.200 www 10075: my $coursehom=&homeserver($coursenum,$coursedomain);
10076: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10077: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10078: my %dumpreply;
1.417 albertel 10079: unless (defined($cached)) {
1.624 albertel 10080: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10081: $result=\%dumpreply;
1.251 albertel 10082: my ($tmp) = keys(%dumpreply);
10083: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10084: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10085: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10086: return $tmp;
1.416 albertel 10087: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10088: $result=undef;
1.599 albertel 10089: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10090: }
10091: }
1.624 albertel 10092: return $result;
10093: }
10094:
1.633 albertel 10095: sub devalidateuserresdata {
10096: my ($uname,$udom)=@_;
10097: my $hashid="$udom:$uname";
10098: &devalidate_cache_new('userres',$hashid);
10099: }
10100:
1.624 albertel 10101: sub get_userresdata {
10102: my ($uname,$udom)=@_;
10103: #most student don\'t have any data set, check if there is some data
10104: if (&EXT_cache_status($udom,$uname)) { return undef; }
10105:
10106: my $hashid="$udom:$uname";
10107: my ($result,$cached)=&is_cached_new('userres',$hashid);
10108: if (!defined($cached)) {
10109: my %resourcedata=&dump('resourcedata',$udom,$uname);
10110: $result=\%resourcedata;
10111: &do_cache_new('userres',$hashid,$result,600);
10112: }
10113: my ($tmp)=keys(%$result);
10114: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10115: return $result;
10116: }
10117: #error 2 occurs when the .db doesn't exist
10118: if ($tmp!~/error: 2 /) {
1.672 albertel 10119: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 10120: " Trying to get resource data for ".
10121: $uname." at ".$udom.": ".
10122: $tmp."</font>");
10123: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10124: #&EXT_cache_set($udom,$uname);
10125: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10126: undef($tmp); # not really an error so don't send it back
1.624 albertel 10127: }
10128: return $tmp;
10129: }
1.879 foxr 10130: #----------------------------------------------- resdata - return resource data
10131: # Purpose:
10132: # Return resource data for either users or for a course.
10133: # Parameters:
10134: # $name - Course/user name.
10135: # $domain - Name of the domain the user/course is registered on.
10136: # $type - Type of thing $name is (must be 'course' or 'user'
10137: # @which - Array of names of resources desired.
10138: # Returns:
10139: # The value of the first reasource in @which that is found in the
10140: # resource hash.
10141: # Exceptional Conditions:
10142: # If the $type passed in is not valid (not the string 'course' or
10143: # 'user', an undefined reference is returned.
10144: # If none of the resources are found, an undef is returned
1.624 albertel 10145: sub resdata {
10146: my ($name,$domain,$type,@which)=@_;
10147: my $result;
10148: if ($type eq 'course') {
10149: $result=&get_courseresdata($name,$domain);
10150: } elsif ($type eq 'user') {
10151: $result=&get_userresdata($name,$domain);
10152: }
10153: if (!ref($result)) { return $result; }
1.251 albertel 10154: foreach my $item (@which) {
1.927 albertel 10155: if (defined($result->{$item->[0]})) {
10156: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10157: }
1.250 albertel 10158: }
1.291 albertel 10159: return undef;
1.200 www 10160: }
10161:
1.1236 raeburn 10162: sub get_numsuppfiles {
10163: my ($cnum,$cdom,$ignorecache)=@_;
10164: my $hashid=$cnum.':'.$cdom;
10165: my ($suppcount,$cached);
10166: unless ($ignorecache) {
10167: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10168: }
10169: unless (defined($cached)) {
10170: my $chome=&homeserver($cnum,$cdom);
10171: unless ($chome eq 'no_host') {
10172: ($suppcount,my $errors) = (0,0);
10173: my $suppmap = 'supplemental.sequence';
10174: ($suppcount,$errors) =
10175: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10176: }
10177: &do_cache_new('suppcount',$hashid,$suppcount,600);
10178: }
10179: return $suppcount;
10180: }
10181:
1.379 matthew 10182: #
10183: # EXT resource caching routines
10184: #
10185:
10186: sub clear_EXT_cache_status {
1.383 albertel 10187: &delenv('cache.EXT.');
1.379 matthew 10188: }
10189:
10190: sub EXT_cache_status {
10191: my ($target_domain,$target_user) = @_;
1.383 albertel 10192: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10193: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10194: # We know already the user has no data
10195: return 1;
10196: } else {
10197: return 0;
10198: }
10199: }
10200:
10201: sub EXT_cache_set {
10202: my ($target_domain,$target_user) = @_;
1.383 albertel 10203: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10204: #&appenv({$cachename => time});
1.379 matthew 10205: }
10206:
1.28 www 10207: # --------------------------------------------------------- Value of a Variable
1.58 www 10208: sub EXT {
1.715 albertel 10209:
1.1228 raeburn 10210: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10211: unless ($varname) { return ''; }
1.218 albertel 10212: #get real user name/domain, courseid and symb
10213: my $courseid;
1.359 albertel 10214: my $publicuser;
1.427 www 10215: if ($symbparm) {
10216: $symbparm=&get_symb_from_alias($symbparm);
10217: }
1.218 albertel 10218: if (!($uname && $udom)) {
1.790 albertel 10219: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10220: if (!$symbparm) { $symbparm=$cursymb; }
10221: } else {
1.620 albertel 10222: $courseid=$env{'request.course.id'};
1.218 albertel 10223: }
1.48 www 10224: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10225: my $rest;
1.320 albertel 10226: if (defined($therest[0])) {
1.48 www 10227: $rest=join('.',@therest);
10228: } else {
10229: $rest='';
10230: }
1.320 albertel 10231:
1.57 www 10232: my $qualifierrest=$qualifier;
10233: if ($rest) { $qualifierrest.='.'.$rest; }
10234: my $spacequalifierrest=$space;
10235: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10236: if ($realm eq 'user') {
1.48 www 10237: # --------------------------------------------------------------- user.resource
10238: if ($space eq 'resource') {
1.651 albertel 10239: if ( (defined($Apache::lonhomework::parsing_a_problem)
10240: || defined($Apache::lonhomework::parsing_a_task))
10241: &&
1.744 albertel 10242: ($symbparm eq &symbread()) ) {
10243: # if we are in the middle of processing the resource the
10244: # get the value we are planning on committing
10245: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10246: return $Apache::lonhomework::results{$qualifierrest};
10247: } else {
10248: return $Apache::lonhomework::history{$qualifierrest};
10249: }
1.335 albertel 10250: } else {
1.359 albertel 10251: my %restored;
1.620 albertel 10252: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10253: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10254: } else {
10255: %restored=&restore($symbparm,$courseid,$udom,$uname);
10256: }
1.335 albertel 10257: return $restored{$qualifierrest};
10258: }
1.48 www 10259: # ----------------------------------------------------------------- user.access
10260: } elsif ($space eq 'access') {
1.218 albertel 10261: # FIXME - not supporting calls for a specific user
1.48 www 10262: return &allowed($qualifier,$rest);
10263: # ------------------------------------------ user.preferences, user.environment
10264: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10265: if (($uname eq $env{'user.name'}) &&
10266: ($udom eq $env{'user.domain'})) {
10267: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10268: } else {
1.359 albertel 10269: my %returnhash;
10270: if (!$publicuser) {
10271: %returnhash=&userenvironment($udom,$uname,
10272: $qualifierrest);
10273: }
1.218 albertel 10274: return $returnhash{$qualifierrest};
10275: }
1.48 www 10276: # ----------------------------------------------------------------- user.course
10277: } elsif ($space eq 'course') {
1.218 albertel 10278: # FIXME - not supporting calls for a specific user
1.620 albertel 10279: return $env{join('.',('request.course',$qualifier))};
1.48 www 10280: # ------------------------------------------------------------------- user.role
10281: } elsif ($space eq 'role') {
1.218 albertel 10282: # FIXME - not supporting calls for a specific user
1.620 albertel 10283: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10284: if ($qualifier eq 'value') {
10285: return $role;
10286: } elsif ($qualifier eq 'extent') {
10287: return $where;
10288: }
10289: # ----------------------------------------------------------------- user.domain
10290: } elsif ($space eq 'domain') {
1.218 albertel 10291: return $udom;
1.48 www 10292: # ------------------------------------------------------------------- user.name
10293: } elsif ($space eq 'name') {
1.218 albertel 10294: return $uname;
1.48 www 10295: # ---------------------------------------------------- Any other user namespace
1.29 www 10296: } else {
1.359 albertel 10297: my %reply;
10298: if (!$publicuser) {
10299: %reply=&get($space,[$qualifierrest],$udom,$uname);
10300: }
10301: return $reply{$qualifierrest};
1.48 www 10302: }
1.236 www 10303: } elsif ($realm eq 'query') {
10304: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10305: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10306: [$spacequalifierrest]);
1.620 albertel 10307: return $env{'form.'.$spacequalifierrest};
1.236 www 10308: } elsif ($realm eq 'request') {
1.48 www 10309: # ------------------------------------------------------------- request.browser
10310: if ($space eq 'browser') {
1.1145 bisitz 10311: return $env{'browser.'.$qualifier};
1.57 www 10312: # ------------------------------------------------------------ request.filename
10313: } else {
1.620 albertel 10314: return $env{'request.'.$spacequalifierrest};
1.29 www 10315: }
1.28 www 10316: } elsif ($realm eq 'course') {
1.48 www 10317: # ---------------------------------------------------------- course.description
1.620 albertel 10318: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10319: } elsif ($realm eq 'resource') {
1.165 www 10320:
1.620 albertel 10321: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10322: if (!$symbparm) { $symbparm=&symbread(); }
10323: }
1.693 albertel 10324:
1.1232 raeburn 10325: if ($qualifier eq '') {
10326: if ($space eq 'title') {
10327: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10328: return &gettitle($symbparm);
10329: }
1.693 albertel 10330:
1.1232 raeburn 10331: if ($space eq 'map') {
10332: my ($map) = &decode_symb($symbparm);
10333: return &symbread($map);
10334: }
10335: if ($space eq 'maptitle') {
10336: my ($map) = &decode_symb($symbparm);
10337: return &gettitle($map);
10338: }
10339: if ($space eq 'filename') {
10340: if ($symbparm) {
10341: return &clutter((&decode_symb($symbparm))[2]);
10342: }
10343: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10344: }
1.1232 raeburn 10345:
1.1233 raeburn 10346: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10347: if ($space eq 'visibleparts') {
10348: my $navmap = Apache::lonnavmaps::navmap->new();
10349: my $item;
10350: if (ref($navmap)) {
10351: my $res = $navmap->getBySymb($symbparm);
10352: my $parts = $res->parts();
10353: if (ref($parts) eq 'ARRAY') {
10354: $item = join(',',@{$parts});
10355: }
10356: undef($navmap);
1.1232 raeburn 10357: }
1.1233 raeburn 10358: return $item;
1.1232 raeburn 10359: }
10360: }
10361: }
1.693 albertel 10362:
10363: my ($section, $group, @groups);
1.593 albertel 10364: my ($courselevelm,$courselevel);
1.1228 raeburn 10365: if (($courseid eq '') && ($cid)) {
10366: $courseid = $cid;
10367: }
10368: if (($symbparm && $courseid) &&
10369: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10370:
1.218 albertel 10371: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10372:
1.60 www 10373: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10374: my $symbp=$symbparm;
1.735 albertel 10375: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10376:
10377: my $symbparm=$symbp.'.'.$spacequalifierrest;
10378: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10379:
1.620 albertel 10380: if (($env{'user.name'} eq $uname) &&
10381: ($env{'user.domain'} eq $udom)) {
10382: $section=$env{'request.course.sec'};
1.733 raeburn 10383: @groups = split(/:/,$env{'request.course.groups'});
10384: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10385: } else {
1.539 albertel 10386: if (! defined($usection)) {
1.551 albertel 10387: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10388: } else {
10389: $section = $usection;
10390: }
1.733 raeburn 10391: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10392: }
10393:
10394: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10395: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10396: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10397:
1.593 albertel 10398: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10399: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10400: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10401:
1.60 www 10402: # ----------------------------------------------------------- first, check user
1.624 albertel 10403:
10404: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10405: ([$courselevelr,'resource'],
10406: [$courselevelm,'map' ],
10407: [$courselevel, 'course' ]));
1.931 albertel 10408: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10409:
1.594 albertel 10410: # ------------------------------------------------ second, check some of course
1.684 raeburn 10411: my $coursereply;
1.691 raeburn 10412: if (@groups > 0) {
10413: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10414: $mapparm,$spacequalifierrest);
1.927 albertel 10415: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10416: }
1.96 www 10417:
1.684 raeburn 10418: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10419: $env{'course.'.$courseid.'.domain'},
10420: 'course',
10421: ([$seclevelr, 'resource'],
10422: [$seclevelm, 'map' ],
10423: [$seclevel, 'course' ],
10424: [$courselevelr,'resource']));
10425: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10426:
1.60 www 10427: # ------------------------------------------------------ third, check map parms
1.218 albertel 10428: my %parmhash=();
10429: my $thisparm='';
10430: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10431: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10432: &GDBM_READER(),0640)) {
1.218 albertel 10433: $thisparm=$parmhash{$symbparm};
10434: untie(%parmhash);
10435: }
1.927 albertel 10436: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10437: }
1.594 albertel 10438: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10439:
1.218 albertel 10440: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10441: my $filename;
10442: if (!$symbparm) { $symbparm=&symbread(); }
10443: if ($symbparm) {
1.409 www 10444: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10445: } else {
1.620 albertel 10446: $filename=$env{'request.filename'};
1.282 albertel 10447: }
10448: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10449: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10450: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10451: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10452:
1.927 albertel 10453: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10454: if ($symbparm && defined($courseid) &&
1.620 albertel 10455: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10456: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10457: $env{'course.'.$courseid.'.domain'},
10458: 'course',
1.927 albertel 10459: ([$courselevelm,'map' ],
10460: [$courselevel, 'course']));
10461: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10462: }
1.145 www 10463: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10464: unless ($space eq '0') {
1.336 albertel 10465: my @parts=split(/_/,$space);
10466: my $id=pop(@parts);
10467: my $part=join('_',@parts);
10468: if ($part eq '') { $part='0'; }
1.927 albertel 10469: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10470: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10471: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10472: }
1.395 albertel 10473: if ($recurse) { return undef; }
10474: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10475: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10476: # ---------------------------------------------------- Any other user namespace
10477: } elsif ($realm eq 'environment') {
10478: # ----------------------------------------------------------------- environment
1.620 albertel 10479: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10480: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10481: } else {
1.770 albertel 10482: if ($uname eq 'anonymous' && $udom eq '') {
10483: return '';
10484: }
1.219 albertel 10485: my %returnhash=&userenvironment($udom,$uname,
10486: $spacequalifierrest);
10487: return $returnhash{$spacequalifierrest};
10488: }
1.28 www 10489: } elsif ($realm eq 'system') {
1.48 www 10490: # ----------------------------------------------------------------- system.time
10491: if ($space eq 'time') {
10492: return time;
10493: }
1.696 albertel 10494: } elsif ($realm eq 'server') {
10495: # ----------------------------------------------------------------- system.time
10496: if ($space eq 'name') {
10497: return $ENV{'SERVER_NAME'};
10498: }
1.28 www 10499: }
1.48 www 10500: return '';
1.61 www 10501: }
10502:
1.927 albertel 10503: sub get_reply {
10504: my ($reply_value) = @_;
1.940 raeburn 10505: if (ref($reply_value) eq 'ARRAY') {
10506: if (wantarray) {
10507: return @$reply_value;
10508: }
10509: return $reply_value->[0];
10510: } else {
10511: return $reply_value;
1.927 albertel 10512: }
10513: }
10514:
1.691 raeburn 10515: sub check_group_parms {
10516: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10517: my @groupitems = ();
10518: my $resultitem;
1.927 albertel 10519: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10520: foreach my $group (@{$groups}) {
10521: foreach my $level (@levels) {
1.927 albertel 10522: my $item = $courseid.'.['.$group.'].'.$level->[0];
10523: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10524: }
10525: }
10526: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10527: $env{'course.'.$courseid.'.domain'},
10528: 'course',@groupitems);
10529: return $coursereply;
10530: }
10531:
10532: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10533: my ($courseid,@groups) = @_;
10534: @groups = sort(@groups);
1.691 raeburn 10535: return @groups;
10536: }
10537:
1.395 albertel 10538: sub packages_tab_default {
10539: my ($uri,$varname)=@_;
10540: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10541:
10542: my (@extension,@specifics,$do_default);
10543: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10544: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10545: if ($pack_type eq 'default') {
10546: $do_default=1;
10547: } elsif ($pack_type eq 'extension') {
10548: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10549: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10550: # only look at packages defaults for packages that this id is
1.738 albertel 10551: push(@specifics,[$package,$pack_type,$pack_part]);
10552: }
10553: }
10554: # first look for a package that matches the requested part id
10555: foreach my $package (@specifics) {
10556: my (undef,$pack_type,$pack_part)=@{$package};
10557: next if ($pack_part ne $part);
10558: if (defined($packagetab{"$pack_type&$name&default"})) {
10559: return $packagetab{"$pack_type&$name&default"};
10560: }
10561: }
10562: # look for any possible matching non extension_ package
10563: foreach my $package (@specifics) {
10564: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10565: if (defined($packagetab{"$pack_type&$name&default"})) {
10566: return $packagetab{"$pack_type&$name&default"};
10567: }
1.585 albertel 10568: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10569: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10570: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10571: }
10572: }
1.738 albertel 10573: # look for any posible extension_ match
10574: foreach my $package (@extension) {
10575: my ($package,$pack_type)=@{$package};
10576: if (defined($packagetab{"$pack_type&$name&default"})) {
10577: return $packagetab{"$pack_type&$name&default"};
10578: }
10579: if (defined($packagetab{$package."&$name&default"})) {
10580: return $packagetab{$package."&$name&default"};
10581: }
10582: }
10583: # look for a global default setting
10584: if ($do_default && defined($packagetab{"default&$name&default"})) {
10585: return $packagetab{"default&$name&default"};
10586: }
1.395 albertel 10587: return undef;
10588: }
10589:
1.334 albertel 10590: sub add_prefix_and_part {
10591: my ($prefix,$part)=@_;
10592: my $keyroot;
10593: if (defined($prefix) && $prefix !~ /^__/) {
10594: # prefix that has a part already
10595: $keyroot=$prefix;
10596: } elsif (defined($prefix)) {
10597: # prefix that is missing a part
10598: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10599: } else {
10600: # no prefix at all
10601: if (defined($part)) { $keyroot='_'.$part; }
10602: }
10603: return $keyroot;
10604: }
10605:
1.71 www 10606: # ---------------------------------------------------------------- Get metadata
10607:
1.599 albertel 10608: my %metaentry;
1.1070 www 10609: my %importedpartids;
1.71 www 10610: sub metadata {
1.176 www 10611: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10612: $uri=&declutter($uri);
1.288 albertel 10613: # if it is a non metadata possible uri return quickly
1.529 albertel 10614: if (($uri eq '') ||
10615: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10616: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10617: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10618: return undef;
10619: }
1.1261 raeburn 10620: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10621: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10622: return undef;
1.288 albertel 10623: }
1.73 www 10624: my $filename=$uri;
10625: $uri=~s/\.meta$//;
1.172 www 10626: #
10627: # Is the metadata already cached?
1.177 www 10628: # Look at timestamp of caching
1.172 www 10629: # Everything is cached by the main uri, libraries are never directly cached
10630: #
1.428 albertel 10631: if (!defined($liburi)) {
1.599 albertel 10632: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10633: if (defined($cached)) { return $result->{':'.$what}; }
10634: }
10635: {
1.1069 www 10636: # Imported parts would go here
1.1070 www 10637: my %importedids=();
10638: my @origfileimportpartids=();
1.1069 www 10639: my $importedparts=0;
1.172 www 10640: #
10641: # Is this a recursive call for a library?
10642: #
1.599 albertel 10643: # if (! exists($metacache{$uri})) {
10644: # $metacache{$uri}={};
10645: # }
1.924 albertel 10646: my $cachetime = 60*60;
1.171 www 10647: if ($liburi) {
10648: $liburi=&declutter($liburi);
10649: $filename=$liburi;
1.401 bowersj2 10650: } else {
1.599 albertel 10651: &devalidate_cache_new('meta',$uri);
10652: undef(%metaentry);
1.401 bowersj2 10653: }
1.140 www 10654: my %metathesekeys=();
1.73 www 10655: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10656: my $metastring;
1.1140 www 10657: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10658: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10659: $metastring =
1.929 albertel 10660: &Apache::lonnet::ssi_body($which,
1.924 albertel 10661: ('grade_target' => 'meta'));
10662: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10663: } elsif (($uri !~ m -^(editupload)/-) &&
10664: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10665: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10666: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10667: $metastring=&getfile($file);
1.489 albertel 10668: }
1.208 albertel 10669: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10670: my $token;
1.140 www 10671: undef %metathesekeys;
1.71 www 10672: while ($token=$parser->get_token) {
1.339 albertel 10673: if ($token->[0] eq 'S') {
10674: if (defined($token->[2]->{'package'})) {
1.172 www 10675: #
10676: # This is a package - get package info
10677: #
1.339 albertel 10678: my $package=$token->[2]->{'package'};
10679: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10680: if (defined($token->[2]->{'id'})) {
10681: $keyroot.='_'.$token->[2]->{'id'};
10682: }
1.599 albertel 10683: if ($metaentry{':packages'}) {
10684: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10685: } else {
1.599 albertel 10686: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10687: }
1.736 albertel 10688: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10689: my $part=$keyroot;
10690: $part=~s/^\_//;
1.736 albertel 10691: if ($pack_entry=~/^\Q$package\E\&/ ||
10692: $pack_entry=~/^\Q$package\E_0\&/) {
10693: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10694: # ignore package.tab specified default values
10695: # here &package_tab_default() will fetch those
10696: if ($subp eq 'default') { next; }
1.736 albertel 10697: my $value=$packagetab{$pack_entry};
1.432 albertel 10698: my $unikey;
10699: if ($pack =~ /_0$/) {
10700: $unikey='parameter_0_'.$name;
10701: $part=0;
10702: } else {
10703: $unikey='parameter'.$keyroot.'_'.$name;
10704: }
1.339 albertel 10705: if ($subp eq 'display') {
10706: $value.=' [Part: '.$part.']';
10707: }
1.599 albertel 10708: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10709: $metathesekeys{$unikey}=1;
1.599 albertel 10710: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10711: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10712: }
1.599 albertel 10713: if (defined($metaentry{':'.$unikey.'.default'})) {
10714: $metaentry{':'.$unikey}=
10715: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10716: }
1.339 albertel 10717: }
10718: }
10719: } else {
1.172 www 10720: #
10721: # This is not a package - some other kind of start tag
1.339 albertel 10722: #
10723: my $entry=$token->[1];
1.1068 www 10724: my $unikey='';
1.175 www 10725:
1.339 albertel 10726: if ($entry eq 'import') {
1.175 www 10727: #
10728: # Importing a library here
1.339 albertel 10729: #
1.1067 www 10730: my $location=$parser->get_text('/import');
10731: my $dir=$filename;
10732: $dir=~s|[^/]*$||;
10733: $location=&filelocation($dir,$location);
1.1069 www 10734:
1.1068 www 10735: my $importmode=$token->[2]->{'importmode'};
10736: if ($importmode eq 'problem') {
1.1069 www 10737: # Import as problem/response
1.1068 www 10738: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10739: } elsif ($importmode eq 'part') {
10740: # Import as part(s)
1.1069 www 10741: $importedparts=1;
10742: # We need to get the original file and the imported file to get the part order correct
10743: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10744: # Load and inspect original file
1.1070 www 10745: if ($#origfileimportpartids<0) {
10746: undef(%importedpartids);
10747: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10748: my $origfile=&getfile($origfilelocation);
10749: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10750: }
10751:
1.1069 www 10752: # Load and inspect imported file
10753: my $impfile=&getfile($location);
10754: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10755: if ($#impfilepartids>=0) {
10756: # This problem had parts
1.1070 www 10757: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10758: } else {
10759: # Importing by turning a single problem into a problem part
10760: # It gets the import-tags ID as part-ID
10761: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10762: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10763: }
1.1068 www 10764: } else {
10765: # Normal import
10766: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10767: if (defined($token->[2]->{'id'})) {
10768: $unikey.='_'.$token->[2]->{'id'};
10769: }
1.1067 www 10770: }
10771:
1.339 albertel 10772: if ($depthcount<20) {
1.736 albertel 10773: my $metadata =
10774: &metadata($uri,'keys', $location,$unikey,
10775: $depthcount+1);
10776: foreach my $meta (split(',',$metadata)) {
10777: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10778: $metathesekeys{$meta}=1;
1.339 albertel 10779: }
1.1068 www 10780:
10781: }
1.1067 www 10782: } else {
10783: #
10784: # Not importing, some other kind of non-package, non-library start tag
10785: #
10786: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10787: if (defined($token->[2]->{'id'})) {
10788: $unikey.='_'.$token->[2]->{'id'};
10789: }
1.339 albertel 10790: if (defined($token->[2]->{'name'})) {
10791: $unikey.='_'.$token->[2]->{'name'};
10792: }
10793: $metathesekeys{$unikey}=1;
1.736 albertel 10794: foreach my $param (@{$token->[3]}) {
10795: $metaentry{':'.$unikey.'.'.$param} =
10796: $token->[2]->{$param};
1.339 albertel 10797: }
10798: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10799: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10800: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10801: # only ws inside the tag, and not in default, so use default
10802: # as value
1.599 albertel 10803: $metaentry{':'.$unikey}=$default;
1.908 albertel 10804: } elsif ( $internaltext =~ /\S/ ) {
10805: # something interesting inside the tag
10806: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10807: } else {
1.908 albertel 10808: # no interesting values, don't set a default
1.339 albertel 10809: }
1.172 www 10810: # end of not-a-package not-a-library import
1.339 albertel 10811: }
1.172 www 10812: # end of not-a-package start tag
1.339 albertel 10813: }
1.172 www 10814: # the next is the end of "start tag"
1.339 albertel 10815: }
10816: }
1.483 albertel 10817: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10818: $extension = lc($extension);
10819: if ($extension eq 'htm') { $extension='html'; }
10820:
1.737 albertel 10821: foreach my $key (keys(%packagetab)) {
1.483 albertel 10822: #no specific packages #how's our extension
10823: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10824: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10825: \%metathesekeys);
10826: }
1.883 albertel 10827:
10828: if (!exists($metaentry{':packages'})
10829: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10830: foreach my $key (keys(%packagetab)) {
1.483 albertel 10831: #no specific packages well let's get default then
10832: if ($key!~/^default&/) { next; }
1.488 albertel 10833: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10834: \%metathesekeys);
10835: }
10836: }
1.338 www 10837: # are there custom rights to evaluate
1.599 albertel 10838: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10839:
1.338 www 10840: #
10841: # Importing a rights file here
1.339 albertel 10842: #
10843: unless ($depthcount) {
1.599 albertel 10844: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10845: my $dir=$filename;
10846: $dir=~s|[^/]*$||;
10847: $location=&filelocation($dir,$location);
1.736 albertel 10848: my $rights_metadata =
10849: &metadata($uri,'keys',$location,'_rights',
10850: $depthcount+1);
10851: foreach my $rights (split(',',$rights_metadata)) {
10852: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10853: $metathesekeys{$rights}=1;
1.339 albertel 10854: }
10855: }
10856: }
1.737 albertel 10857: # uniqifiy package listing
10858: my %seen;
10859: my @uniq_packages =
10860: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10861: $metaentry{':packages'} = join(',',@uniq_packages);
10862:
1.1070 www 10863: if ($importedparts) {
10864: # We had imported parts and need to rebuild partorder
10865: $metaentry{':partorder'}='';
10866: $metathesekeys{'partorder'}=1;
10867: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10868: if ($origfileimportpartids[$index] eq 'part') {
10869: # original part, part of the problem
10870: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10871: } else {
10872: # we have imported parts at this position
10873: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10874: }
10875: }
10876: $metaentry{':partorder'}=~s/^\,//;
10877: }
10878:
1.737 albertel 10879: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10880: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10881: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10882: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10883: # this is the end of "was not already recently cached
1.71 www 10884: }
1.599 albertel 10885: return $metaentry{':'.$what};
1.261 albertel 10886: }
10887:
1.488 albertel 10888: sub metadata_create_package_def {
1.483 albertel 10889: my ($uri,$key,$package,$metathesekeys)=@_;
10890: my ($pack,$name,$subp)=split(/\&/,$key);
10891: if ($subp eq 'default') { next; }
10892:
1.599 albertel 10893: if (defined($metaentry{':packages'})) {
10894: $metaentry{':packages'}.=','.$package;
1.483 albertel 10895: } else {
1.599 albertel 10896: $metaentry{':packages'}=$package;
1.483 albertel 10897: }
10898: my $value=$packagetab{$key};
10899: my $unikey;
10900: $unikey='parameter_0_'.$name;
1.599 albertel 10901: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10902: $$metathesekeys{$unikey}=1;
1.599 albertel 10903: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10904: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10905: }
1.599 albertel 10906: if (defined($metaentry{':'.$unikey.'.default'})) {
10907: $metaentry{':'.$unikey}=
10908: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10909: }
10910: }
10911:
1.261 albertel 10912: sub metadata_generate_part0 {
10913: my ($metadata,$metacache,$uri) = @_;
10914: my %allnames;
1.737 albertel 10915: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10916: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10917: my $part=$$metacache{':'.$metakey.'.part'};
10918: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10919: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10920: $allnames{$name}=$part;
10921: }
10922: }
10923: }
10924: foreach my $name (keys(%allnames)) {
10925: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10926: my $key=":parameter_0_$name";
1.261 albertel 10927: $$metacache{"$key.part"}='0';
10928: $$metacache{"$key.name"}=$name;
1.428 albertel 10929: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10930: $allnames{$name}.'_'.$name.
10931: '.type'};
1.428 albertel 10932: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10933: '.display'};
1.644 www 10934: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10935: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10936: $$metacache{"$key.display"}=$olddis;
10937: }
1.71 www 10938: }
10939:
1.764 albertel 10940: # ------------------------------------------------------ Devalidate title cache
10941:
10942: sub devalidate_title_cache {
10943: my ($url)=@_;
10944: if (!$env{'request.course.id'}) { return; }
10945: my $symb=&symbread($url);
10946: if (!$symb) { return; }
10947: my $key=$env{'request.course.id'}."\0".$symb;
10948: &devalidate_cache_new('title',$key);
10949: }
10950:
1.1014 droeschl 10951: # ------------------------------------------------- Get the title of a course
10952:
10953: sub current_course_title {
10954: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10955: }
1.301 www 10956: # ------------------------------------------------- Get the title of a resource
10957:
10958: sub gettitle {
10959: my $urlsymb=shift;
10960: my $symb=&symbread($urlsymb);
1.534 albertel 10961: if ($symb) {
1.620 albertel 10962: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10963: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10964: if (defined($cached)) {
10965: return $result;
10966: }
1.534 albertel 10967: my ($map,$resid,$url)=&decode_symb($symb);
10968: my $title='';
1.907 albertel 10969: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10970: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10971: } else {
10972: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10973: &GDBM_READER(),0640)) {
10974: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10975: $title=$bighash{'title_'.$mapid.'.'.$resid};
10976: untie(%bighash);
10977: }
1.534 albertel 10978: }
10979: $title=~s/\&colon\;/\:/gs;
10980: if ($title) {
1.1159 www 10981: # Remember both $symb and $title for dynamic metadata
10982: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10983: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10984: # Cache this title and then return it
1.599 albertel 10985: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10986: }
10987: $urlsymb=$url;
10988: }
10989: my $title=&metadata($urlsymb,'title');
10990: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10991: return $title;
1.301 www 10992: }
1.613 albertel 10993:
1.614 albertel 10994: sub get_slot {
10995: my ($which,$cnum,$cdom)=@_;
10996: if (!$cnum || !$cdom) {
1.790 albertel 10997: (undef,my $courseid)=&whichuser();
1.620 albertel 10998: $cdom=$env{'course.'.$courseid.'.domain'};
10999: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11000: }
1.703 albertel 11001: my $key=join("\0",'slots',$cdom,$cnum,$which);
11002: my %slotinfo;
11003: if (exists($remembered{$key})) {
11004: $slotinfo{$which} = $remembered{$key};
11005: } else {
11006: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11007: &Apache::lonhomework::showhash(%slotinfo);
11008: my ($tmp)=keys(%slotinfo);
11009: if ($tmp=~/^error:/) { return (); }
11010: $remembered{$key} = $slotinfo{$which};
11011: }
1.616 albertel 11012: if (ref($slotinfo{$which}) eq 'HASH') {
11013: return %{$slotinfo{$which}};
11014: }
11015: return $slotinfo{$which};
1.614 albertel 11016: }
1.1150 raeburn 11017:
11018: sub get_reservable_slots {
11019: my ($cnum,$cdom,$uname,$udom) = @_;
11020: my $now = time;
11021: my $reservable_info;
11022: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11023: if (exists($remembered{$key})) {
11024: $reservable_info = $remembered{$key};
11025: } else {
11026: my %resv;
11027: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11028: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11029: $reservable_info = \%resv;
11030: $remembered{$key} = $reservable_info;
11031: }
11032: return $reservable_info;
11033: }
11034:
11035: sub get_course_slots {
11036: my ($cnum,$cdom) = @_;
11037: my $hashid=$cnum.':'.$cdom;
11038: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11039: if (defined($cached)) {
11040: if (ref($result) eq 'HASH') {
11041: return %{$result};
11042: }
11043: } else {
11044: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11045: my ($tmp) = keys(%slots);
11046: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11047: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11048: return %slots;
11049: }
11050: }
11051: return;
11052: }
11053:
11054: sub devalidate_slots_cache {
11055: my ($cnum,$cdom)=@_;
11056: my $hashid=$cnum.':'.$cdom;
11057: &devalidate_cache_new('allslots',$hashid);
11058: }
11059:
1.1181 raeburn 11060: sub get_coursechange {
11061: my ($cdom,$cnum) = @_;
11062: if ($cdom eq '' || $cnum eq '') {
11063: return unless ($env{'request.course.id'});
11064: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11065: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11066: }
11067: my $hashid=$cdom.'_'.$cnum;
11068: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11069: if ((defined($cached)) && ($change ne '')) {
11070: return $change;
11071: } else {
11072: my %crshash;
11073: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11074: if ($crshash{'internal.contentchange'} eq '') {
11075: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11076: if ($change eq '') {
11077: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11078: $change = $crshash{'internal.created'};
11079: }
11080: } else {
11081: $change = $crshash{'internal.contentchange'};
11082: }
11083: my $cachetime = 600;
11084: &do_cache_new('crschange',$hashid,$change,$cachetime);
11085: }
11086: return $change;
11087: }
11088:
11089: sub devalidate_coursechange_cache {
11090: my ($cnum,$cdom)=@_;
11091: my $hashid=$cnum.':'.$cdom;
11092: &devalidate_cache_new('crschange',$hashid);
11093: }
11094:
1.31 www 11095: # ------------------------------------------------- Update symbolic store links
11096:
11097: sub symblist {
11098: my ($mapname,%newhash)=@_;
1.438 www 11099: $mapname=&deversion(&declutter($mapname));
1.31 www 11100: my %hash;
1.620 albertel 11101: if (($env{'request.course.fn'}) && (%newhash)) {
11102: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11103: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11104: foreach my $url (keys(%newhash)) {
1.711 albertel 11105: next if ($url eq 'last_known'
11106: && $env{'form.no_update_last_known'});
11107: $hash{declutter($url)}=&encode_symb($mapname,
11108: $newhash{$url}->[1],
11109: $newhash{$url}->[0]);
1.191 harris41 11110: }
1.31 www 11111: if (untie(%hash)) {
11112: return 'ok';
11113: }
11114: }
11115: }
11116: return 'error';
1.212 www 11117: }
11118:
11119: # --------------------------------------------------------------- Verify a symb
11120:
11121: sub symbverify {
1.1190 raeburn 11122: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11123: my $thisfn=$thisurl;
1.439 www 11124: $thisfn=&declutter($thisfn);
1.215 www 11125: # direct jump to resource in page or to a sequence - will construct own symbs
11126: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11127: # check URL part
1.409 www 11128: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11129:
1.431 www 11130: unless ($url eq $thisfn) { return 0; }
1.213 www 11131:
1.216 www 11132: $symb=&symbclean($symb);
1.510 www 11133: $thisurl=&deversion($thisurl);
1.439 www 11134: $thisfn=&deversion($thisfn);
1.213 www 11135:
11136: my %bighash;
11137: my $okay=0;
1.431 www 11138:
1.620 albertel 11139: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11140: &GDBM_READER(),0640)) {
1.1204 raeburn 11141: my $noclutter;
1.1032 raeburn 11142: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11143: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11144: if ($map =~ m{^uploaded/.+\.page$}) {
11145: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11146: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11147: $noclutter = 1;
11148: }
11149: }
11150: my $ids;
11151: if ($noclutter) {
11152: $ids=$bighash{'ids_'.$thisurl};
11153: } else {
11154: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11155: }
1.1102 raeburn 11156: unless ($ids) {
11157: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11158: $ids=$bighash{$idkey};
1.216 www 11159: }
11160: if ($ids) {
11161: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11162: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11163: $symb =~ s/\?.+$//;
1.1202 raeburn 11164: }
1.800 albertel 11165: foreach my $id (split(/\,/,$ids)) {
11166: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11167: if (
11168: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11169: eq $symb) {
11170: if (ref($encstate)) {
11171: $$encstate = $bighash{'encrypted_'.$id};
11172: }
1.620 albertel 11173: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11174: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11175: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11176: $okay=1;
1.1202 raeburn 11177: last;
1.582 albertel 11178: }
11179: }
1.216 www 11180: }
11181: }
1.213 www 11182: untie(%bighash);
11183: }
11184: return $okay;
1.31 www 11185: }
11186:
1.210 www 11187: # --------------------------------------------------------------- Clean-up symb
11188:
11189: sub symbclean {
11190: my $symb=shift;
1.568 albertel 11191: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11192: # remove version from map
11193: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11194:
1.210 www 11195: # remove version from URL
11196: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11197:
1.507 www 11198: # remove wrapper
11199:
1.510 www 11200: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11201: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11202: return $symb;
1.409 www 11203: }
11204:
11205: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11206:
11207: sub encode_symb {
11208: my ($map,$resid,$url)=@_;
11209: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11210: }
1.409 www 11211:
11212: sub decode_symb {
1.568 albertel 11213: my $symb=shift;
11214: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11215: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11216: return (&fixversion($map),$resid,&fixversion($url));
11217: }
11218:
11219: sub fixversion {
11220: my $fn=shift;
1.609 banghart 11221: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11222: my %bighash;
11223: my $uri=&clutter($fn);
1.620 albertel 11224: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11225: # is this cached?
1.599 albertel 11226: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11227: if (defined($cached)) { return $result; }
11228: # unfortunately not cached, or expired
1.620 albertel 11229: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11230: &GDBM_READER(),0640)) {
11231: if ($bighash{'version_'.$uri}) {
11232: my $version=$bighash{'version_'.$uri};
1.444 www 11233: unless (($version eq 'mostrecent') ||
11234: ($version==&getversion($uri))) {
1.440 www 11235: $uri=~s/\.(\w+)$/\.$version\.$1/;
11236: }
11237: }
11238: untie %bighash;
1.413 www 11239: }
1.599 albertel 11240: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11241: }
11242:
11243: sub deversion {
11244: my $url=shift;
11245: $url=~s/\.\d+\.(\w+)$/\.$1/;
11246: return $url;
1.210 www 11247: }
11248:
1.31 www 11249: # ------------------------------------------------------ Return symb list entry
11250:
11251: sub symbread {
1.1282 raeburn 11252: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11253: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11254: if (defined($env{$cache_str})) {
11255: if ($ignorecachednull) {
11256: return $env{$cache_str} unless ($env{$cache_str} eq '');
11257: } else {
11258: return $env{$cache_str};
11259: }
11260: }
1.242 www 11261: # no filename provided? try from environment
1.1265 raeburn 11262: unless ($thisfn) {
1.620 albertel 11263: if ($env{'request.symb'}) {
11264: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11265: }
1.620 albertel 11266: $thisfn=$env{'request.filename'};
1.44 www 11267: }
1.569 albertel 11268: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11269: # is that filename actually a symb? Verify, clean, and return
11270: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11271: if (&symbverify($thisfn,$1)) {
1.620 albertel 11272: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11273: }
1.242 www 11274: }
1.44 www 11275: $thisfn=declutter($thisfn);
1.31 www 11276: my %hash;
1.37 www 11277: my %bighash;
11278: my $syval='';
1.620 albertel 11279: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11280: my $targetfn = $thisfn;
1.609 banghart 11281: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11282: $targetfn = 'adm/wrapper/'.$thisfn;
11283: }
1.687 albertel 11284: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11285: $targetfn=$1;
11286: }
1.620 albertel 11287: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11288: &GDBM_READER(),0640)) {
1.481 raeburn 11289: $syval=$hash{$targetfn};
1.37 www 11290: untie(%hash);
11291: }
11292: # ---------------------------------------------------------- There was an entry
11293: if ($syval) {
1.601 albertel 11294: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11295: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11296: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11297: #return $env{$cache_str}='';
1.601 albertel 11298: #}
11299: #$syval.=$1;
11300: #}
1.37 www 11301: } else {
11302: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11303: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11304: &GDBM_READER(),0640)) {
1.37 www 11305: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11306: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11307: unless ($ids) {
11308: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11309: }
11310: unless ($ids) {
11311: # alias?
11312: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11313: }
1.37 www 11314: if ($ids) {
11315: # ------------------------------------------------------------------- Has ID(s)
11316: my @possibilities=split(/\,/,$ids);
1.39 www 11317: if ($#possibilities==0) {
11318: # ----------------------------------------------- There is only one possibility
1.37 www 11319: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11320: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11321: $resid,$thisfn);
1.1282 raeburn 11322: if (ref($possibles) eq 'HASH') {
11323: $possibles->{$syval} = 1;
11324: }
11325: if ($checkforblock) {
11326: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11327: if (@blockers) {
11328: $syval = '';
11329: return;
11330: }
11331: }
11332: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11333: # ------------------------------------------ There is more than one possibility
11334: my $realpossible=0;
1.800 albertel 11335: foreach my $id (@possibilities) {
11336: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11337: my $canaccess;
11338: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11339: $canaccess = 1;
11340: } else {
11341: $canaccess = &allowed('bre',$file);
11342: }
11343: if ($canaccess) {
11344: my ($mapid,$resid)=split(/\./,$id);
11345: if ($bighash{'map_type_'.$mapid} ne 'page') {
11346: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11347: $resid,$thisfn);
11348: if (ref($possibles) eq 'HASH') {
11349: $possibles->{$syval} = 1;
11350: }
11351: if ($checkforblock) {
11352: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11353: unless (@blockers > 0) {
11354: $syval = $poss_syval;
11355: $realpossible++;
11356: }
11357: } else {
11358: $syval = $poss_syval;
11359: $realpossible++;
11360: }
11361: }
1.39 www 11362: }
1.191 harris41 11363: }
1.39 www 11364: if ($realpossible!=1) { $syval=''; }
1.249 www 11365: } else {
11366: $syval='';
1.37 www 11367: }
11368: }
1.1282 raeburn 11369: untie(%bighash);
1.481 raeburn 11370: }
1.31 www 11371: }
1.62 www 11372: if ($syval) {
1.620 albertel 11373: return $env{$cache_str}=$syval;
1.62 www 11374: }
1.31 www 11375: }
1.949 raeburn 11376: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11377: return $env{$cache_str}='';
1.31 www 11378: }
11379:
11380: # ---------------------------------------------------------- Return random seed
11381:
1.32 www 11382: sub numval {
11383: my $txt=shift;
11384: $txt=~tr/A-J/0-9/;
11385: $txt=~tr/a-j/0-9/;
11386: $txt=~tr/K-T/0-9/;
11387: $txt=~tr/k-t/0-9/;
11388: $txt=~tr/U-Z/0-5/;
11389: $txt=~tr/u-z/0-5/;
11390: $txt=~s/\D//g;
1.564 albertel 11391: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11392: return int($txt);
1.368 albertel 11393: }
11394:
1.484 albertel 11395: sub numval2 {
11396: my $txt=shift;
11397: $txt=~tr/A-J/0-9/;
11398: $txt=~tr/a-j/0-9/;
11399: $txt=~tr/K-T/0-9/;
11400: $txt=~tr/k-t/0-9/;
11401: $txt=~tr/U-Z/0-5/;
11402: $txt=~tr/u-z/0-5/;
11403: $txt=~s/\D//g;
11404: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11405: my $total;
11406: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11407: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11408: return int($total);
11409: }
11410:
1.575 albertel 11411: sub numval3 {
11412: use integer;
11413: my $txt=shift;
11414: $txt=~tr/A-J/0-9/;
11415: $txt=~tr/a-j/0-9/;
11416: $txt=~tr/K-T/0-9/;
11417: $txt=~tr/k-t/0-9/;
11418: $txt=~tr/U-Z/0-5/;
11419: $txt=~tr/u-z/0-5/;
11420: $txt=~s/\D//g;
11421: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11422: my $total;
11423: foreach my $val (@txts) { $total+=$val; }
11424: if ($_64bit) { $total=(($total<<32)>>32); }
11425: return $total;
11426: }
11427:
1.675 albertel 11428: sub digest {
11429: my ($data)=@_;
11430: my $digest=&Digest::MD5::md5($data);
11431: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11432: my ($e,$f);
11433: {
11434: use integer;
11435: $e=($a+$b);
11436: $f=($c+$d);
11437: if ($_64bit) {
11438: $e=(($e<<32)>>32);
11439: $f=(($f<<32)>>32);
11440: }
11441: }
11442: if (wantarray) {
11443: return ($e,$f);
11444: } else {
11445: my $g;
11446: {
11447: use integer;
11448: $g=($e+$f);
11449: if ($_64bit) {
11450: $g=(($g<<32)>>32);
11451: }
11452: }
11453: return $g;
11454: }
11455: }
11456:
1.368 albertel 11457: sub latest_rnd_algorithm_id {
1.675 albertel 11458: return '64bit5';
1.366 albertel 11459: }
1.32 www 11460:
1.503 albertel 11461: sub get_rand_alg {
11462: my ($courseid)=@_;
1.790 albertel 11463: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11464: if ($courseid) {
1.620 albertel 11465: return $env{"course.$courseid.rndseed"};
1.503 albertel 11466: }
11467: return &latest_rnd_algorithm_id();
11468: }
11469:
1.562 albertel 11470: sub validCODE {
11471: my ($CODE)=@_;
11472: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11473: return 0;
11474: }
11475:
1.491 albertel 11476: sub getCODE {
1.620 albertel 11477: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11478: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11479: defined($Apache::lonhomework::parsing_a_task) ) &&
11480: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11481: return $Apache::lonhomework::history{'resource.CODE'};
11482: }
11483: return undef;
11484: }
1.1133 foxr 11485: #
11486: # Determines the random seed for a specific context:
11487: #
11488: # parameters:
11489: # symb - in course context the symb for the seed.
11490: # course_id - The course id of the form domain_coursenum.
11491: # domain - Domain for the user.
11492: # course - Course for the user.
11493: # cenv - environment of the course.
11494: #
11495: # NOTE:
11496: # All parameters are picked out of the environment if missing
11497: # or not defined.
11498: # If a symb cannot be determined the current time is used instead.
11499: #
11500: # For a given well defined symb, courside, domain, username,
11501: # and course environment, the seed is reproducible.
11502: #
1.31 www 11503: sub rndseed {
1.1133 foxr 11504: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11505: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11506: if (!defined($symb)) {
1.366 albertel 11507: unless ($symb=$wsymb) { return time; }
11508: }
1.1146 foxr 11509: if (!defined $courseid) {
11510: $courseid=$wcourseid;
11511: }
11512: if (!defined $domain) { $domain=$wdomain; }
11513: if (!defined $username) { $username=$wusername }
1.1133 foxr 11514:
11515: my $which;
11516: if (defined($cenv->{'rndseed'})) {
11517: $which = $cenv->{'rndseed'};
11518: } else {
11519: $which =&get_rand_alg($courseid);
11520: }
1.491 albertel 11521: if (defined(&getCODE())) {
1.1133 foxr 11522:
1.675 albertel 11523: if ($which eq '64bit5') {
11524: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11525: } elsif ($which eq '64bit4') {
1.575 albertel 11526: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11527: } else {
11528: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11529: }
1.675 albertel 11530: } elsif ($which eq '64bit5') {
11531: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11532: } elsif ($which eq '64bit4') {
11533: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11534: } elsif ($which eq '64bit3') {
11535: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11536: } elsif ($which eq '64bit2') {
11537: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11538: } elsif ($which eq '64bit') {
11539: return &rndseed_64bit($symb,$courseid,$domain,$username);
11540: }
11541: return &rndseed_32bit($symb,$courseid,$domain,$username);
11542: }
11543:
11544: sub rndseed_32bit {
11545: my ($symb,$courseid,$domain,$username)=@_;
11546: {
11547: use integer;
11548: my $symbchck=unpack("%32C*",$symb) << 27;
11549: my $symbseed=numval($symb) << 22;
11550: my $namechck=unpack("%32C*",$username) << 17;
11551: my $nameseed=numval($username) << 12;
11552: my $domainseed=unpack("%32C*",$domain) << 7;
11553: my $courseseed=unpack("%32C*",$courseid);
11554: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11555: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11556: #&logthis("rndseed :$num:$symb");
1.564 albertel 11557: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11558: return $num;
11559: }
11560: }
11561:
11562: sub rndseed_64bit {
11563: my ($symb,$courseid,$domain,$username)=@_;
11564: {
11565: use integer;
11566: my $symbchck=unpack("%32S*",$symb) << 21;
11567: my $symbseed=numval($symb) << 10;
11568: my $namechck=unpack("%32S*",$username);
11569:
11570: my $nameseed=numval($username) << 21;
11571: my $domainseed=unpack("%32S*",$domain) << 10;
11572: my $courseseed=unpack("%32S*",$courseid);
11573:
11574: my $num1=$symbchck+$symbseed+$namechck;
11575: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11576: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11577: #&logthis("rndseed :$num:$symb");
1.564 albertel 11578: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11579: return "$num1,$num2";
1.155 albertel 11580: }
1.366 albertel 11581: }
11582:
1.443 albertel 11583: sub rndseed_64bit2 {
11584: my ($symb,$courseid,$domain,$username)=@_;
11585: {
11586: use integer;
11587: # strings need to be an even # of cahracters long, it it is odd the
11588: # last characters gets thrown away
11589: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11590: my $symbseed=numval($symb) << 10;
11591: my $namechck=unpack("%32S*",$username.' ');
11592:
11593: my $nameseed=numval($username) << 21;
1.501 albertel 11594: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11595: my $courseseed=unpack("%32S*",$courseid.' ');
11596:
11597: my $num1=$symbchck+$symbseed+$namechck;
11598: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11599: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11600: #&logthis("rndseed :$num:$symb");
1.803 albertel 11601: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11602: return "$num1,$num2";
11603: }
11604: }
11605:
11606: sub rndseed_64bit3 {
11607: my ($symb,$courseid,$domain,$username)=@_;
11608: {
11609: use integer;
11610: # strings need to be an even # of cahracters long, it it is odd the
11611: # last characters gets thrown away
11612: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11613: my $symbseed=numval2($symb) << 10;
11614: my $namechck=unpack("%32S*",$username.' ');
11615:
11616: my $nameseed=numval2($username) << 21;
1.443 albertel 11617: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11618: my $courseseed=unpack("%32S*",$courseid.' ');
11619:
11620: my $num1=$symbchck+$symbseed+$namechck;
11621: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11622: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11623: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11624: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11625:
1.503 albertel 11626: return "$num1:$num2";
1.443 albertel 11627: }
11628: }
11629:
1.575 albertel 11630: sub rndseed_64bit4 {
11631: my ($symb,$courseid,$domain,$username)=@_;
11632: {
11633: use integer;
11634: # strings need to be an even # of cahracters long, it it is odd the
11635: # last characters gets thrown away
11636: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11637: my $symbseed=numval3($symb) << 10;
11638: my $namechck=unpack("%32S*",$username.' ');
11639:
11640: my $nameseed=numval3($username) << 21;
11641: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11642: my $courseseed=unpack("%32S*",$courseid.' ');
11643:
11644: my $num1=$symbchck+$symbseed+$namechck;
11645: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11646: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11647: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11648: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11649:
1.575 albertel 11650: return "$num1:$num2";
11651: }
11652: }
11653:
1.675 albertel 11654: sub rndseed_64bit5 {
11655: my ($symb,$courseid,$domain,$username)=@_;
11656: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11657: return "$num1:$num2";
11658: }
11659:
1.366 albertel 11660: sub rndseed_CODE_64bit {
11661: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11662: {
1.366 albertel 11663: use integer;
1.443 albertel 11664: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11665: my $symbseed=numval2($symb);
1.491 albertel 11666: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11667: my $CODEseed=numval(&getCODE());
1.443 albertel 11668: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11669: my $num1=$symbseed+$CODEchck;
11670: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11671: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11672: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11673: if ($_64bit) { $num1=(($num1<<32)>>32); }
11674: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11675: return "$num1:$num2";
1.366 albertel 11676: }
11677: }
11678:
1.575 albertel 11679: sub rndseed_CODE_64bit4 {
11680: my ($symb,$courseid,$domain,$username)=@_;
11681: {
11682: use integer;
11683: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11684: my $symbseed=numval3($symb);
11685: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11686: my $CODEseed=numval3(&getCODE());
11687: my $courseseed=unpack("%32S*",$courseid.' ');
11688: my $num1=$symbseed+$CODEchck;
11689: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11690: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11691: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11692: if ($_64bit) { $num1=(($num1<<32)>>32); }
11693: if ($_64bit) { $num2=(($num2<<32)>>32); }
11694: return "$num1:$num2";
11695: }
11696: }
11697:
1.675 albertel 11698: sub rndseed_CODE_64bit5 {
11699: my ($symb,$courseid,$domain,$username)=@_;
11700: my $code = &getCODE();
11701: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11702: return "$num1:$num2";
11703: }
11704:
1.366 albertel 11705: sub setup_random_from_rndseed {
11706: my ($rndseed)=@_;
1.503 albertel 11707: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11708: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11709: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11710: &Math::Random::random_set_seed_from_phrase($rndseed);
11711: } else {
11712: &Math::Random::random_set_seed($num1,$num2);
11713: }
1.366 albertel 11714: } else {
11715: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11716: }
1.36 albertel 11717: }
11718:
1.474 albertel 11719: sub latest_receipt_algorithm_id {
1.835 albertel 11720: return 'receipt3';
1.474 albertel 11721: }
11722:
1.480 www 11723: sub recunique {
11724: my $fucourseid=shift;
11725: my $unique;
1.835 albertel 11726: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11727: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11728: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11729: } else {
11730: $unique=$perlvar{'lonReceipt'};
11731: }
11732: return unpack("%32C*",$unique);
11733: }
11734:
11735: sub recprefix {
11736: my $fucourseid=shift;
11737: my $prefix;
1.835 albertel 11738: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11739: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11740: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11741: } else {
11742: $prefix=$perlvar{'lonHostID'};
11743: }
11744: return unpack("%32C*",$prefix);
11745: }
11746:
1.76 www 11747: sub ireceipt {
1.474 albertel 11748: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11749:
11750: my $return =&recprefix($fucourseid).'-';
11751:
11752: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11753: $env{'request.state'} eq 'construct') {
11754: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11755: return $return;
11756: }
11757:
1.76 www 11758: my $cuname=unpack("%32C*",$funame);
11759: my $cudom=unpack("%32C*",$fudom);
11760: my $cucourseid=unpack("%32C*",$fucourseid);
11761: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11762: my $cunique=&recunique($fucourseid);
1.474 albertel 11763: my $cpart=unpack("%32S*",$part);
1.835 albertel 11764: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11765:
1.790 albertel 11766: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11767:
11768: $return.= ($cunique%$cuname+
11769: $cunique%$cudom+
11770: $cusymb%$cuname+
11771: $cusymb%$cudom+
11772: $cucourseid%$cuname+
11773: $cucourseid%$cudom+
11774: $cpart%$cuname+
11775: $cpart%$cudom);
11776: } else {
11777: $return.= ($cunique%$cuname+
11778: $cunique%$cudom+
11779: $cusymb%$cuname+
11780: $cusymb%$cudom+
11781: $cucourseid%$cuname+
11782: $cucourseid%$cudom);
11783: }
11784: return $return;
1.76 www 11785: }
11786:
11787: sub receipt {
1.474 albertel 11788: my ($part)=@_;
1.790 albertel 11789: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11790: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11791: }
1.260 ng 11792:
1.790 albertel 11793: sub whichuser {
11794: my ($passedsymb)=@_;
11795: my ($symb,$courseid,$domain,$name,$publicuser);
11796: if (defined($env{'form.grade_symb'})) {
11797: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11798: my $allowed=&allowed('vgr',$tmp_courseid);
11799: if (!$allowed &&
11800: exists($env{'request.course.sec'}) &&
11801: $env{'request.course.sec'} !~ /^\s*$/) {
11802: $allowed=&allowed('vgr',$tmp_courseid.
11803: '/'.$env{'request.course.sec'});
11804: }
11805: if ($allowed) {
11806: ($symb)=&get_env_multiple('form.grade_symb');
11807: $courseid=$tmp_courseid;
11808: ($domain)=&get_env_multiple('form.grade_domain');
11809: ($name)=&get_env_multiple('form.grade_username');
11810: return ($symb,$courseid,$domain,$name,$publicuser);
11811: }
11812: }
11813: if (!$passedsymb) {
11814: $symb=&symbread();
11815: } else {
11816: $symb=$passedsymb;
11817: }
11818: $courseid=$env{'request.course.id'};
11819: $domain=$env{'user.domain'};
11820: $name=$env{'user.name'};
11821: if ($name eq 'public' && $domain eq 'public') {
11822: if (!defined($env{'form.username'})) {
11823: $env{'form.username'}.=time.rand(10000000);
11824: }
11825: $name.=$env{'form.username'};
11826: }
11827: return ($symb,$courseid,$domain,$name,$publicuser);
11828:
11829: }
11830:
1.36 albertel 11831: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11832: # returns either the contents of the file or
11833: # -1 if the file doesn't exist
1.481 raeburn 11834: #
11835: # if the target is a file that was uploaded via DOCS,
11836: # a check will be made to see if a current copy exists on the local server,
11837: # if it does this will be served, otherwise a copy will be retrieved from
11838: # the home server for the course and stored in /home/httpd/html/userfiles on
11839: # the local server.
1.472 albertel 11840:
1.36 albertel 11841: sub getfile {
1.538 albertel 11842: my ($file) = @_;
1.609 banghart 11843: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11844: &repcopy($file);
11845: return &readfile($file);
11846: }
11847:
11848: sub repcopy_userfile {
11849: my ($file)=@_;
1.1142 raeburn 11850: my $londocroot = $perlvar{'lonDocRoot'};
11851: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11852: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11853: my ($cdom,$cnum,$filename) =
1.811 albertel 11854: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11855: my $uri="/uploaded/$cdom/$cnum/$filename";
11856: if (-e "$file") {
1.828 www 11857: # we already have a local copy, check it out
1.538 albertel 11858: my @fileinfo = stat($file);
1.828 www 11859: my $rtncode;
11860: my $info;
1.538 albertel 11861: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11862: if ($lwpresp ne 'ok') {
1.828 www 11863: # there is no such file anymore, even though we had a local copy
1.482 albertel 11864: if ($rtncode eq '404') {
1.538 albertel 11865: unlink($file);
1.482 albertel 11866: }
11867: return -1;
11868: }
11869: if ($info < $fileinfo[9]) {
1.828 www 11870: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11871: return 'ok';
1.828 www 11872: } else {
11873: # the file is outdated, get rid of it
11874: unlink($file);
1.482 albertel 11875: }
1.828 www 11876: }
11877: # one way or the other, at this point, we don't have the file
11878: # construct the correct path for the file
11879: my @parts = ($cdom,$cnum);
11880: if ($filename =~ m|^(.+)/[^/]+$|) {
11881: push @parts, split(/\//,$1);
11882: }
11883: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11884: foreach my $part (@parts) {
11885: $path .= '/'.$part;
11886: if (!-e $path) {
11887: mkdir($path,0770);
1.482 albertel 11888: }
11889: }
1.828 www 11890: # now the path exists for sure
11891: # get a user agent
11892: my $ua=new LWP::UserAgent;
11893: my $transferfile=$file.'.in.transfer';
11894: # FIXME: this should flock
11895: if (-e $transferfile) { return 'ok'; }
11896: my $request;
11897: $uri=~s/^\///;
1.980 raeburn 11898: my $homeserver = &homeserver($cnum,$cdom);
11899: my $protocol = $protocol{$homeserver};
11900: $protocol = 'http' if ($protocol ne 'https');
11901: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11902: my $response=$ua->request($request,$transferfile);
11903: # did it work?
11904: if ($response->is_error()) {
11905: unlink($transferfile);
11906: &logthis("Userfile repcopy failed for $uri");
11907: return -1;
11908: }
11909: # worked, rename the transfer file
11910: rename($transferfile,$file);
1.607 raeburn 11911: return 'ok';
1.481 raeburn 11912: }
11913:
1.517 albertel 11914: sub tokenwrapper {
11915: my $uri=shift;
1.980 raeburn 11916: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11917: $uri=~s|^/||;
1.620 albertel 11918: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11919: my $token=$1;
1.552 albertel 11920: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11921: if ($udom && $uname && $file) {
11922: $file=~s|(\?\.*)*$||;
1.949 raeburn 11923: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11924: my $homeserver = &homeserver($uname,$udom);
11925: my $protocol = $protocol{$homeserver};
11926: $protocol = 'http' if ($protocol ne 'https');
11927: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11928: (($uri=~/\?/)?'&':'?').'token='.$token.
11929: '&tokenissued='.$perlvar{'lonHostID'};
11930: } else {
11931: return '/adm/notfound.html';
11932: }
11933: }
11934:
1.828 www 11935: # call with reqtype HEAD: get last modification time
11936: # call with reqtype GET: get the file contents
11937: # Do not call this with reqtype GET for large files! It loads everything into memory
11938: #
1.481 raeburn 11939: sub getuploaded {
11940: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11941: $uri=~s/^\///;
1.980 raeburn 11942: my $homeserver = &homeserver($cnum,$cdom);
11943: my $protocol = $protocol{$homeserver};
11944: $protocol = 'http' if ($protocol ne 'https');
11945: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11946: my $ua=new LWP::UserAgent;
11947: my $request=new HTTP::Request($reqtype,$uri);
11948: my $response=$ua->request($request);
11949: $$rtncode = $response->code;
1.482 albertel 11950: if (! $response->is_success()) {
11951: return 'failed';
11952: }
11953: if ($reqtype eq 'HEAD') {
1.486 www 11954: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11955: } elsif ($reqtype eq 'GET') {
11956: $$info = $response->content;
1.472 albertel 11957: }
1.482 albertel 11958: return 'ok';
1.36 albertel 11959: }
11960:
1.481 raeburn 11961: sub readfile {
11962: my $file = shift;
11963: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11964: my $fh;
11965: open($fh,"<$file");
11966: my $a='';
1.800 albertel 11967: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11968: return $a;
11969: }
11970:
1.36 albertel 11971: sub filelocation {
1.590 banghart 11972: my ($dir,$file) = @_;
11973: my $location;
11974: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11975:
11976: if ($file =~ m-^/adm/-) {
11977: $file=~s-^/adm/wrapper/-/-;
11978: $file=~s-^/adm/coursedocs/showdoc/-/-;
11979: }
1.882 albertel 11980:
1.1139 www 11981: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11982: $location = $file;
1.609 banghart 11983: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11984: my ($udom,$uname,$filename)=
1.811 albertel 11985: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11986: my $home=&homeserver($uname,$udom);
11987: my $is_me=0;
11988: my @ids=¤t_machine_ids();
11989: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11990: if ($is_me) {
1.1117 foxr 11991: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11992: } else {
11993: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11994: $udom.'/'.$uname.'/'.$filename;
11995: }
1.882 albertel 11996: } elsif ($file =~ m-^/adm/-) {
11997: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11998: } else {
11999: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12000: $file=~s:^/(res|priv)/:/:;
12001: my $space=$1;
1.590 banghart 12002: if ( !( $file =~ m:^/:) ) {
12003: $location = $dir. '/'.$file;
12004: } else {
1.1142 raeburn 12005: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12006: }
1.59 albertel 12007: }
1.590 banghart 12008: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12009: while ($location=~m{/\.\./}) {
12010: if ($location =~ m{/[^/]+/\.\./}) {
12011: $location=~ s{/[^/]+/\.\./}{/}g;
12012: } else {
12013: $location=~ s{/\.\./}{/}g;
12014: }
12015: } #remove dir/..
1.590 banghart 12016: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12017: return $location;
1.46 www 12018: }
1.36 albertel 12019:
1.46 www 12020: sub hreflocation {
12021: my ($dir,$file)=@_;
1.980 raeburn 12022: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12023: $file=filelocation($dir,$file);
1.700 albertel 12024: } elsif ($file=~m-^/adm/-) {
12025: $file=~s-^/adm/wrapper/-/-;
12026: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12027: }
12028: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12029: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12030: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12031: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12032: {/uploaded/$1/$2/}x;
1.46 www 12033: }
1.913 albertel 12034: if ($file=~ m{^/userfiles/}) {
12035: $file =~ s{^/userfiles/}{/uploaded/};
12036: }
1.462 albertel 12037: return $file;
1.465 albertel 12038: }
12039:
1.1139 www 12040:
12041:
12042:
12043:
1.465 albertel 12044: sub current_machine_domains {
1.853 albertel 12045: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12046: }
12047:
12048: sub machine_domains {
12049: my ($hostname) = @_;
1.465 albertel 12050: my @domains;
1.838 albertel 12051: my %hostname = &all_hostnames();
1.465 albertel 12052: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12053: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12054: if ($hostname eq $name) {
1.844 albertel 12055: push(@domains,&host_domain($id));
1.465 albertel 12056: }
12057: }
12058: return @domains;
12059: }
12060:
12061: sub current_machine_ids {
1.853 albertel 12062: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12063: }
12064:
12065: sub machine_ids {
12066: my ($hostname) = @_;
12067: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12068: my @ids;
1.888 albertel 12069: my %name_to_host = &all_names();
1.889 albertel 12070: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12071: return @{ $name_to_host{$hostname} };
12072: }
12073: return;
1.31 www 12074: }
12075:
1.824 raeburn 12076: sub additional_machine_domains {
12077: my @domains;
12078: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12079: while( my $line = <$fh>) {
12080: $line =~ s/\s//g;
12081: push(@domains,$line);
12082: }
12083: return @domains;
12084: }
12085:
12086: sub default_login_domain {
12087: my $domain = $perlvar{'lonDefDomain'};
12088: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12089: foreach my $posdom (¤t_machine_domains(),
12090: &additional_machine_domains()) {
12091: if (lc($posdom) eq lc($testdomain)) {
12092: $domain=$posdom;
12093: last;
12094: }
12095: }
12096: return $domain;
12097: }
12098:
1.31 www 12099: # ------------------------------------------------------------- Declutters URLs
12100:
12101: sub declutter {
12102: my $thisfn=shift;
1.569 albertel 12103: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12104: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12105: $thisfn=~s{^/home/httpd/html}{};
12106: }
1.31 www 12107: $thisfn=~s/^\///;
1.697 albertel 12108: $thisfn=~s|^adm/wrapper/||;
12109: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12110: $thisfn=~s/^res\///;
1.1172 bisitz 12111: $thisfn=~s/^priv\///;
1.1032 raeburn 12112: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12113: $thisfn=~s/\?.+$//;
12114: }
1.268 www 12115: return $thisfn;
12116: }
12117:
12118: # ------------------------------------------------------------- Clutter up URLs
12119:
12120: sub clutter {
12121: my $thisfn='/'.&declutter(shift);
1.887 albertel 12122: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12123: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12124: $thisfn='/res'.$thisfn;
12125: }
1.1031 raeburn 12126: if ($thisfn !~m|^/adm|) {
12127: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12128: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12129: } else {
12130: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12131: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12132: if ($embstyle eq 'ssi'
12133: || ($embstyle eq 'hdn')
12134: || ($embstyle eq 'rat')
12135: || ($embstyle eq 'prv')
12136: || ($embstyle eq 'ign')) {
12137: #do nothing with these
12138: } elsif (($embstyle eq 'img')
1.695 albertel 12139: || ($embstyle eq 'emb')
12140: || ($embstyle eq 'wrp')) {
12141: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12142: } elsif ($embstyle eq 'unk'
12143: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12144: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12145: } else {
1.718 www 12146: # &logthis("Got a blank emb style");
1.695 albertel 12147: }
1.694 albertel 12148: }
12149: }
1.31 www 12150: return $thisfn;
1.12 www 12151: }
12152:
1.787 albertel 12153: sub clutter_with_no_wrapper {
12154: my $uri = &clutter(shift);
12155: if ($uri =~ m-^/adm/-) {
12156: $uri =~ s-^/adm/wrapper/-/-;
12157: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12158: }
12159: return $uri;
12160: }
12161:
1.557 albertel 12162: sub freeze_escape {
12163: my ($value)=@_;
12164: if (ref($value)) {
12165: $value=&nfreeze($value);
12166: return '__FROZEN__'.&escape($value);
12167: }
12168: return &escape($value);
12169: }
12170:
1.11 www 12171:
1.557 albertel 12172: sub thaw_unescape {
12173: my ($value)=@_;
12174: if ($value =~ /^__FROZEN__/) {
12175: substr($value,0,10,undef);
12176: $value=&unescape($value);
12177: return &thaw($value);
12178: }
12179: return &unescape($value);
12180: }
12181:
1.436 albertel 12182: sub correct_line_ends {
12183: my ($result)=@_;
12184: $$result =~s/\r\n/\n/mg;
12185: $$result =~s/\r/\n/mg;
1.415 albertel 12186: }
1.1 albertel 12187: # ================================================================ Main Program
12188:
1.184 www 12189: sub goodbye {
1.204 albertel 12190: &logthis("Starting Shut down");
1.443 albertel 12191: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12192: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12193: #converted
1.599 albertel 12194: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12195: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12196: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12197: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12198: #1.1 only
1.870 albertel 12199: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12200: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12201: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12202: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12203: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12204: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12205: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12206: &flushcourselogs();
12207: &logthis("Shutting down");
12208: }
12209:
1.852 albertel 12210: sub get_dns {
1.1210 raeburn 12211: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12212: if (!$ignore_cache) {
12213: my ($content,$cached)=
12214: &Apache::lonnet::is_cached_new('dns',$url);
12215: if ($cached) {
1.1210 raeburn 12216: &$func($content,$hashref);
1.869 albertel 12217: return;
12218: }
12219: }
12220:
12221: my %alldns;
1.852 albertel 12222: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12223: foreach my $dns (<$config>) {
12224: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12225: my $line = $1;
12226: my ($host,$protocol) = split(/:/,$line);
12227: if ($protocol ne 'https') {
12228: $protocol = 'http';
12229: }
12230: $alldns{$host} = $protocol;
1.869 albertel 12231: }
12232: while (%alldns) {
1.1263 raeburn 12233: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12234: my $ua=new LWP::UserAgent;
1.1134 raeburn 12235: $ua->timeout(30);
1.979 raeburn 12236: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12237: my $response=$ua->request($request);
1.979 raeburn 12238: delete($alldns{$dns});
1.852 albertel 12239: next if ($response->is_error());
12240: my @content = split("\n",$response->content);
1.1210 raeburn 12241: unless ($nocache) {
1.1219 raeburn 12242: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12243: }
12244: &$func(\@content,$hashref);
1.869 albertel 12245: return;
1.852 albertel 12246: }
12247: close($config);
1.871 albertel 12248: my $which = (split('/',$url))[3];
12249: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12250: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12251: my @content = <$config>;
1.1210 raeburn 12252: &$func(\@content,$hashref);
12253: return;
12254: }
12255:
12256: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12257: sub parse_dns_checksums_tab {
1.1210 raeburn 12258: my ($lines,$hashref) = @_;
1.1264 raeburn 12259: my $lonhost = $perlvar{'lonHostID'};
12260: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12261: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12262: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12263: my $webconfdir = '/etc/httpd/conf';
12264: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12265: $webconfdir = '/etc/apache2';
12266: } elsif ($distro =~ /^sles(\d+)$/) {
12267: if ($1 >= 10) {
12268: $webconfdir = '/etc/apache2';
12269: }
12270: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12271: if ($1 >= 10.0) {
12272: $webconfdir = '/etc/apache2';
12273: }
12274: }
1.1210 raeburn 12275: my ($release,$timestamp) = split(/\-/,$loncaparev);
12276: my (%chksum,%revnum);
12277: if (ref($lines) eq 'ARRAY') {
12278: chomp(@{$lines});
1.1238 raeburn 12279: my $version = shift(@{$lines});
12280: if ($version eq $release) {
1.1210 raeburn 12281: foreach my $line (@{$lines}) {
1.1238 raeburn 12282: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12283: if ($file =~ m{^/etc/httpd/conf}) {
12284: if ($webconfdir eq '/etc/apache2') {
12285: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12286: }
12287: }
1.1238 raeburn 12288: $chksum{$file} = $shasum;
12289: $revnum{$file} = $version;
1.1210 raeburn 12290: }
12291: if (ref($hashref) eq 'HASH') {
12292: %{$hashref} = (
12293: sums => \%chksum,
12294: versions => \%revnum,
12295: );
12296: }
12297: }
12298: }
1.869 albertel 12299: return;
1.852 albertel 12300: }
1.1210 raeburn 12301:
12302: sub fetch_dns_checksums {
1.1238 raeburn 12303: my %checksums;
12304: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12305: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12306: my ($release,$timestamp) = split(/\-/,$loncaparev);
12307: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12308: \%checksums);
1.1210 raeburn 12309: return \%checksums;
12310: }
12311:
1.327 albertel 12312: # ------------------------------------------------------------ Read domain file
12313: {
1.852 albertel 12314: my $loaded;
1.846 albertel 12315: my %domain;
12316:
1.852 albertel 12317: sub parse_domain_tab {
12318: my ($lines) = @_;
12319: foreach my $line (@$lines) {
12320: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12321:
1.846 albertel 12322: chomp($line);
1.852 albertel 12323: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12324: my %this_domain;
12325: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12326: 'lang_def', 'city', 'longi', 'lati',
12327: 'primary') {
12328: $this_domain{$field} = shift(@elements);
12329: }
12330: $domain{$name} = \%this_domain;
1.852 albertel 12331: }
12332: }
1.864 albertel 12333:
12334: sub reset_domain_info {
12335: undef($loaded);
12336: undef(%domain);
12337: }
12338:
1.852 albertel 12339: sub load_domain_tab {
1.869 albertel 12340: my ($ignore_cache) = @_;
12341: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12342: my $fh;
12343: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12344: my @lines = <$fh>;
12345: &parse_domain_tab(\@lines);
1.448 albertel 12346: }
1.852 albertel 12347: close($fh);
12348: $loaded = 1;
1.327 albertel 12349: }
1.846 albertel 12350:
12351: sub domain {
1.852 albertel 12352: &load_domain_tab() if (!$loaded);
12353:
1.846 albertel 12354: my ($name,$what) = @_;
12355: return if ( !exists($domain{$name}) );
12356:
12357: if (!$what) {
12358: return $domain{$name}{'description'};
12359: }
12360: return $domain{$name}{$what};
12361: }
1.974 raeburn 12362:
12363: sub domain_info {
12364: &load_domain_tab() if (!$loaded);
12365: return %domain;
12366: }
12367:
1.327 albertel 12368: }
12369:
12370:
1.1 albertel 12371: # ------------------------------------------------------------- Read hosts file
12372: {
1.838 albertel 12373: my %hostname;
1.844 albertel 12374: my %hostdom;
1.845 albertel 12375: my %libserv;
1.852 albertel 12376: my $loaded;
1.888 albertel 12377: my %name_to_host;
1.1074 raeburn 12378: my %internetdom;
1.1107 raeburn 12379: my %LC_dns_serv;
1.852 albertel 12380:
12381: sub parse_hosts_tab {
12382: my ($file) = @_;
12383: foreach my $configline (@$file) {
12384: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12385: chomp($configline);
12386: if ($configline =~ /^\^/) {
12387: if ($configline =~ /^\^([\w.\-]+)/) {
12388: $LC_dns_serv{$1} = 1;
12389: }
12390: next;
12391: }
1.1074 raeburn 12392: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12393: $name=~s/\s//g;
12394: if ($id && $domain && $role && $name) {
12395: $hostname{$id}=$name;
1.888 albertel 12396: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12397: $hostdom{$id}=$domain;
12398: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12399: if (defined($protocol)) {
12400: if ($protocol eq 'https') {
12401: $protocol{$id} = $protocol;
12402: } else {
12403: $protocol{$id} = 'http';
12404: }
1.968 raeburn 12405: } else {
1.969 raeburn 12406: $protocol{$id} = 'http';
1.968 raeburn 12407: }
1.1074 raeburn 12408: if (defined($intdom)) {
12409: $internetdom{$id} = $intdom;
12410: }
1.852 albertel 12411: }
12412: }
12413: }
1.864 albertel 12414:
12415: sub reset_hosts_info {
1.897 albertel 12416: &purge_remembered();
1.864 albertel 12417: &reset_domain_info();
12418: &reset_hosts_ip_info();
1.892 albertel 12419: undef(%name_to_host);
1.864 albertel 12420: undef(%hostname);
12421: undef(%hostdom);
12422: undef(%libserv);
12423: undef($loaded);
12424: }
1.1 albertel 12425:
1.852 albertel 12426: sub load_hosts_tab {
1.869 albertel 12427: my ($ignore_cache) = @_;
12428: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12429: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12430: my @config = <$config>;
12431: &parse_hosts_tab(\@config);
12432: close($config);
12433: $loaded=1;
1.1 albertel 12434: }
1.852 albertel 12435:
1.838 albertel 12436: sub hostname {
1.852 albertel 12437: &load_hosts_tab() if (!$loaded);
12438:
1.838 albertel 12439: my ($lonid) = @_;
12440: return $hostname{$lonid};
12441: }
1.845 albertel 12442:
1.838 albertel 12443: sub all_hostnames {
1.852 albertel 12444: &load_hosts_tab() if (!$loaded);
12445:
1.838 albertel 12446: return %hostname;
12447: }
1.845 albertel 12448:
1.888 albertel 12449: sub all_names {
12450: &load_hosts_tab() if (!$loaded);
12451:
12452: return %name_to_host;
12453: }
12454:
1.974 raeburn 12455: sub all_host_domain {
12456: &load_hosts_tab() if (!$loaded);
12457: return %hostdom;
12458: }
12459:
1.845 albertel 12460: sub is_library {
1.852 albertel 12461: &load_hosts_tab() if (!$loaded);
12462:
1.845 albertel 12463: return exists($libserv{$_[0]});
12464: }
12465:
12466: sub all_library {
1.852 albertel 12467: &load_hosts_tab() if (!$loaded);
12468:
1.845 albertel 12469: return %libserv;
12470: }
12471:
1.1062 droeschl 12472: sub unique_library {
12473: #2x reverse removes all hostnames that appear more than once
12474: my %unique = reverse &all_library();
12475: return reverse %unique;
12476: }
12477:
1.841 albertel 12478: sub get_servers {
1.852 albertel 12479: &load_hosts_tab() if (!$loaded);
12480:
1.841 albertel 12481: my ($domain,$type) = @_;
12482: my %possible_hosts = ($type eq 'library') ? %libserv
12483: : %hostname;
12484: my %result;
1.842 albertel 12485: if (ref($domain) eq 'ARRAY') {
12486: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12487: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12488: $result{$host} = $hostname;
12489: }
12490: }
12491: } else {
12492: while ( my ($host,$hostname) = each(%possible_hosts)) {
12493: if ($hostdom{$host} eq $domain) {
12494: $result{$host} = $hostname;
12495: }
1.841 albertel 12496: }
12497: }
12498: return %result;
12499: }
1.845 albertel 12500:
1.1062 droeschl 12501: sub get_unique_servers {
12502: my %unique = reverse &get_servers(@_);
12503: return reverse %unique;
12504: }
12505:
1.844 albertel 12506: sub host_domain {
1.852 albertel 12507: &load_hosts_tab() if (!$loaded);
12508:
1.844 albertel 12509: my ($lonid) = @_;
12510: return $hostdom{$lonid};
12511: }
12512:
1.841 albertel 12513: sub all_domains {
1.852 albertel 12514: &load_hosts_tab() if (!$loaded);
12515:
1.841 albertel 12516: my %seen;
12517: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12518: return @uniq;
12519: }
1.1074 raeburn 12520:
12521: sub internet_dom {
12522: &load_hosts_tab() if (!$loaded);
12523:
12524: my ($lonid) = @_;
12525: return $internetdom{$lonid};
12526: }
1.1107 raeburn 12527:
12528: sub is_LC_dns {
12529: &load_hosts_tab() if (!$loaded);
12530:
12531: my ($hostname) = @_;
12532: return exists($LC_dns_serv{$hostname});
12533: }
12534:
1.1 albertel 12535: }
12536:
1.847 albertel 12537: {
12538: my %iphost;
1.856 albertel 12539: my %name_to_ip;
12540: my %lonid_to_ip;
1.869 albertel 12541:
1.847 albertel 12542: sub get_hosts_from_ip {
12543: my ($ip) = @_;
12544: my %iphosts = &get_iphost();
12545: if (ref($iphosts{$ip})) {
12546: return @{$iphosts{$ip}};
12547: }
12548: return;
1.839 albertel 12549: }
1.864 albertel 12550:
12551: sub reset_hosts_ip_info {
12552: undef(%iphost);
12553: undef(%name_to_ip);
12554: undef(%lonid_to_ip);
12555: }
1.856 albertel 12556:
12557: sub get_host_ip {
12558: my ($lonid) = @_;
12559: if (exists($lonid_to_ip{$lonid})) {
12560: return $lonid_to_ip{$lonid};
12561: }
12562: my $name=&hostname($lonid);
12563: my $ip = gethostbyname($name);
12564: return if (!$ip || length($ip) ne 4);
12565: $ip=inet_ntoa($ip);
12566: $name_to_ip{$name} = $ip;
12567: $lonid_to_ip{$lonid} = $ip;
12568: return $ip;
12569: }
1.847 albertel 12570:
12571: sub get_iphost {
1.869 albertel 12572: my ($ignore_cache) = @_;
1.894 albertel 12573:
1.869 albertel 12574: if (!$ignore_cache) {
12575: if (%iphost) {
12576: return %iphost;
12577: }
12578: my ($ip_info,$cached)=
12579: &Apache::lonnet::is_cached_new('iphost','iphost');
12580: if ($cached) {
12581: %iphost = %{$ip_info->[0]};
12582: %name_to_ip = %{$ip_info->[1]};
12583: %lonid_to_ip = %{$ip_info->[2]};
12584: return %iphost;
12585: }
12586: }
1.894 albertel 12587:
12588: # get yesterday's info for fallback
12589: my %old_name_to_ip;
12590: my ($ip_info,$cached)=
12591: &Apache::lonnet::is_cached_new('iphost','iphost');
12592: if ($cached) {
12593: %old_name_to_ip = %{$ip_info->[1]};
12594: }
12595:
1.888 albertel 12596: my %name_to_host = &all_names();
12597: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12598: my $ip;
12599: if (!exists($name_to_ip{$name})) {
12600: $ip = gethostbyname($name);
12601: if (!$ip || length($ip) ne 4) {
1.894 albertel 12602: if (defined($old_name_to_ip{$name})) {
12603: $ip = $old_name_to_ip{$name};
12604: &logthis("Can't find $name defaulting to old $ip");
12605: } else {
12606: &logthis("Name $name no IP found");
12607: next;
12608: }
12609: } else {
12610: $ip=inet_ntoa($ip);
1.847 albertel 12611: }
12612: $name_to_ip{$name} = $ip;
12613: } else {
12614: $ip = $name_to_ip{$name};
1.653 albertel 12615: }
1.888 albertel 12616: foreach my $id (@{ $name_to_host{$name} }) {
12617: $lonid_to_ip{$id} = $ip;
12618: }
12619: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12620: }
1.1219 raeburn 12621: &do_cache_new('iphost','iphost',
12622: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12623: 48*60*60);
1.869 albertel 12624:
1.847 albertel 12625: return %iphost;
1.598 albertel 12626: }
12627:
1.992 raeburn 12628: #
12629: # Given a DNS returns the loncapa host name for that DNS
12630: #
12631: sub host_from_dns {
12632: my ($dns) = @_;
12633: my @hosts;
12634: my $ip;
12635:
1.993 raeburn 12636: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12637: $ip = $name_to_ip{$dns};
12638: }
12639: if (!$ip) {
12640: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12641: if (length($ip) == 4) {
12642: $ip = &IO::Socket::inet_ntoa($ip);
12643: }
12644: }
12645: if ($ip) {
12646: @hosts = get_hosts_from_ip($ip);
12647: return $hosts[0];
12648: }
12649: return undef;
1.986 foxr 12650: }
1.992 raeburn 12651:
1.1074 raeburn 12652: sub get_internet_names {
12653: my ($lonid) = @_;
12654: return if ($lonid eq '');
12655: my ($idnref,$cached)=
12656: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12657: if ($cached) {
12658: return $idnref;
12659: }
12660: my $ip = &get_host_ip($lonid);
12661: my @hosts = &get_hosts_from_ip($ip);
12662: my %iphost = &get_iphost();
12663: my (@idns,%seen);
12664: foreach my $id (@hosts) {
12665: my $dom = &host_domain($id);
12666: my $prim_id = &domain($dom,'primary');
12667: my $prim_ip = &get_host_ip($prim_id);
12668: next if ($seen{$prim_ip});
12669: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12670: foreach my $id (@{$iphost{$prim_ip}}) {
12671: my $intdom = &internet_dom($id);
12672: unless (grep(/^\Q$intdom\E$/,@idns)) {
12673: push(@idns,$intdom);
12674: }
12675: }
12676: }
12677: $seen{$prim_ip} = 1;
12678: }
1.1219 raeburn 12679: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12680: }
12681:
1.986 foxr 12682: }
12683:
1.1079 raeburn 12684: sub all_loncaparevs {
1.1249 raeburn 12685: 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 12686: }
12687:
1.1227 raeburn 12688: # ---------------------------------------------------------- Read loncaparev table
12689: {
12690: sub load_loncaparevs {
12691: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12692: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12693: while (my $configline=<$config>) {
12694: chomp($configline);
12695: my ($hostid,$loncaparev)=split(/:/,$configline);
12696: $loncaparevs{$hostid}=$loncaparev;
12697: }
12698: close($config);
12699: }
12700: }
12701: }
12702: }
12703:
12704: # ---------------------------------------------------------- Read serverhostID table
12705: {
12706: sub load_serverhomeIDs {
12707: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12708: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12709: while (my $configline=<$config>) {
12710: chomp($configline);
12711: my ($name,$id)=split(/:/,$configline);
12712: $serverhomeIDs{$name}=$id;
12713: }
12714: close($config);
12715: }
12716: }
12717: }
12718: }
12719:
12720:
1.862 albertel 12721: BEGIN {
12722:
12723: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12724: unless ($readit) {
12725: {
12726: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12727: %perlvar = (%perlvar,%{$configvars});
12728: }
12729:
12730:
1.1 albertel 12731: # ------------------------------------------------------ Read spare server file
12732: {
1.448 albertel 12733: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12734:
12735: while (my $configline=<$config>) {
12736: chomp($configline);
1.284 matthew 12737: if ($configline) {
1.784 albertel 12738: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12739: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12740: push(@{ $spareid{$type} }, $host);
1.1 albertel 12741: }
12742: }
1.448 albertel 12743: close($config);
1.1 albertel 12744: }
1.11 www 12745: # ------------------------------------------------------------ Read permissions
12746: {
1.448 albertel 12747: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12748:
12749: while (my $configline=<$config>) {
1.448 albertel 12750: chomp($configline);
12751: if ($configline) {
12752: my ($role,$perm)=split(/ /,$configline);
12753: if ($perm ne '') { $pr{$role}=$perm; }
12754: }
1.11 www 12755: }
1.448 albertel 12756: close($config);
1.11 www 12757: }
12758:
12759: # -------------------------------------------- Read plain texts for permissions
12760: {
1.448 albertel 12761: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12762:
12763: while (my $configline=<$config>) {
1.448 albertel 12764: chomp($configline);
12765: if ($configline) {
1.742 raeburn 12766: my ($short,@plain)=split(/:/,$configline);
12767: %{$prp{$short}} = ();
12768: if (@plain > 0) {
12769: $prp{$short}{'std'} = $plain[0];
12770: for (my $i=1; $i<@plain; $i++) {
12771: $prp{$short}{'alt'.$i} = $plain[$i];
12772: }
12773: }
1.448 albertel 12774: }
1.135 www 12775: }
1.448 albertel 12776: close($config);
1.135 www 12777: }
12778:
12779: # ---------------------------------------------------------- Read package table
12780: {
1.448 albertel 12781: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12782:
12783: while (my $configline=<$config>) {
1.483 albertel 12784: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12785: chomp($configline);
12786: my ($short,$plain)=split(/:/,$configline);
12787: my ($pack,$name)=split(/\&/,$short);
12788: if ($plain ne '') {
12789: $packagetab{$pack.'&'.$name.'&name'}=$name;
12790: $packagetab{$short}=$plain;
12791: }
1.11 www 12792: }
1.448 albertel 12793: close($config);
1.329 matthew 12794: }
12795:
1.1073 raeburn 12796: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12797:
12798: &load_loncaparevs();
1.1073 raeburn 12799:
1.1074 raeburn 12800: # ---------------------------------------------------------- Read serverhostID table
12801:
1.1227 raeburn 12802: &load_serverhomeIDs();
12803:
12804: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12805: {
12806: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12807: if (-e $file) {
12808: my $parser = HTML::LCParser->new($file);
12809: while (my $token = $parser->get_token()) {
12810: if ($token->[0] eq 'S') {
12811: my $item = $token->[1];
12812: my $name = $token->[2]{'name'};
12813: my $value = $token->[2]{'value'};
1.1285 raeburn 12814: my $valuematch = $token->[2]{'valuematch'};
12815: if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
1.1079 raeburn 12816: my $release = $parser->get_text();
12817: $release =~ s/(^\s*|\s*$ )//gx;
1.1285 raeburn 12818: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
1.1079 raeburn 12819: }
12820: }
12821: }
12822: }
1.1073 raeburn 12823: }
12824:
1.1138 raeburn 12825: # ---------------------------------------------------------- Read managers table
12826: {
12827: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12828: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12829: while (my $configline=<$config>) {
12830: chomp($configline);
12831: next if ($configline =~ /^\#/);
12832: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12833: $managerstab{$configline} = 1;
12834: }
12835: }
12836: close($config);
12837: }
12838: }
12839: }
12840:
1.329 matthew 12841: # ------------- set up temporary directory
12842: {
1.1117 foxr 12843: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12844:
1.11 www 12845: }
12846:
1.794 albertel 12847: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12848: 'compress_threshold'=> 20_000,
12849: });
1.185 www 12850:
1.281 www 12851: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12852: $dumpcount=0;
1.958 www 12853: $locknum=0;
1.22 www 12854:
1.163 harris41 12855: &logtouch();
1.672 albertel 12856: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12857: $readit=1;
1.564 albertel 12858: {
12859: use integer;
12860: my $test=(2**32)+1;
1.568 albertel 12861: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12862: &logthis(" Detected 64bit platform ($_64bit)");
12863: }
1.195 www 12864: }
1.1 albertel 12865: }
1.179 www 12866:
1.1 albertel 12867: 1;
1.191 harris41 12868: __END__
12869:
1.243 albertel 12870: =pod
12871:
1.191 harris41 12872: =head1 NAME
12873:
1.243 albertel 12874: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12875:
12876: =head1 SYNOPSIS
12877:
1.243 albertel 12878: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12879:
12880: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12881:
1.243 albertel 12882: Common parameters:
12883:
12884: =over 4
12885:
12886: =item *
12887:
12888: $uname : an internal username (if $cname expecting a course Id specifically)
12889:
12890: =item *
12891:
12892: $udom : a domain (if $cdom expecting a course's domain specifically)
12893:
12894: =item *
12895:
12896: $symb : a resource instance identifier
12897:
12898: =item *
12899:
12900: $namespace : the name of a .db file that contains the data needed or
12901: being set.
12902:
12903: =back
12904:
1.394 bowersj2 12905: =head1 OVERVIEW
1.191 harris41 12906:
1.394 bowersj2 12907: lonnet provides subroutines which interact with the
12908: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12909: about classes, users, and resources.
1.243 albertel 12910:
12911: For many of these objects you can also use this to store data about
12912: them or modify them in various ways.
1.191 harris41 12913:
1.394 bowersj2 12914: =head2 Symbs
1.191 harris41 12915:
1.394 bowersj2 12916: To identify a specific instance of a resource, LON-CAPA uses symbols
12917: or "symbs"X<symb>. These identifiers are built from the URL of the
12918: map, the resource number of the resource in the map, and the URL of
12919: the resource itself. The latter is somewhat redundant, but might help
12920: if maps change.
12921:
12922: An example is
12923:
12924: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12925:
12926: The respective map entry is
12927:
12928: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12929: title="Problem 2">
12930: </resource>
12931:
12932: Symbs are used by the random number generator, as well as to store and
12933: restore data specific to a certain instance of for example a problem.
12934:
12935: =head2 Storing And Retrieving Data
12936:
12937: X<store()>X<cstore()>X<restore()>Three of the most important functions
12938: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12939: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12940: is is the non-critical message twin of cstore. These functions are for
12941: handlers to store a perl hash to a user's permanent data space in an
12942: easy manner, and to retrieve it again on another call. It is expected
12943: that a handler would use this once at the beginning to retrieve data,
12944: and then again once at the end to send only the new data back.
12945:
12946: The data is stored in the user's data directory on the user's
12947: homeserver under the ID of the course.
12948:
12949: The hash that is returned by restore will have all of the previous
12950: value for all of the elements of the hash.
12951:
12952: Example:
12953:
12954: #creating a hash
12955: my %hash;
12956: $hash{'foo'}='bar';
12957:
12958: #storing it
12959: &Apache::lonnet::cstore(\%hash);
12960:
12961: #changing a value
12962: $hash{'foo'}='notbar';
12963:
12964: #adding a new value
12965: $hash{'bar'}='foo';
12966: &Apache::lonnet::cstore(\%hash);
12967:
12968: #retrieving the hash
12969: my %history=&Apache::lonnet::restore();
12970:
12971: #print the hash
12972: foreach my $key (sort(keys(%history))) {
12973: print("\%history{$key} = $history{$key}");
12974: }
12975:
12976: Will print out:
1.191 harris41 12977:
1.394 bowersj2 12978: %history{1:foo} = bar
12979: %history{1:keys} = foo:timestamp
12980: %history{1:timestamp} = 990455579
12981: %history{2:bar} = foo
12982: %history{2:foo} = notbar
12983: %history{2:keys} = foo:bar:timestamp
12984: %history{2:timestamp} = 990455580
12985: %history{bar} = foo
12986: %history{foo} = notbar
12987: %history{timestamp} = 990455580
12988: %history{version} = 2
12989:
12990: Note that the special hash entries C<keys>, C<version> and
12991: C<timestamp> were added to the hash. C<version> will be equal to the
12992: total number of versions of the data that have been stored. The
12993: C<timestamp> attribute will be the UNIX time the hash was
12994: stored. C<keys> is available in every historical section to list which
12995: keys were added or changed at a specific historical revision of a
12996: hash.
12997:
12998: B<Warning>: do not store the hash that restore returns directly. This
12999: will cause a mess since it will restore the historical keys as if the
13000: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13001:
1.394 bowersj2 13002: Calling convention:
1.191 harris41 13003:
1.1225 raeburn 13004: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13005: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13006:
1.394 bowersj2 13007: For more detailed information, see lonnet specific documentation.
1.191 harris41 13008:
1.394 bowersj2 13009: =head1 RETURN MESSAGES
1.191 harris41 13010:
1.394 bowersj2 13011: =over 4
1.191 harris41 13012:
1.394 bowersj2 13013: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13014:
1.394 bowersj2 13015: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13016: when the connection is brought back up
1.191 harris41 13017:
1.394 bowersj2 13018: =item * B<con_failed>: unable to contact remote host and unable to save message
13019: for later delivery
1.191 harris41 13020:
1.967 bisitz 13021: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13022:
1.394 bowersj2 13023: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13024: that was requested
1.191 harris41 13025:
1.243 albertel 13026: =back
1.191 harris41 13027:
1.243 albertel 13028: =head1 PUBLIC SUBROUTINES
1.191 harris41 13029:
1.243 albertel 13030: =head2 Session Environment Functions
1.191 harris41 13031:
1.243 albertel 13032: =over 4
1.191 harris41 13033:
1.394 bowersj2 13034: =item *
13035: X<appenv()>
1.949 raeburn 13036: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13037: the user envirnoment file, and will be restored for each access this
1.620 albertel 13038: user makes during this session, also modifies the %env for the current
1.949 raeburn 13039: process. Optional rolesarrayref - if defined contains a reference to an array
13040: of roles which are exempt from the restriction on modifying user.role entries
13041: in the user's environment.db and in %env.
1.191 harris41 13042:
13043: =item *
1.394 bowersj2 13044: X<delenv()>
1.987 raeburn 13045: B<delenv($delthis,$regexp)>: removes all items from the session
13046: environment file that begin with $delthis. If the
13047: optional second arg - $regexp - is true, $delthis is treated as a
13048: regular expression, otherwise \Q$delthis\E is used.
13049: The values are also deleted from the current processes %env.
1.191 harris41 13050:
1.795 albertel 13051: =item * get_env_multiple($name)
13052:
13053: gets $name from the %env hash, it seemlessly handles the cases where multiple
13054: values may be defined and end up as an array ref.
13055:
13056: returns an array of values
13057:
1.243 albertel 13058: =back
13059:
13060: =head2 User Information
1.191 harris41 13061:
1.243 albertel 13062: =over 4
1.191 harris41 13063:
13064: =item *
1.394 bowersj2 13065: X<queryauthenticate()>
13066: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13067: authentication scheme
13068:
13069: =item *
1.394 bowersj2 13070: X<authenticate()>
1.1073 raeburn 13071: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13072: authenticate user from domain's lib servers (first use the current
13073: one). C<$upass> should be the users password.
1.1073 raeburn 13074: $checkdefauth is optional (value is 1 if a check should be made to
13075: authenticate user using default authentication method, and allow
13076: account creation if username does not have account in the domain).
13077: $clientcancheckhost is optional (value is 1 if checking whether the
13078: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13079:
13080: =item *
1.394 bowersj2 13081: X<homeserver()>
13082: B<homeserver($uname,$udom)>: find the server which has
13083: the user's directory and files (there must be only one), this caches
13084: the answer, and also caches if there is a borken connection.
1.191 harris41 13085:
13086: =item *
1.394 bowersj2 13087: X<idget()>
13088: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13089: (IDs are a unique resource in a domain, there must be only 1 ID per
13090: username, and only 1 username per ID in a specific domain) (returns
13091: hash: id=>name,id=>name)
1.191 harris41 13092:
13093: =item *
1.394 bowersj2 13094: X<idrget()>
13095: B<idrget($udom,@unames)>: find the IDs behind a list of
13096: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13097:
13098: =item *
1.394 bowersj2 13099: X<idput()>
13100: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13101:
13102: =item *
1.394 bowersj2 13103: X<rolesinit()>
1.1169 droeschl 13104: B<rolesinit($udom,$username)>: get user privileges.
13105: returns user role, first access and timer interval hashes
1.243 albertel 13106:
13107: =item *
1.1171 droeschl 13108: X<privileged()>
13109: B<privileged($username,$domain)>: returns a true if user has a
13110: privileged and active role (i.e. su or dc), false otherwise.
13111:
13112: =item *
1.551 albertel 13113: X<getsection()>
13114: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13115: course $cname, return section name/number or '' for "not in course"
13116: and '-1' for "no section"
13117:
13118: =item *
1.394 bowersj2 13119: X<userenvironment()>
13120: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13121: passed in @what from the requested user's environment, returns a hash
13122:
1.858 raeburn 13123: =item *
13124: X<userlog_query()>
1.859 albertel 13125: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13126: activity.log file. %filters defines filters applied when parsing the
13127: log file. These can be start or end timestamps, or the type of action
13128: - log to look for Login or Logout events, check for Checkin or
13129: Checkout, role for role selection. The response is in the form
13130: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13131: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13132:
1.243 albertel 13133: =back
13134:
13135: =head2 User Roles
13136:
13137: =over 4
13138:
13139: =item *
13140:
1.1284 raeburn 13141: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13142: returns codes for allowed actions.
13143:
13144: The first argument is required, all others are optional.
13145:
13146: $priv is the privilege being checked.
13147: $uri contains additional information about what is being checked for access (e.g.,
13148: URL, course ID etc.).
13149: $symb is the unique resource instance identifier in a course; if needed,
13150: but not provided, it will be retrieved via a call to &symbread().
13151: $role is the role for which a priv is being checked (only used if priv is evb).
13152: $clientip is the user's IP address (only used when checking for access to portfolio
13153: files).
13154: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13155: prevents recursive calls to &allowed.
13156:
1.243 albertel 13157: F: full access
13158: U,I,K: authentication modes (cxx only)
13159: '': forbidden
13160: 1: user needs to choose course
13161: 2: browse allowed
1.766 albertel 13162: A: passphrase authentication needed
1.1284 raeburn 13163: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13164:
13165: =item *
13166:
1.1192 raeburn 13167: constructaccess($url,$setpriv) : check for access to construction space URL
13168:
13169: See if the owner domain and name in the URL match those in the
13170: expected environment. If so, return three element list
13171: ($ownername,$ownerdomain,$ownerhome).
13172:
13173: Otherwise return the null string.
13174:
13175: If second argument 'setpriv' is true, it assigns the privileges,
13176: and returns the same three element list, unless the owner has
13177: blocked "ad hoc" Domain Coordinator access to the Author Space,
13178: in which case the null string is returned.
13179:
13180: =item *
13181:
1.243 albertel 13182: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13183: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13184: and course level
13185:
13186: =item *
13187:
1.988 raeburn 13188: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13189: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13190: $type is Course (default) or Community.
1.988 raeburn 13191: If $forcedefault evaluates to true, text returned will be default
13192: text for $type. Otherwise, if this is a course, the text returned
13193: will be a custom name for the role (if defined in the course's
13194: environment). If no custom name is defined the default is returned.
13195:
1.832 raeburn 13196: =item *
13197:
1.1219 raeburn 13198: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13199: All arguments are optional. Returns a hash of a roles, either for
13200: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13201: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13202: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13203: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13204: For each key, value is set to colon-separated start and end times for
13205: the role. If no username and domain are specified, will default to
1.934 raeburn 13206: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13207: of role statuses (active, future or previous), roles
13208: (e.g., cc,in, st etc.) and domains of the roles which can be used
13209: to restrict the list of roles reported. If no array ref is
13210: provided for types, will default to return only active roles.
1.834 albertel 13211:
1.1195 raeburn 13212: =item *
13213:
13214: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13215: user: $uname:$udom has a role in the course: $cdom_$cnum.
13216:
13217: Additional optional arguments are: $type (if role checking is to be restricted
13218: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13219: available roles) or future (roles available in the future), and
13220: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13221: have active Domain Coordinator role in course's domain or in additional
13222: domains (specified in 'Domains to check for privileged users' in course
13223: environment -- set via: Course Settings -> Classlists and staff listing).
13224:
13225: =item *
13226:
13227: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13228: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13229: $possdomains and $possroles are optional array refs -- to domains to check and
13230: roles to check. If $possdomains is not specified, a dump will be done of the
13231: users' roles.db to check for a dc or su role in any domain. This can be
13232: time consuming if &privileged is called repeatedly (e.g., when displaying a
13233: classlist), so in such cases, supplying a $possdomains array is preferred, as
13234: this then allows &privileged_by_domain() to be used, which caches the identity
13235: of privileged users, eliminating the need for repeated calls to &dump().
13236:
13237: =item *
13238:
13239: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13240: where the outer hash keys are domains specified in the $possdomains array ref,
13241: next inner hash keys are privileged roles specified in the $roles array ref,
13242: and the innermost hash contains key = value pairs for username:domain = end:start
13243: for active or future "privileged" users with that role in that domain. To avoid
13244: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13245: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13246:
1.243 albertel 13247: =back
13248:
13249: =head2 User Modification
13250:
13251: =over 4
13252:
13253: =item *
13254:
1.957 raeburn 13255: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13256: user for the level given by URL. Optional start and end dates (leave empty
13257: string or zero for "no date")
1.191 harris41 13258:
13259: =item *
13260:
1.243 albertel 13261: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13262: change a users, password, possible return values are: ok,
13263: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13264: refused
1.191 harris41 13265:
13266: =item *
13267:
1.243 albertel 13268: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13269:
13270: =item *
13271:
1.1058 raeburn 13272: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13273: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13274:
13275: will update user information (firstname,middlename,lastname,generation,
13276: permanentemail), and if forceid is true, student/employee ID also.
13277: A user's institutional affiliation(s) can also be updated.
13278: User information fields will not be overwritten with empty entries
13279: unless the field is included in the $candelete array reference.
13280: This array is included when a single user is modified via "Manage Users",
13281: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13282:
13283: =item *
13284:
1.286 matthew 13285: modifystudent
13286:
1.957 raeburn 13287: modify a student's enrollment and identification information.
1.1235 raeburn 13288: The course id is resolved based on the current user's environment.
13289: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13290: associated with a course.
13291:
1.297 matthew 13292: This call is essentially a wrapper for lonnet::modifyuser and
13293: lonnet::modify_student_enrollment
1.286 matthew 13294:
13295: Inputs:
13296:
13297: =over 4
13298:
1.957 raeburn 13299: =item B<$udom> Student's loncapa domain
1.286 matthew 13300:
1.957 raeburn 13301: =item B<$uname> Student's loncapa login name
1.286 matthew 13302:
1.964 bisitz 13303: =item B<$uid> Student/Employee ID
1.286 matthew 13304:
1.957 raeburn 13305: =item B<$umode> Student's authentication mode
1.286 matthew 13306:
1.957 raeburn 13307: =item B<$upass> Student's password
1.286 matthew 13308:
1.957 raeburn 13309: =item B<$first> Student's first name
1.286 matthew 13310:
1.957 raeburn 13311: =item B<$middle> Student's middle name
1.286 matthew 13312:
1.957 raeburn 13313: =item B<$last> Student's last name
1.286 matthew 13314:
1.957 raeburn 13315: =item B<$gene> Student's generation
1.286 matthew 13316:
1.957 raeburn 13317: =item B<$usec> Student's section in course
1.286 matthew 13318:
13319: =item B<$end> Unix time of the roles expiration
13320:
13321: =item B<$start> Unix time of the roles start date
13322:
13323: =item B<$forceid> If defined, allow $uid to be changed
13324:
13325: =item B<$desiredhome> server to use as home server for student
13326:
1.957 raeburn 13327: =item B<$email> Student's permanent e-mail address
13328:
13329: =item B<$type> Type of enrollment (auto or manual)
13330:
1.963 raeburn 13331: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13332:
13333: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13334:
1.963 raeburn 13335: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13336:
1.963 raeburn 13337: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13338:
1.1216 raeburn 13339: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13340:
13341: =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 13342:
1.286 matthew 13343: =back
1.297 matthew 13344:
13345: =item *
13346:
13347: modify_student_enrollment
13348:
1.1235 raeburn 13349: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13350: 'role.request.course' must be defined for this function to proceed.
13351:
13352: Inputs:
13353:
13354: =over 4
13355:
1.1235 raeburn 13356: =item $udom, student's domain
1.297 matthew 13357:
1.1235 raeburn 13358: =item $uname, student's name
1.297 matthew 13359:
1.1235 raeburn 13360: =item $uid, student's user id
1.297 matthew 13361:
1.1235 raeburn 13362: =item $first, student's first name
1.297 matthew 13363:
13364: =item $middle
13365:
13366: =item $last
13367:
13368: =item $gene
13369:
13370: =item $usec
13371:
13372: =item $end
13373:
13374: =item $start
13375:
1.957 raeburn 13376: =item $type
13377:
13378: =item $locktype
13379:
13380: =item $cid
13381:
13382: =item $selfenroll
13383:
13384: =item $context
13385:
1.1216 raeburn 13386: =item $credits, number of credits student will earn from this class
13387:
1.297 matthew 13388: =back
13389:
1.191 harris41 13390:
13391: =item *
13392:
1.243 albertel 13393: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13394: custom role; give a custom role to a user for the level given by URL. Specify
13395: name and domain of role author, and role name
1.191 harris41 13396:
13397: =item *
13398:
1.243 albertel 13399: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13400:
13401: =item *
13402:
1.243 albertel 13403: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13404:
13405: =back
13406:
13407: =head2 Course Infomation
13408:
13409: =over 4
1.191 harris41 13410:
13411: =item *
13412:
1.1118 foxr 13413: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13414: specified course id, including all environment settings for the
13415: course, the description of the course will be in the hash under the
13416: key 'description'
1.191 harris41 13417:
1.1118 foxr 13418: $options is an optional parameter that if supplied is a hash reference that controls
13419: what how this function works. It has the following key/values:
13420:
13421: =over 4
13422:
13423: =item freshen_cache
13424:
13425: If defined, and the environment cache for the course is valid, it is
13426: returned in the returned hash.
13427:
13428: =item one_time
13429:
13430: If defined, the last cache time is set to _now_
13431:
13432: =item user
13433:
13434: If defined, the supplied username is used instead of the current user.
13435:
13436:
13437: =back
13438:
1.191 harris41 13439: =item *
13440:
1.624 albertel 13441: resdata($name,$domain,$type,@which) : request for current parameter
13442: setting for a specific $type, where $type is either 'course' or 'user',
13443: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13444: answers for 10 minutes.
1.243 albertel 13445:
1.877 foxr 13446: =item *
13447:
13448: get_courseresdata($courseid, $domain) : dump the entire course resource
13449: data base, returning a hash that is keyed by the resource name and has
13450: values that are the resource value. I believe that the timestamps and
13451: versions are also returned.
13452:
1.1236 raeburn 13453: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13454: supplemental content area. This routine caches the number of files for
13455: 10 minutes.
13456:
1.243 albertel 13457: =back
13458:
13459: =head2 Course Modification
13460:
13461: =over 4
1.191 harris41 13462:
13463: =item *
13464:
1.243 albertel 13465: writecoursepref($courseid,%prefs) : write preferences (environment
13466: database) for a course
1.191 harris41 13467:
13468: =item *
13469:
1.1011 raeburn 13470: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13471:
13472: =item *
13473:
1.1038 raeburn 13474: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13475:
1.1167 droeschl 13476: =item *
13477:
13478: is_course($courseid), is_course($cdom, $cnum)
13479:
13480: Accepts either a combined $courseid (in the form of domain_courseid) or the
13481: two component version $cdom, $cnum. It checks if the specified course exists.
13482:
13483: Returns:
13484: undef if the course doesn't exist, otherwise
13485: in scalar context the combined courseid.
13486: in list context the two components of the course identifier, domain and
13487: courseid.
13488:
1.243 albertel 13489: =back
13490:
13491: =head2 Resource Subroutines
13492:
13493: =over 4
1.191 harris41 13494:
13495: =item *
13496:
1.243 albertel 13497: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13498:
13499: =item *
13500:
1.243 albertel 13501: repcopy($filename) : subscribes to the requested file, and attempts to
13502: replicate from the owning library server, Might return
1.607 raeburn 13503: 'unavailable', 'not_found', 'forbidden', 'ok', or
13504: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13505: resource. Expects the local filesystem pathname
13506: (/home/httpd/html/res/....)
13507:
13508: =back
13509:
13510: =head2 Resource Information
13511:
13512: =over 4
1.191 harris41 13513:
13514: =item *
13515:
1.1228 raeburn 13516: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13517: and returns the value of a variety of different possible values,
13518: $varname should be a request string, and the other parameters can be
13519: used to specify who and what one is asking about. Ordinarily, $cid
13520: does not need to be specified, as it is retrived from
13521: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13522: within lonuserstate::loadmap() when initializing a course, before
13523: $env{'request.course.id'} has been set, so it needs to be provided
13524: in that one case.
1.243 albertel 13525:
13526: Possible values for $varname are environment.lastname (or other item
13527: from the envirnment hash), user.name (or someother aspect about the
13528: user), resource.0.maxtries (or some other part and parameter of a
13529: resource)
1.204 albertel 13530:
13531: =item *
13532:
1.243 albertel 13533: directcondval($number) : get current value of a condition; reads from a state
13534: string
1.204 albertel 13535:
13536: =item *
13537:
1.243 albertel 13538: condval($condidx) : value of condition index based on state
1.204 albertel 13539:
13540: =item *
13541:
1.243 albertel 13542: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13543: resource's metadata, $what should be either a specific key, or either
13544: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13545: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13546:
13547: this function automatically caches all requests
1.191 harris41 13548:
13549: =item *
13550:
1.243 albertel 13551: metadata_query($query,$custom,$customshow) : make a metadata query against the
13552: network of library servers; returns file handle of where SQL and regex results
13553: will be stored for query
1.191 harris41 13554:
13555: =item *
13556:
1.1282 raeburn 13557: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13558: return symbolic list entry (all arguments optional).
13559:
13560: Args: filename is the filename (including path) for the file for which a symb
13561: is required; donotrecurse, if true will prevent calls to allowed() being made
13562: to check access status if more than one resource was found in the bighash
13563: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13564: a randompick); ignorecachednull, if true will prevent a symb of '' being
13565: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13566: cause possible symbs to be checked to determine if they are subject to content
13567: blocking, if so they will not be included as possible symbs; possibles is a
13568: ref to a hash, which, as a side effect, will be populated with all possible
13569: symbs (content blocking not tested).
13570:
1.243 albertel 13571: returns the data handle
1.191 harris41 13572:
13573: =item *
13574:
1.1190 raeburn 13575: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13576: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13577: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13578: on failure, user must be in a course, as it assumes the existence of
13579: the course initial hash, and uses $env('request.course.id'}. The third
13580: arg is an optional reference to a scalar. If this arg is passed in the
13581: call to symbverify, it will be set to 1 if the symb has been set to be
13582: encrypted; otherwise it will be null.
1.191 harris41 13583:
13584: =item *
13585:
1.243 albertel 13586: symbclean($symb) : removes versions numbers from a symb, returns the
13587: cleaned symb
1.191 harris41 13588:
13589: =item *
13590:
1.243 albertel 13591: is_on_map($uri) : checks if the $uri is somewhere on the current
13592: course map, user must be in a course for it to work.
1.191 harris41 13593:
13594: =item *
13595:
1.243 albertel 13596: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13597:
13598: =item *
13599:
1.243 albertel 13600: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13601: a random seed, all arguments are optional, if they aren't sent it uses the
13602: environment to derive them. Note: if symb isn't sent and it can't get one
13603: from &symbread it will use the current time as its return value
1.191 harris41 13604:
13605: =item *
13606:
1.243 albertel 13607: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13608: unfakeable, receipt
1.191 harris41 13609:
13610: =item *
13611:
1.620 albertel 13612: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13613:
13614: =item *
13615:
1.243 albertel 13616: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13617:
13618: =item *
13619:
1.243 albertel 13620: 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 13621:
13622: =item *
13623:
1.243 albertel 13624: 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 13625:
13626: =item *
13627:
1.243 albertel 13628: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13629:
13630: =item *
13631:
1.243 albertel 13632: devalidate($symb) : devalidate temporary spreadsheet calculations,
13633: forcing spreadsheet to reevaluate the resource scores next time.
13634:
1.1195 raeburn 13635: =item *
13636:
1.1196 raeburn 13637: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13638: when viewing in course context.
1.1195 raeburn 13639:
1.1196 raeburn 13640: input: six args -- filename (decluttered), course number, course domain,
13641: url, symb (if registered) and group (if this is a
13642: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13643:
1.1196 raeburn 13644: output: array of five scalars --
1.1195 raeburn 13645: $cfile -- url for file editing if editable on current server
13646: $home -- homeserver of resource (i.e., for author if published,
13647: or course if uploaded.).
13648: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13649: $forceedit -- 1 if icon/link should be to go to edit mode
13650: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13651:
13652: =item *
13653:
13654: is_course_upload($file,$cnum,$cdom)
13655:
13656: Used in course context to determine if current file was uploaded to
13657: the course (i.e., would be found in /userfiles/docs on the course's
13658: homeserver.
13659:
13660: input: 3 args -- filename (decluttered), course number and course domain.
13661: output: boolean -- 1 if file was uploaded.
13662:
1.243 albertel 13663: =back
13664:
13665: =head2 Storing/Retreiving Data
13666:
13667: =over 4
1.191 harris41 13668:
13669: =item *
13670:
1.1269 raeburn 13671: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13672: permanently for this url; hashref needs to be given and should be a \%hashname;
13673: the remaining args aren't required and if they aren't passed or are '' they will
13674: be derived from the env (with the exception of $laststore, which is an
13675: optional arg used when a user's submission is stored in grading).
13676: $laststore is $version=$timestamp, where $version is the most recent version
13677: number retrieved for the corresponding $symb in the $namespace db file, and
13678: $timestamp is the timestamp for that transaction (UNIX time).
13679: $laststore is currently only passed when cstore() is called by
13680: structuretags::finalize_storage().
1.191 harris41 13681:
13682: =item *
13683:
1.1269 raeburn 13684: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13685: but uses critical subroutine
1.191 harris41 13686:
13687: =item *
13688:
1.243 albertel 13689: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13690: all args are optional
1.191 harris41 13691:
13692: =item *
13693:
1.717 albertel 13694: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13695: dumps the complete (or key matching regexp) namespace into a hash
13696: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13697: normally &store()ed into
13698:
13699: $range should be either an integer '100' (give me the first 100
13700: matching records)
13701: or be two integers sperated by a - with no spaces
13702: '30-50' (give me the 30th through the 50th matching
13703: records)
13704:
13705:
13706: =item *
13707:
1.1269 raeburn 13708: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13709: replaces a &store() version of data with a replacement set of data
13710: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13711: reference. If $tolog is true, the transaction is logged in the courselog
13712: with an action=PUTSTORE.
1.717 albertel 13713:
13714: =item *
13715:
1.243 albertel 13716: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13717: works very similar to store/cstore, but all data is stored in a
13718: temporary location and can be reset using tmpreset, $storehash should
13719: be a hash reference, returns nothing on success
1.191 harris41 13720:
13721: =item *
13722:
1.243 albertel 13723: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13724: similar to restore, but all data is stored in a temporary location and
13725: can be reset using tmpreset. Returns a hash of values on success,
13726: error string otherwise.
1.191 harris41 13727:
13728: =item *
13729:
1.243 albertel 13730: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13731: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13732:
13733: =item *
13734:
1.243 albertel 13735: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13736: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13737:
13738: =item *
13739:
1.243 albertel 13740: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13741: namesp ($udom and $uname are optional)
1.191 harris41 13742:
13743: =item *
13744:
1.702 albertel 13745: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13746: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13747: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13748:
1.702 albertel 13749: $range should be either an integer '100' (give me the first 100
13750: matching records)
13751: or be two integers sperated by a - with no spaces
13752: '30-50' (give me the 30th through the 50th matching
13753: records)
1.449 matthew 13754: =item *
13755:
13756: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13757: $store can be a scalar, an array reference, or if the amount to be
13758: incremented is > 1, a hash reference.
13759:
13760: ($udom and $uname are optional)
1.191 harris41 13761:
13762: =item *
13763:
1.243 albertel 13764: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13765: ($udom and $uname are optional)
1.191 harris41 13766:
13767: =item *
13768:
1.243 albertel 13769: cput($namespace,$storehash,$udom,$uname) : critical put
13770: ($udom and $uname are optional)
1.191 harris41 13771:
13772: =item *
13773:
1.748 albertel 13774: newput($namespace,$storehash,$udom,$uname) :
13775:
13776: Attempts to store the items in the $storehash, but only if they don't
13777: currently exist, if this succeeds you can be certain that you have
13778: successfully created a new key value pair in the $namespace db.
13779:
13780:
13781: Args:
13782: $namespace: name of database to store values to
13783: $storehash: hashref to store to the db
13784: $udom: (optional) domain of user containing the db
13785: $uname: (optional) name of user caontaining the db
13786:
13787: Returns:
13788: 'ok' -> succeeded in storing all keys of $storehash
13789: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13790: least <key> already existed in the db (other
13791: requested keys may also already exist)
1.967 bisitz 13792: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13793: 'con_lost' -> unable to contact request server
13794: 'refused' -> action was not allowed by remote machine
13795:
13796:
13797: =item *
13798:
1.243 albertel 13799: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13800: reference filled in from namesp (encrypts the return communication)
13801: ($udom and $uname are optional)
1.191 harris41 13802:
13803: =item *
13804:
1.243 albertel 13805: log($udom,$name,$home,$message) : write to permanent log for user; use
13806: critical subroutine
13807:
1.806 raeburn 13808: =item *
13809:
1.860 raeburn 13810: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13811: array reference filled in from namespace found in domain level on either
13812: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13813:
13814: =item *
13815:
1.860 raeburn 13816: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13817: domain level either on specified domain server ($uhome) or primary domain
13818: server ($udom and $uhome are optional)
1.806 raeburn 13819:
1.943 raeburn 13820: =item *
13821:
1.1240 raeburn 13822: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13823: for: authentication, language, quotas, timezone, date locale, and portal URL in
13824: the target domain.
13825:
13826: May also include additional key => value pairs for the following groups:
13827:
13828: =over
13829:
13830: =item
13831: disk quotas (MB allocated by default to portfolios and authoring spaces).
13832:
13833: =over
13834:
13835: =item defaultquota, authorquota
13836:
13837: =back
13838:
13839: =item
13840: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13841: portfolio for users).
13842:
13843: =over
13844:
13845: =item
13846: aboutme, blog, webdav, portfolio
13847:
13848: =back
13849:
13850: =item
13851: requestcourses: ability to request courses, and how requests are processed.
13852:
13853: =over
13854:
13855: =item
1.1246 raeburn 13856: official, unofficial, community, textbook
1.1240 raeburn 13857:
13858: =back
13859:
13860: =item
13861: inststatus: types of institutional affiliation, and order in which they are displayed.
13862:
13863: =over
13864:
13865: =item
1.1256 raeburn 13866: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13867:
13868: =back
13869:
13870: =item
13871: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13872: for course's uploaded content.
13873:
13874: =over
13875:
13876: =item
1.1246 raeburn 13877: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13878: communityquota, textbookquota
1.1240 raeburn 13879:
13880: =back
13881:
13882: =item
13883: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13884: on your servers.
13885:
13886: =over
13887:
13888: =item
13889: remotesessions, hostedsessions
13890:
13891: =back
13892:
13893: =back
13894:
13895: In cases where a domain coordinator has never used the "Set Domain Configuration"
13896: utility to create a configuration.db file on a domain's primary library server
13897: only the following domain defaults: auth_def, auth_arg_def, lang_def
13898: -- corresponding values are authentication type (internal, krb4, krb5,
13899: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13900: will be available. Values are retrieved from cache (if current), unless the
13901: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13902: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13903:
13904: Typical usage:
1.943 raeburn 13905:
1.1240 raeburn 13906: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13907:
1.243 albertel 13908: =back
13909:
13910: =head2 Network Status Functions
13911:
13912: =over 4
1.191 harris41 13913:
13914: =item *
13915:
1.1137 raeburn 13916: dirlist() : return directory list based on URI (first arg).
13917:
13918: Inputs: 1 required, 5 optional.
13919:
13920: =over
13921:
13922: =item
13923: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13924:
13925: =item
13926: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13927:
13928: =item
13929: $username - username of user/course to be listed. Extracted from $uri if absent.
13930:
13931: =item
13932: $getpropath - boolean: 1 if prepend path using &propath().
13933:
13934: =item
13935: $getuserdir - boolean: 1 if prepend path for "userfiles".
13936:
13937: =item
13938: $alternateRoot - path to prepend in place of path from $uri.
13939:
13940: =back
13941:
13942: Returns: Array of up to two items.
13943:
13944: =over
13945:
13946: a reference to an array of files/subdirectories
13947:
13948: =over
13949:
13950: Each element in the array of files/subdirectories is a & separated list of
13951: item name and the result of running stat on the item. If dirlist was requested
13952: for a file instead of a directory, the item name will be ''. For a directory
13953: listing, if the item is a metadata file, the element will end &N&M
13954: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13955: default copyright set (1).
13956:
13957: =back
13958:
13959: a scalar containing error condition (if encountered).
13960:
13961: =over
13962:
13963: =item
13964: no_host (no homeserver identified for $username:$domain).
13965:
13966: =item
13967: no_such_host (server contacted for listing not identified as valid host).
13968:
13969: =item
13970: con_lost (connection to remote server failed).
13971:
13972: =item
13973: refused (invalid $username:$domain received on lond side).
13974:
13975: =item
13976: no_such_dir (directory at specified path on lond side does not exist).
13977:
13978: =item
13979: empty (directory at specified path on lond side is empty).
13980:
13981: =over
13982:
13983: This is currently not encountered because the &ls3, &ls2,
13984: &ls (_handler) routines on the lond side do not filter out
13985: . and .. from a directory listing.
13986:
13987: =back
13988:
13989: =back
13990:
13991: =back
1.191 harris41 13992:
13993: =item *
13994:
1.243 albertel 13995: spareserver() : find server with least workload from spare.tab
13996:
1.986 foxr 13997:
13998: =item *
13999:
14000: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14001: if there is no corresponding loncapa host.
14002:
1.243 albertel 14003: =back
14004:
1.986 foxr 14005:
1.243 albertel 14006: =head2 Apache Request
14007:
14008: =over 4
1.191 harris41 14009:
14010: =item *
14011:
1.243 albertel 14012: ssi($url,%hash) : server side include, does a complete request cycle on url to
14013: localhost, posts hash
14014:
14015: =back
14016:
14017: =head2 Data to String to Data
14018:
14019: =over 4
1.191 harris41 14020:
14021: =item *
14022:
1.243 albertel 14023: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14024: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14025:
14026: =item *
14027:
1.243 albertel 14028: hashref2str($hashref) : convert a hashref into a string complete with
14029: escaping and '=' and '&' separators, supports elements that are
14030: arrayrefs and hashrefs
1.191 harris41 14031:
14032: =item *
14033:
1.243 albertel 14034: arrayref2str($arrayref) : convert an arrayref into a string complete
14035: with escaping and '&' separators, supports elements that are arrayrefs
14036: and hashrefs
1.191 harris41 14037:
14038: =item *
14039:
1.243 albertel 14040: str2hash($string) : convert string to hash using unescaping and
14041: splitting on '=' and '&', supports elements that are arrayrefs and
14042: hashrefs
1.191 harris41 14043:
14044: =item *
14045:
1.243 albertel 14046: str2array($string) : convert string to hash using unescaping and
14047: splitting on '&', supports elements that are arrayrefs and hashrefs
14048:
14049: =back
14050:
14051: =head2 Logging Routines
14052:
14053:
14054: These routines allow one to make log messages in the lonnet.log and
14055: lonnet.perm logfiles.
1.191 harris41 14056:
1.1119 foxr 14057: =over 4
14058:
1.191 harris41 14059: =item *
14060:
1.243 albertel 14061: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14062:
14063: =item *
14064:
1.243 albertel 14065: logthis() : append message to the normal lonnet.log file, it gets
14066: preiodically rolled over and deleted.
1.191 harris41 14067:
14068: =item *
14069:
1.243 albertel 14070: logperm() : append a permanent message to lonnet.perm.log, this log
14071: file never gets deleted by any automated portion of the system, only
14072: messages of critical importance should go in here.
14073:
1.1119 foxr 14074:
1.243 albertel 14075: =back
14076:
14077: =head2 General File Helper Routines
14078:
14079: =over 4
1.191 harris41 14080:
14081: =item *
14082:
1.481 raeburn 14083: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14084: (a) files in /uploaded
14085: (i) If a local copy of the file exists -
14086: compares modification date of local copy with last-modified date for
14087: definitive version stored on home server for course. If local copy is
14088: stale, requests a new version from the home server and stores it.
14089: If the original has been removed from the home server, then local copy
14090: is unlinked.
14091: (ii) If local copy does not exist -
14092: requests the file from the home server and stores it.
14093:
14094: If $caller is 'uploadrep':
14095: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14096: for request for files originally uploaded via DOCS.
14097: - returns 'ok' if fresh local copy now available, -1 otherwise.
14098:
14099: Otherwise:
14100: This indicates a call from the content generation phase of the request.
14101: - returns the entire contents of the file or -1.
14102:
14103: (b) files in /res
14104: - returns the entire contents of a file or -1;
14105: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14106:
1.712 albertel 14107:
14108: =item *
14109:
14110: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14111: reference
14112:
14113: returns either a stat() list of data about the file or an empty list
14114: if the file doesn't exist or couldn't find out about it (connection
14115: problems or user unknown)
14116:
1.191 harris41 14117: =item *
14118:
1.243 albertel 14119: filelocation($dir,$file) : returns file system location of a file
14120: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14121: directory that relative $file lookups are to looked in ($dir of /a/dir
14122: and a file of ../bob will become /a/bob)
1.191 harris41 14123:
14124: =item *
14125:
14126: hreflocation($dir,$file) : returns file system location or a URL; same as
14127: filelocation except for hrefs
14128:
14129: =item *
14130:
1.1261 raeburn 14131: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14132: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14133:
1.243 albertel 14134: =back
14135:
1.608 albertel 14136: =head2 Usererfile file routines (/uploaded*)
14137:
14138: =over 4
14139:
14140: =item *
14141:
14142: userfileupload(): main rotine for putting a file in a user or course's
14143: filespace, arguments are,
14144:
1.620 albertel 14145: formname - required - this is the name of the element in $env where the
1.608 albertel 14146: filename, and the contents of the file to create/modifed exist
1.620 albertel 14147: the filename is in $env{'form.'.$formname.'.filename'} and the
14148: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14149: context - if coursedoc, store the file in the course of the active role
14150: of the current user;
14151: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14152: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14153: subdir - required - subdirectory to put the file in under ../userfiles/
14154: if undefined, it will be placed in "unknown"
14155:
14156: (This routine calls clean_filename() to remove any dangerous
14157: characters from the filename, and then calls finuserfileupload() to
14158: complete the transaction)
14159:
14160: returns either the url of the uploaded file (/uploaded/....) if successful
14161: and /adm/notfound.html if unsuccessful
14162:
14163: =item *
14164:
14165: clean_filename(): routine for cleaing a filename up for storage in
14166: userfile space, argument is:
14167:
14168: filename - proposed filename
14169:
14170: returns: the new clean filename
14171:
14172: =item *
14173:
1.1090 raeburn 14174: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14175: userspace, probably shouldn't be called directly
14176:
14177: docuname: username or courseid of destination for the file
14178: docudom: domain of user/course of destination for the file
14179: formname: same as for userfileupload()
1.1090 raeburn 14180: fname: filename (including subdirectories) for the file
14181: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14182: allfiles: reference to hash used to store objects found by parser
14183: codebase: reference to hash used for codebases of java objects found by parser
14184: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14185: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14186: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14187: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14188: context: if 'overwrite', will move the uploaded file from its temporary location to
14189: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14190: mimetype: reference to scalar to accommodate mime type determined
14191: from File::MMagic if $parser = parse.
1.608 albertel 14192:
14193: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14194: and /adm/notfound.html if unsuccessful (or an error message if context
14195: was 'overwrite').
14196:
1.608 albertel 14197:
14198: =item *
14199:
14200: renameuserfile(): renames an existing userfile to a new name
14201:
14202: Args:
14203: docuname: username or courseid of destination for the file
14204: docudom: domain of user/course of destination for the file
14205: old: current file name (including any subdirs under userfiles)
14206: new: desired file name (including any subdirs under userfiles)
14207:
14208: =item *
14209:
14210: mkdiruserfile(): creates a directory is a userfiles dir
14211:
14212: Args:
14213: docuname: username or courseid of destination for the file
14214: docudom: domain of user/course of destination for the file
14215: dir: dir to create (including any subdirs under userfiles)
14216:
14217: =item *
14218:
14219: removeuserfile(): removes a file that exists in userfiles
14220:
14221: Args:
14222: docuname: username or courseid of destination for the file
14223: docudom: domain of user/course of destination for the file
14224: fname: filname to delete (including any subdirs under userfiles)
14225:
14226: =item *
14227:
14228: removeuploadedurl(): convience function for removeuserfile()
14229:
14230: Args:
14231: url: a full /uploaded/... url to delete
14232:
1.747 albertel 14233: =item *
14234:
14235: get_portfile_permissions():
14236: Args:
14237: domain: domain of user or course contain the portfolio files
14238: user: name of user or num of course contain the portfolio files
14239: Returns:
14240: hashref of a dump of the proper file_permissions.db
14241:
14242:
14243: =item *
14244:
14245: get_access_controls():
14246:
14247: Args:
14248: current_permissions: the hash ref returned from get_portfile_permissions()
14249: group: (optional) the group you want the files associated with
14250: file: (optional) the file you want access info on
14251:
14252: Returns:
1.749 raeburn 14253: a hash (keys are file names) of hashes containing
14254: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14255: values are XML containing access control settings (see below)
1.747 albertel 14256:
14257: Internal notes:
14258:
1.749 raeburn 14259: access controls are stored in file_permissions.db as key=value pairs.
14260: key -> path to file/file_name\0uniqueID:scope_end_start
14261: where scope -> public,guest,course,group,domains or users.
14262: end -> UNIX time for end of access (0 -> no end date)
14263: start -> UNIX time for start of access
14264:
14265: value -> XML description of access control
14266: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14267: <start></start>
14268: <end></end>
14269:
14270: <password></password> for scope type = guest
14271:
14272: <domain></domain> for scope type = course or group
14273: <number></number>
14274: <roles id="">
14275: <role></role>
14276: <access></access>
14277: <section></section>
14278: <group></group>
14279: </roles>
14280:
14281: <dom></dom> for scope type = domains
14282:
14283: <users> for scope type = users
14284: <user>
14285: <uname></uname>
14286: <udom></udom>
14287: </user>
14288: </users>
14289: </scope>
14290:
14291: Access data is also aggregated for each file in an additional key=value pair:
14292: key -> path to file/file_name\0accesscontrol
14293: value -> reference to hash
14294: hash contains key = value pairs
14295: where key = uniqueID:scope_end_start
14296: value = UNIX time record was last updated
14297:
14298: Used to improve speed of look-ups of access controls for each file.
14299:
14300: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14301:
1.1198 raeburn 14302: =item *
14303:
1.749 raeburn 14304: modify_access_controls():
14305:
14306: Modifies access controls for a portfolio file
14307: Args
14308: 1. file name
14309: 2. reference to hash of required changes,
14310: 3. domain
14311: 4. username
14312: where domain,username are the domain of the portfolio owner
14313: (either a user or a course)
14314:
14315: Returns:
14316: 1. result of additions or updates ('ok' or 'error', with error message).
14317: 2. result of deletions ('ok' or 'error', with error message).
14318: 3. reference to hash of any new or updated access controls.
14319: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14320: key = integer (inbound ID)
1.1198 raeburn 14321: value = uniqueID
14322:
14323: =item *
14324:
14325: get_timebased_id():
14326:
14327: Attempts to get a unique timestamp-based suffix for use with items added to a
14328: course via the Course Editor (e.g., folders, composite pages,
14329: group bulletin boards).
14330:
14331: Args: (first three required; six others optional)
14332:
14333: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14334: docssequence, or name of group
14335:
14336: 2. keyid (alphanumeric): name of temporary locking key in hash,
14337: e.g., num, boardids
14338:
14339: 3. namespace: name of gdbm file used to store suffixes already assigned;
14340: file will be named nohist_namespace.db
14341:
14342: 4. cdom: domain of course; default is current course domain from %env
14343:
14344: 5. cnum: course number; default is current course number from %env
14345:
14346: 6. idtype: set to concat if an additional digit is to be appended to the
14347: unix timestamp to form the suffix, if the plain timestamp is already
14348: in use. Default is to not do this, but simply increment the unix
14349: timestamp by 1 until a unique key is obtained.
14350:
14351: 7. who: holder of locking key; defaults to user:domain for user.
14352:
14353: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14354: retrying); default is 3.
14355:
14356: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14357:
14358: Returns:
14359:
14360: 1. suffix obtained (numeric)
14361:
14362: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14363:
14364: 3. error: contains (localized) error message if an error occurred.
14365:
1.747 albertel 14366:
1.608 albertel 14367: =back
14368:
1.243 albertel 14369: =head2 HTTP Helper Routines
14370:
14371: =over 4
14372:
1.191 harris41 14373: =item *
14374:
14375: escape() : unpack non-word characters into CGI-compatible hex codes
14376:
14377: =item *
14378:
14379: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14380:
1.243 albertel 14381: =back
14382:
14383: =head1 PRIVATE SUBROUTINES
14384:
14385: =head2 Underlying communication routines (Shouldn't call)
14386:
14387: =over 4
14388:
14389: =item *
14390:
14391: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14392:
14393: =item *
14394:
14395: reply() : uses subreply to send a message to remote machine, logs all failures
14396:
14397: =item *
14398:
14399: critical() : passes a critical message to another server; if cannot
14400: get through then place message in connection buffer directory and
14401: returns con_delayed, if incapable of saving message, returns
14402: con_failed
14403:
14404: =item *
14405:
14406: reconlonc() : tries to reconnect lonc client processes.
14407:
14408: =back
14409:
14410: =head2 Resource Access Logging
14411:
14412: =over 4
14413:
14414: =item *
14415:
14416: flushcourselogs() : flush (save) buffer logs and access logs
14417:
14418: =item *
14419:
14420: courselog($what) : save message for course in hash
14421:
14422: =item *
14423:
14424: courseacclog($what) : save message for course using &courselog(). Perform
14425: special processing for specific resource types (problems, exams, quizzes, etc).
14426:
1.191 harris41 14427: =item *
14428:
14429: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14430: as a PerlChildExitHandler
1.243 albertel 14431:
14432: =back
14433:
14434: =head2 Other
14435:
14436: =over 4
14437:
14438: =item *
14439:
14440: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14441:
14442: =back
14443:
14444: =cut
1.877 foxr 14445:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>