Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.46
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.46! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.45 2014/04/30 23:19:24 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
1.1172.2.41 raeburn 888: my ($try_server, $spare_server, $lowest_load, $required) = @_;
889:
890: if ($required) {
891: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
892: my $remoterev = &get_server_loncaparev(undef,$try_server);
893: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
894: if (($major eq '' && $minor eq '') ||
895: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
896: return ($spare_server,$lowest_load);
897: }
898: }
1.784 albertel 899:
900: my $loadans = &reply('load', $try_server);
901: my $userloadans = &reply('userload',$try_server);
902:
903: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 904: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 905: }
906:
907: my $load;
908: if ($loadans =~ /\d/) {
909: if ($userloadans =~ /\d/) {
910: #both are numbers, pick the bigger one
911: $load = ($loadans > $userloadans) ? $loadans
912: : $userloadans;
1.411 albertel 913: } else {
1.784 albertel 914: $load = $loadans;
1.411 albertel 915: }
1.784 albertel 916: } else {
917: $load = $userloadans;
918: }
919:
920: if (($load =~ /\d/) && ($load < $lowest_load)) {
921: $spare_server = $try_server;
922: $lowest_load = $load;
1.370 albertel 923: }
1.784 albertel 924: return ($spare_server,$lowest_load);
1.202 matthew 925: }
1.914 albertel 926:
927: # --------------------------- ask offload servers if user already has a session
928: sub find_existing_session {
929: my ($udom,$uname) = @_;
1.1123 raeburn 930: my $spareshash = &this_host_spares($udom);
931: if (ref($spareshash) eq 'HASH') {
932: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'primary'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
937: if (ref($spareshash->{'default'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'default'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
1.914 albertel 942: }
943: return;
944: }
945:
946: # -------------------------------- ask if server already has a session for user
947: sub has_user_session {
948: my ($lonid,$udom,$uname) = @_;
949: my $result = &reply(join(':','userhassession',
950: map {&escape($_)} ($udom,$uname)),$lonid);
951: return 1 if ($result eq 'ok');
952:
953: return 0;
954: }
955:
1.1076 raeburn 956: # --------- determine least loaded server in a user's domain which allows login
957:
958: sub choose_server {
1.1172.2.42 raeburn 959: my ($udom,$checkloginvia,$required) = @_;
1.1076 raeburn 960: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 961: my %servers = &get_servers($udom);
1.1076 raeburn 962: my $lowest_load = 30000;
1.1151 raeburn 963: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 964: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 965: my $loginvia;
966: if ($checkloginvia) {
967: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 968: if ($loginvia) {
969: my ($server,$path) = split(/:/,$loginvia);
970: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 971: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 972: if ($login_host eq $server) {
973: $portal_path = $path;
1.1151 raeburn 974: $isredirect = 1;
1.1116 raeburn 975: }
976: } else {
977: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 978: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 979: if ($login_host eq $lonhost) {
980: $portal_path = '';
1.1151 raeburn 981: $isredirect = '';
1.1116 raeburn 982: }
983: }
984: } else {
1.1076 raeburn 985: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 986: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 987: }
988: }
989: if ($login_host ne '') {
1.1116 raeburn 990: $hostname = &hostname($login_host);
1.1076 raeburn 991: }
1.1151 raeburn 992: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 993: }
994:
1.202 matthew 995: # --------------------------------------------- Try to change a user's password
996:
997: sub changepass {
1.799 raeburn 998: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 999: $currentpass = &escape($currentpass);
1000: $newpass = &escape($newpass);
1.1030 raeburn 1001: my $lonhost = $perlvar{'lonHostID'};
1002: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1003: $server);
1004: if (! $answer) {
1005: &logthis("No reply on password change request to $server ".
1006: "by $uname in domain $udom.");
1007: } elsif ($answer =~ "^ok") {
1008: &logthis("$uname in $udom successfully changed their password ".
1009: "on $server.");
1010: } elsif ($answer =~ "^pwchange_failure") {
1011: &logthis("$uname in $udom was unable to change their password ".
1012: "on $server. The action was blocked by either lcpasswd ".
1013: "or pwchange");
1014: } elsif ($answer =~ "^non_authorized") {
1015: &logthis("$uname in $udom did not get their password correct when ".
1016: "attempting to change it on $server.");
1017: } elsif ($answer =~ "^auth_mode_error") {
1018: &logthis("$uname in $udom attempted to change their password despite ".
1019: "not being locally or internally authenticated on $server.");
1020: } elsif ($answer =~ "^unknown_user") {
1021: &logthis("$uname in $udom attempted to change their password ".
1022: "on $server but were unable to because $server is not ".
1023: "their home server.");
1024: } elsif ($answer =~ "^refused") {
1025: &logthis("$server refused to change $uname in $udom password because ".
1026: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1027: } elsif ($answer =~ "invalid_client") {
1028: &logthis("$server refused to change $uname in $udom password because ".
1029: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1030: }
1031: return $answer;
1.1 albertel 1032: }
1033:
1.169 harris41 1034: # ----------------------- Try to determine user's current authentication scheme
1035:
1036: sub queryauthenticate {
1037: my ($uname,$udom)=@_;
1.456 albertel 1038: my $uhome=&homeserver($uname,$udom);
1039: if (!$uhome) {
1040: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1041: return 'no_host';
1042: }
1043: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1044: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1045: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1046: }
1.456 albertel 1047: return $answer;
1.169 harris41 1048: }
1049:
1.1 albertel 1050: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1051:
1.1 albertel 1052: sub authenticate {
1.1073 raeburn 1053: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1054: $upass=&escape($upass);
1055: $uname= &LONCAPA::clean_username($uname);
1.836 www 1056: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1057: my $newhome;
1.836 www 1058: if ((!$uhome) || ($uhome eq 'no_host')) {
1059: # Maybe the machine was offline and only re-appeared again recently?
1060: &reconlonc();
1061: # One more
1.952 raeburn 1062: $uhome=&homeserver($uname,$udom,1);
1063: if (($uhome eq 'no_host') && $checkdefauth) {
1064: if (defined(&domain($udom,'primary'))) {
1065: $newhome=&domain($udom,'primary');
1066: }
1067: if ($newhome ne '') {
1068: $uhome = $newhome;
1069: }
1070: }
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1073: return 'no_host';
1074: }
1.1 albertel 1075: }
1.1073 raeburn 1076: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1077: if ($answer eq 'authorized') {
1.952 raeburn 1078: if ($newhome) {
1079: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1080: return 'no_account_on_host';
1081: } else {
1082: &logthis("User $uname at $udom authorized by $uhome");
1083: return $uhome;
1084: }
1.471 albertel 1085: }
1086: if ($answer eq 'non_authorized') {
1087: &logthis("User $uname at $udom rejected by $uhome");
1088: return 'no_host';
1.9 www 1089: }
1.471 albertel 1090: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1091: return 'no_host';
1092: }
1093:
1.1073 raeburn 1094: sub can_host_session {
1.1074 raeburn 1095: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1096: my $canhost = 1;
1.1074 raeburn 1097: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1098: if (ref($remotesessions) eq 'HASH') {
1099: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1100: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1101: $canhost = 0;
1102: } else {
1103: $canhost = 1;
1104: }
1105: }
1106: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1107: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1108: $canhost = 1;
1109: } else {
1110: $canhost = 0;
1111: }
1112: }
1113: if ($canhost) {
1114: if ($remotesessions->{'version'} ne '') {
1115: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1116: if ($reqmajor ne '' && $reqminor ne '') {
1117: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1118: my $major = $1;
1119: my $minor = $2;
1120: if (($major < $reqmajor ) ||
1121: (($major == $reqmajor) && ($minor < $reqminor))) {
1122: $canhost = 0;
1123: }
1124: } else {
1125: $canhost = 0;
1126: }
1127: }
1128: }
1129: }
1130: }
1131: if ($canhost) {
1132: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1133: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1134: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1135: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1136: if (($uint_dom ne '') &&
1137: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1138: $canhost = 0;
1139: } else {
1140: $canhost = 1;
1141: }
1142: }
1143: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1144: if (($uint_dom ne '') &&
1145: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1146: $canhost = 1;
1147: } else {
1148: $canhost = 0;
1149: }
1150: }
1151: }
1152: }
1153: return $canhost;
1154: }
1155:
1.1083 raeburn 1156: sub spare_can_host {
1157: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1158: my $canhost=1;
1159: my @intdoms;
1160: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1161: if (ref($internet_names) eq 'ARRAY') {
1162: @intdoms = @{$internet_names};
1163: }
1164: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1165: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1166: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1167: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1168: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1169: $canhost = &can_host_session($udom,$try_server,$remoterev,
1170: $remotesessions,
1171: $defdomdefaults{'hostedsessions'});
1172: }
1173: return $canhost;
1174: }
1175:
1.1123 raeburn 1176: sub this_host_spares {
1177: my ($dom) = @_;
1.1126 raeburn 1178: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1179: my @hosts = ¤t_machine_ids();
1180: foreach my $lonhost (@hosts) {
1181: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1182: $dom_in_use = $dom;
1183: $lonhost_in_use = $lonhost;
1.1123 raeburn 1184: last;
1185: }
1186: }
1.1126 raeburn 1187: if ($dom_in_use ne '') {
1188: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1189: }
1190: if (ref($result) ne 'HASH') {
1191: $lonhost_in_use = $perlvar{'lonHostID'};
1192: $dom_in_use = &host_domain($lonhost_in_use);
1193: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1194: if (ref($result) ne 'HASH') {
1195: $result = \%spareid;
1196: }
1197: }
1198: return $result;
1199: }
1200:
1201: sub spares_for_offload {
1202: my ($dom_in_use,$lonhost_in_use) = @_;
1203: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1204: if (defined($cached)) {
1205: return $result;
1206: } else {
1.1126 raeburn 1207: my $cachetime = 60*60*24;
1208: my %domconfig =
1209: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1210: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1211: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1212: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1213: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1214: }
1215: }
1216: }
1217: }
1.1126 raeburn 1218: return;
1.1123 raeburn 1219: }
1220:
1.1129 raeburn 1221: sub get_lonbalancer_config {
1222: my ($servers) = @_;
1223: my ($currbalancer,$currtargets);
1224: if (ref($servers) eq 'HASH') {
1225: foreach my $server (keys(%{$servers})) {
1226: my %what = (
1227: spareid => 1,
1228: perlvar => 1,
1229: );
1230: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1231: if ($result eq 'ok') {
1232: if (ref($returnhash) eq 'HASH') {
1233: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1234: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1235: $currbalancer = $server;
1236: $currtargets = {};
1237: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1238: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1239: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1240: }
1241: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1242: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1243: }
1244: }
1245: last;
1246: }
1247: }
1248: }
1249: }
1250: }
1251: }
1252: return ($currbalancer,$currtargets);
1253: }
1254:
1255: sub check_loadbalancing {
1256: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1257: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1258: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1259: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1260: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1261: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1262: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1263: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1264: my $serverhomedom = &host_domain($lonhost);
1265:
1266: my $cachetime = 60*60*24;
1267:
1268: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1269: $dom_in_use = $udom;
1270: $homeintdom = 1;
1271: } else {
1272: $dom_in_use = $serverhomedom;
1273: }
1274: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1275: unless (defined($cached)) {
1276: my %domconfig =
1277: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1278: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1279: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1280: }
1281: }
1282: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1283: ($is_balancer,$currtargets,$currrules) =
1284: &check_balancer_result($result,@hosts);
1.1129 raeburn 1285: if ($is_balancer) {
1286: if (ref($currrules) eq 'HASH') {
1287: if ($homeintdom) {
1288: if ($uname ne '') {
1289: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1290: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1291: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1292: $rule_in_effect = $currrules->{'_LC_author'};
1293: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1294: $rule_in_effect = $currrules->{'_LC_adv'}
1295: }
1296: }
1297: if ($rule_in_effect eq '') {
1298: my %userenv = &userenvironment($udom,$uname,'inststatus');
1299: if ($userenv{'inststatus'} ne '') {
1300: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1301: my ($othertitle,$usertypes,$types) =
1302: &Apache::loncommon::sorted_inst_types($udom);
1303: if (ref($types) eq 'ARRAY') {
1304: foreach my $type (@{$types}) {
1305: if (grep(/^\Q$type\E$/,@statuses)) {
1306: if (exists($currrules->{$type})) {
1307: $rule_in_effect = $currrules->{$type};
1308: }
1309: }
1310: }
1311: }
1312: } else {
1313: if (exists($currrules->{'default'})) {
1314: $rule_in_effect = $currrules->{'default'};
1315: }
1316: }
1317: }
1318: } else {
1319: if (exists($currrules->{'default'})) {
1320: $rule_in_effect = $currrules->{'default'};
1321: }
1322: }
1323: } else {
1324: if ($currrules->{'_LC_external'} ne '') {
1325: $rule_in_effect = $currrules->{'_LC_external'};
1326: }
1327: }
1328: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1329: $uname,$udom);
1330: }
1331: }
1332: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1333: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1334: unless (defined($cached)) {
1335: my %domconfig =
1336: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1337: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1338: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1339: }
1340: }
1341: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1342: ($is_balancer,$currtargets,$currrules) =
1343: &check_balancer_result($result,@hosts);
1344: if ($is_balancer) {
1.1129 raeburn 1345: if (ref($currrules) eq 'HASH') {
1346: if ($currrules->{'_LC_internetdom'} ne '') {
1347: $rule_in_effect = $currrules->{'_LC_internetdom'};
1348: }
1349: }
1350: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1351: $uname,$udom);
1352: }
1353: } else {
1354: if ($perlvar{'lonBalancer'} eq 'yes') {
1355: $is_balancer = 1;
1356: $offloadto = &this_host_spares($dom_in_use);
1357: }
1358: }
1359: } else {
1360: if ($perlvar{'lonBalancer'} eq 'yes') {
1361: $is_balancer = 1;
1362: $offloadto = &this_host_spares($dom_in_use);
1363: }
1364: }
1.1172.2.5 raeburn 1365: if ($is_balancer) {
1366: my $lowest_load = 30000;
1367: if (ref($offloadto) eq 'HASH') {
1368: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1369: foreach my $try_server (@{$offloadto->{'primary'}}) {
1370: ($otherserver,$lowest_load) =
1371: &compare_server_load($try_server,$otherserver,$lowest_load);
1372: }
1.1129 raeburn 1373: }
1.1172.2.5 raeburn 1374: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1375:
1.1172.2.5 raeburn 1376: if (!$found_server) {
1377: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1378: foreach my $try_server (@{$offloadto->{'default'}}) {
1379: ($otherserver,$lowest_load) =
1380: &compare_server_load($try_server,$otherserver,$lowest_load);
1381: }
1382: }
1383: }
1384: } elsif (ref($offloadto) eq 'ARRAY') {
1385: if (@{$offloadto} == 1) {
1386: $otherserver = $offloadto->[0];
1387: } elsif (@{$offloadto} > 1) {
1388: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1389: ($otherserver,$lowest_load) =
1390: &compare_server_load($try_server,$otherserver,$lowest_load);
1391: }
1392: }
1393: }
1.1172.2.5 raeburn 1394: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1395: $is_balancer = 0;
1396: if ($uname ne '' && $udom ne '') {
1397: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1398:
1399: &appenv({'user.loadbalexempt' => $lonhost,
1400: 'user.loadbalcheck.time' => time});
1401: }
1.1129 raeburn 1402: }
1403: }
1404: }
1405: return ($is_balancer,$otherserver);
1406: }
1407:
1.1172.2.12 raeburn 1408: sub check_balancer_result {
1409: my ($result,@hosts) = @_;
1410: my ($is_balancer,$currtargets,$currrules);
1411: if (ref($result) eq 'HASH') {
1412: if ($result->{'lonhost'} ne '') {
1413: my $currbalancer = $result->{'lonhost'};
1414: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1415: $is_balancer = 1;
1416: $currtargets = $result->{'targets'};
1417: $currrules = $result->{'rules'};
1418: }
1419: } else {
1420: foreach my $key (keys(%{$result})) {
1421: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1422: (ref($result->{$key}) eq 'HASH')) {
1423: $is_balancer = 1;
1424: $currrules = $result->{$key}{'rules'};
1425: $currtargets = $result->{$key}{'targets'};
1426: last;
1427: }
1428: }
1429: }
1430: }
1431: return ($is_balancer,$currtargets,$currrules);
1432: }
1433:
1.1129 raeburn 1434: sub get_loadbalancer_targets {
1435: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1436: my $offloadto;
1.1172.2.4 raeburn 1437: if ($rule_in_effect eq 'none') {
1438: return [$perlvar{'lonHostID'}];
1439: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1440: $offloadto = $currtargets;
1441: } else {
1442: if ($rule_in_effect eq 'homeserver') {
1443: my $homeserver = &homeserver($uname,$udom);
1444: if ($homeserver ne 'no_host') {
1445: $offloadto = [$homeserver];
1446: }
1447: } elsif ($rule_in_effect eq 'externalbalancer') {
1448: my %domconfig =
1449: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1450: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1451: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1452: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1453: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1454: }
1455: }
1456: } else {
1.1172.2.7 raeburn 1457: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1458: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1459: if (&hostname($remotebalancer) ne '') {
1460: $offloadto = [$remotebalancer];
1461: }
1462: }
1463: } elsif (&hostname($rule_in_effect) ne '') {
1464: $offloadto = [$rule_in_effect];
1465: }
1466: }
1467: return $offloadto;
1468: }
1469:
1.1127 raeburn 1470: sub internet_dom_servers {
1471: my ($dom) = @_;
1472: my (%uniqservers,%servers);
1473: my $primaryserver = &hostname(&domain($dom,'primary'));
1474: my @machinedoms = &machine_domains($primaryserver);
1475: foreach my $mdom (@machinedoms) {
1476: my %currservers = %servers;
1477: my %server = &get_servers($mdom);
1478: %servers = (%currservers,%server);
1479: }
1480: my %by_hostname;
1481: foreach my $id (keys(%servers)) {
1482: push(@{$by_hostname{$servers{$id}}},$id);
1483: }
1484: foreach my $hostname (sort(keys(%by_hostname))) {
1485: if (@{$by_hostname{$hostname}} > 1) {
1486: my $match = 0;
1487: foreach my $id (@{$by_hostname{$hostname}}) {
1488: if (&host_domain($id) eq $dom) {
1489: $uniqservers{$id} = $hostname;
1490: $match = 1;
1491: }
1492: }
1493: unless ($match) {
1494: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1495: }
1496: } else {
1497: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1498: }
1499: }
1500: return %uniqservers;
1501: }
1502:
1.1 albertel 1503: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1504:
1.599 albertel 1505: my %homecache;
1.1 albertel 1506: sub homeserver {
1.230 stredwic 1507: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1508: my $index="$uname:$udom";
1.426 albertel 1509:
1.599 albertel 1510: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1511:
1512: my %servers = &get_servers($udom,'library');
1513: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1514: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1515: exists($badServerCache{$tryserver}));
1.841 albertel 1516:
1517: my $answer=reply("home:$udom:$uname",$tryserver);
1518: if ($answer eq 'found') {
1519: delete($badServerCache{$tryserver});
1520: return $homecache{$index}=$tryserver;
1521: } elsif ($answer eq 'no_host') {
1522: $badServerCache{$tryserver}=1;
1523: }
1.1 albertel 1524: }
1525: return 'no_host';
1.70 www 1526: }
1527:
1528: # ------------------------------------- Find the usernames behind a list of IDs
1529:
1530: sub idget {
1531: my ($udom,@ids)=@_;
1532: my %returnhash=();
1533:
1.841 albertel 1534: my %servers = &get_servers($udom,'library');
1535: foreach my $tryserver (keys(%servers)) {
1536: my $idlist=join('&',@ids);
1537: $idlist=~tr/A-Z/a-z/;
1538: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1539: my @answer=();
1540: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1541: @answer=split(/\&/,$reply);
1542: } ;
1543: my $i;
1544: for ($i=0;$i<=$#ids;$i++) {
1545: if ($answer[$i]) {
1546: $returnhash{$ids[$i]}=$answer[$i];
1547: }
1548: }
1549: }
1.70 www 1550: return %returnhash;
1551: }
1552:
1553: # ------------------------------------- Find the IDs behind a list of usernames
1554:
1555: sub idrget {
1556: my ($udom,@unames)=@_;
1557: my %returnhash=();
1.800 albertel 1558: foreach my $uname (@unames) {
1559: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1560: }
1.70 www 1561: return %returnhash;
1562: }
1563:
1564: # ------------------------------- Store away a list of names and associated IDs
1565:
1566: sub idput {
1567: my ($udom,%ids)=@_;
1568: my %servers=();
1.800 albertel 1569: foreach my $uname (keys(%ids)) {
1570: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1571: my $uhom=&homeserver($uname,$udom);
1.70 www 1572: if ($uhom ne 'no_host') {
1.800 albertel 1573: my $id=&escape($ids{$uname});
1.70 www 1574: $id=~tr/A-Z/a-z/;
1.800 albertel 1575: my $esc_unam=&escape($uname);
1.70 www 1576: if ($servers{$uhom}) {
1.800 albertel 1577: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1578: } else {
1.800 albertel 1579: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1580: }
1581: }
1.191 harris41 1582: }
1.800 albertel 1583: foreach my $server (keys(%servers)) {
1584: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1585: }
1.344 www 1586: }
1587:
1.1172.2.30 raeburn 1588: # ---------------------------------------- Delete unwanted IDs from ids.db file
1589:
1590: sub iddel {
1591: my ($udom,$idshashref,$uhome)=@_;
1592: my %result=();
1593: unless (ref($idshashref) eq 'HASH') {
1594: return %result;
1595: }
1596: my %servers=();
1597: while (my ($id,$uname) = each(%{$idshashref})) {
1598: my $uhom;
1599: if ($uhome) {
1600: $uhom = $uhome;
1601: } else {
1602: $uhom=&homeserver($uname,$udom);
1603: }
1604: if ($uhom ne 'no_host') {
1605: if ($servers{$uhom}) {
1606: $servers{$uhom}.='&'.&escape($id);
1607: } else {
1608: $servers{$uhom}=&escape($id);
1609: }
1610: }
1611: }
1612: foreach my $server (keys(%servers)) {
1613: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1614: }
1615: return %result;
1616: }
1617:
1.1023 raeburn 1618: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1619: sub dump_dom {
1.1165 droeschl 1620: my ($namespace, $udom, $regexp) = @_;
1621:
1622: $udom ||= $env{'user.domain'};
1623:
1624: return () unless $udom;
1625:
1626: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1627: }
1628:
1.1023 raeburn 1629: # ------------------------------------------ get items from domain db files
1.806 raeburn 1630:
1631: sub get_dom {
1.860 raeburn 1632: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1633: my $items='';
1634: foreach my $item (@$storearr) {
1635: $items.=&escape($item).'&';
1636: }
1637: $items=~s/\&$//;
1.860 raeburn 1638: if (!$udom) {
1639: $udom=$env{'user.domain'};
1640: if (defined(&domain($udom,'primary'))) {
1641: $uhome=&domain($udom,'primary');
1642: } else {
1.874 albertel 1643: undef($uhome);
1.860 raeburn 1644: }
1645: } else {
1646: if (!$uhome) {
1647: if (defined(&domain($udom,'primary'))) {
1648: $uhome=&domain($udom,'primary');
1649: }
1650: }
1651: }
1652: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1653: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1654: my %returnhash;
1.875 albertel 1655: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1656: return %returnhash;
1657: }
1.806 raeburn 1658: my @pairs=split(/\&/,$rep);
1659: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1660: return @pairs;
1661: }
1662: my $i=0;
1663: foreach my $item (@$storearr) {
1664: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1665: $i++;
1666: }
1667: return %returnhash;
1668: } else {
1.880 banghart 1669: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1670: }
1671: }
1672:
1673: # -------------------------------------------- put items in domain db files
1674:
1675: sub put_dom {
1.860 raeburn 1676: my ($namespace,$storehash,$udom,$uhome)=@_;
1677: if (!$udom) {
1678: $udom=$env{'user.domain'};
1679: if (defined(&domain($udom,'primary'))) {
1680: $uhome=&domain($udom,'primary');
1681: } else {
1.874 albertel 1682: undef($uhome);
1.860 raeburn 1683: }
1684: } else {
1685: if (!$uhome) {
1686: if (defined(&domain($udom,'primary'))) {
1687: $uhome=&domain($udom,'primary');
1688: }
1689: }
1690: }
1691: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1692: my $items='';
1693: foreach my $item (keys(%$storehash)) {
1694: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1695: }
1696: $items=~s/\&$//;
1697: return &reply("putdom:$udom:$namespace:$items",$uhome);
1698: } else {
1.860 raeburn 1699: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1700: }
1701: }
1702:
1.1023 raeburn 1703: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1704: sub newput_dom {
1.1023 raeburn 1705: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1706: my $result;
1707: if (!$udom) {
1708: $udom=$env{'user.domain'};
1709: }
1.1023 raeburn 1710: if ($udom) {
1711: my $uname = &get_domainconfiguser($udom);
1712: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1713: }
1714: return $result;
1715: }
1716:
1.1023 raeburn 1717: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1718: sub del_dom {
1.1023 raeburn 1719: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1720: if (ref($storearr) eq 'ARRAY') {
1721: if (!$udom) {
1722: $udom=$env{'user.domain'};
1723: }
1.1023 raeburn 1724: if ($udom) {
1725: my $uname = &get_domainconfiguser($udom);
1726: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1727: }
1728: }
1729: }
1730:
1.1023 raeburn 1731: # ----------------------------------construct domainconfig user for a domain
1732: sub get_domainconfiguser {
1733: my ($udom) = @_;
1734: return $udom.'-domainconfig';
1735: }
1736:
1.837 raeburn 1737: sub retrieve_inst_usertypes {
1738: my ($udom) = @_;
1739: my (%returnhash,@order);
1.989 raeburn 1740: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1741: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1742: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1743: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1744: } else {
1745: if (defined(&domain($udom,'primary'))) {
1746: my $uhome=&domain($udom,'primary');
1747: my $rep=&reply("inst_usertypes:$udom",$uhome);
1748: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1749: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1750: return (\%returnhash,\@order);
1751: }
1752: my ($hashitems,$orderitems) = split(/:/,$rep);
1753: my @pairs=split(/\&/,$hashitems);
1754: foreach my $item (@pairs) {
1755: my ($key,$value)=split(/=/,$item,2);
1756: $key = &unescape($key);
1757: next if ($key =~ /^error: 2 /);
1758: $returnhash{$key}=&thaw_unescape($value);
1759: }
1760: my @esc_order = split(/\&/,$orderitems);
1761: foreach my $item (@esc_order) {
1762: push(@order,&unescape($item));
1763: }
1764: } else {
1.1172.2.44 raeburn 1765: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1766: }
1.1172.2.44 raeburn 1767: return (\%returnhash,\@order);
1.837 raeburn 1768: }
1769: }
1770:
1.868 raeburn 1771: sub is_domainimage {
1772: my ($url) = @_;
1773: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1774: if (&domain($1) ne '') {
1775: return '1';
1776: }
1777: }
1778: return;
1779: }
1780:
1.899 raeburn 1781: sub inst_directory_query {
1782: my ($srch) = @_;
1783: my $udom = $srch->{'srchdomain'};
1784: my %results;
1785: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1786: my $outcome;
1.899 raeburn 1787: if ($homeserver ne '') {
1.904 albertel 1788: my $queryid=&reply("querysend:instdirsearch:".
1789: &escape($srch->{'srchby'}).':'.
1790: &escape($srch->{'srchterm'}).':'.
1791: &escape($srch->{'srchtype'}),$homeserver);
1792: my $host=&hostname($homeserver);
1793: if ($queryid !~/^\Q$host\E\_/) {
1794: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1795: return;
1796: }
1797: my $response = &get_query_reply($queryid);
1798: my $maxtries = 5;
1799: my $tries = 1;
1800: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1801: $response = &get_query_reply($queryid);
1802: $tries ++;
1803: }
1804:
1805: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1806: if ($response eq 'unavailable') {
1807: $outcome = $response;
1808: } else {
1809: $outcome = 'ok';
1810: my @matches = split(/\n/,$response);
1811: foreach my $match (@matches) {
1812: my ($key,$value) = split(/=/,$match);
1813: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1814: }
1.899 raeburn 1815: }
1816: }
1817: }
1.909 raeburn 1818: return ($outcome,%results);
1.899 raeburn 1819: }
1820:
1821: sub usersearch {
1822: my ($srch) = @_;
1823: my $dom = $srch->{'srchdomain'};
1824: my %results;
1825: my %libserv = &all_library();
1826: my $query = 'usersearch';
1827: foreach my $tryserver (keys(%libserv)) {
1828: if (&host_domain($tryserver) eq $dom) {
1829: my $host=&hostname($tryserver);
1830: my $queryid=
1.911 raeburn 1831: &reply("querysend:".&escape($query).':'.
1832: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1833: &escape($srch->{'srchtype'}).':'.
1834: &escape($srch->{'srchterm'}),$tryserver);
1835: if ($queryid !~/^\Q$host\E\_/) {
1836: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1837: next;
1.899 raeburn 1838: }
1839: my $reply = &get_query_reply($queryid);
1840: my $maxtries = 1;
1841: my $tries = 1;
1842: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1843: $reply = &get_query_reply($queryid);
1844: $tries ++;
1845: }
1846: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1847: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1848: } else {
1.911 raeburn 1849: my @matches;
1850: if ($reply =~ /\n/) {
1851: @matches = split(/\n/,$reply);
1852: } else {
1853: @matches = split(/\&/,$reply);
1854: }
1.899 raeburn 1855: foreach my $match (@matches) {
1856: my ($uname,$udom,%userhash);
1.911 raeburn 1857: foreach my $entry (split(/:/,$match)) {
1858: my ($key,$value) =
1859: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1860: $userhash{$key} = $value;
1861: if ($key eq 'username') {
1862: $uname = $value;
1863: } elsif ($key eq 'domain') {
1864: $udom = $value;
1.911 raeburn 1865: }
1.899 raeburn 1866: }
1867: $results{$uname.':'.$udom} = \%userhash;
1868: }
1869: }
1870: }
1871: }
1872: return %results;
1873: }
1874:
1.912 raeburn 1875: sub get_instuser {
1876: my ($udom,$uname,$id) = @_;
1877: my $homeserver = &domain($udom,'primary');
1878: my ($outcome,%results);
1879: if ($homeserver ne '') {
1880: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1881: &escape($id).':'.&escape($udom),$homeserver);
1882: my $host=&hostname($homeserver);
1883: if ($queryid !~/^\Q$host\E\_/) {
1884: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1885: return;
1886: }
1887: my $response = &get_query_reply($queryid);
1888: my $maxtries = 5;
1889: my $tries = 1;
1890: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1891: $response = &get_query_reply($queryid);
1892: $tries ++;
1893: }
1894: if (!&error($response) && $response ne 'refused') {
1895: if ($response eq 'unavailable') {
1896: $outcome = $response;
1897: } else {
1898: $outcome = 'ok';
1899: my @matches = split(/\n/,$response);
1900: foreach my $match (@matches) {
1901: my ($key,$value) = split(/=/,$match);
1902: $results{&unescape($key)} = &thaw_unescape($value);
1903: }
1904: }
1905: }
1906: }
1907: my %userinfo;
1908: if (ref($results{$uname}) eq 'HASH') {
1909: %userinfo = %{$results{$uname}};
1910: }
1911: return ($outcome,%userinfo);
1912: }
1913:
1914: sub inst_rulecheck {
1.923 raeburn 1915: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1916: my %returnhash;
1917: if ($udom ne '') {
1918: if (ref($rules) eq 'ARRAY') {
1919: @{$rules} = map {&escape($_);} (@{$rules});
1920: my $rulestr = join(':',@{$rules});
1921: my $homeserver=&domain($udom,'primary');
1922: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1923: my $response;
1924: if ($item eq 'username') {
1925: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1926: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1927: $homeserver));
1.923 raeburn 1928: } elsif ($item eq 'id') {
1929: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1930: ':'.&escape($id).':'.$rulestr,
1931: $homeserver));
1.945 raeburn 1932: } elsif ($item eq 'selfcreate') {
1933: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1934: &escape($udom).':'.&escape($uname).
1935: ':'.$rulestr,$homeserver));
1.923 raeburn 1936: }
1.912 raeburn 1937: if ($response ne 'refused') {
1938: my @pairs=split(/\&/,$response);
1939: foreach my $item (@pairs) {
1940: my ($key,$value)=split(/=/,$item,2);
1941: $key = &unescape($key);
1942: next if ($key =~ /^error: 2 /);
1943: $returnhash{$key}=&thaw_unescape($value);
1944: }
1945: }
1946: }
1947: }
1948: }
1949: return %returnhash;
1950: }
1951:
1952: sub inst_userrules {
1.923 raeburn 1953: my ($udom,$check) = @_;
1.912 raeburn 1954: my (%ruleshash,@ruleorder);
1955: if ($udom ne '') {
1956: my $homeserver=&domain($udom,'primary');
1957: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1958: my $response;
1959: if ($check eq 'id') {
1960: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1961: $homeserver);
1.943 raeburn 1962: } elsif ($check eq 'email') {
1963: $response=&reply('instemailrules:'.&escape($udom),
1964: $homeserver);
1.923 raeburn 1965: } else {
1966: $response=&reply('instuserrules:'.&escape($udom),
1967: $homeserver);
1968: }
1.912 raeburn 1969: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1970: ($response ne 'unknown_cmd') &&
1.912 raeburn 1971: ($response ne 'no_such_host')) {
1972: my ($hashitems,$orderitems) = split(/:/,$response);
1973: my @pairs=split(/\&/,$hashitems);
1974: foreach my $item (@pairs) {
1975: my ($key,$value)=split(/=/,$item,2);
1976: $key = &unescape($key);
1977: next if ($key =~ /^error: 2 /);
1978: $ruleshash{$key}=&thaw_unescape($value);
1979: }
1980: my @esc_order = split(/\&/,$orderitems);
1981: foreach my $item (@esc_order) {
1982: push(@ruleorder,&unescape($item));
1983: }
1984: }
1985: }
1986: }
1987: return (\%ruleshash,\@ruleorder);
1988: }
1989:
1.976 raeburn 1990: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1991:
1992: sub get_domain_defaults {
1.1172.2.35 raeburn 1993: my ($domain,$ignore_cache) = @_;
1994: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1995: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 1996: unless ($ignore_cache) {
1997: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1998: if (defined($cached)) {
1999: if (ref($result) eq 'HASH') {
2000: return %{$result};
2001: }
1.943 raeburn 2002: }
2003: }
2004: my %domdefaults;
2005: my %domconfig =
1.989 raeburn 2006: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2007: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2008: 'coursedefaults','usersessions',
1.1172.2.46! raeburn 2009: 'requestauthor','selfenrollment',
! 2010: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2011: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2012: if (ref($domconfig{'defaults'}) eq 'HASH') {
2013: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2014: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2015: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2016: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2017: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2018: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2019: } else {
2020: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2021: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2022: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2023: }
1.976 raeburn 2024: if (ref($domconfig{'quotas'}) eq 'HASH') {
2025: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2026: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2027: } else {
2028: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2029: }
1.1172.2.6 raeburn 2030: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2031: foreach my $item (@usertools) {
2032: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2033: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2034: }
2035: }
1.1172.2.29 raeburn 2036: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2037: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2038: }
1.976 raeburn 2039: }
1.985 raeburn 2040: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2041: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2042: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2043: }
2044: }
1.1172.2.9 raeburn 2045: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2046: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2047: }
1.989 raeburn 2048: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2049: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2050: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2051: }
2052: }
1.1047 raeburn 2053: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41 raeburn 2054: foreach my $type (@coursetypes) {
2055: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2056: unless ($type eq 'community') {
2057: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2058: }
2059: }
2060: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2061: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2062: }
1.1172.2.30 raeburn 2063: }
1.1047 raeburn 2064: }
1.1073 raeburn 2065: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2066: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2067: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2068: }
2069: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2070: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2071: }
2072: }
1.1172.2.41 raeburn 2073: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2074: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2075: my @settings = ('types','registered','enroll_dates','access_dates','section',
2076: 'approval','limit');
2077: foreach my $type (@coursetypes) {
2078: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2079: my @mgrdc = ();
2080: foreach my $item (@settings) {
2081: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2082: push(@mgrdc,$item);
2083: }
2084: }
2085: if (@mgrdc) {
2086: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2087: }
2088: }
2089: }
2090: }
2091: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2092: foreach my $type (@coursetypes) {
2093: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2094: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2095: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2096: }
2097: }
2098: }
2099: }
2100: }
1.1172.2.46! raeburn 2101: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
! 2102: $domdefaults{'catauth'} = 'std';
! 2103: $domdefaults{'catunauth'} = 'std';
! 2104: if ($domconfig{'coursecategories'}{'auth'}) {
! 2105: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
! 2106: }
! 2107: if ($domconfig{'coursecategories'}{'unauth'}) {
! 2108: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
! 2109: }
! 2110: }
1.1172.2.23 raeburn 2111: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2112: return %domdefaults;
2113: }
2114:
1.344 www 2115: # --------------------------------------------------- Assign a key to a student
2116:
2117: sub assign_access_key {
1.364 www 2118: #
2119: # a valid key looks like uname:udom#comments
2120: # comments are being appended
2121: #
1.498 www 2122: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2123: $kdom=
1.620 albertel 2124: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2125: $knum=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2127: $cdom=
1.620 albertel 2128: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2129: $cnum=
1.620 albertel 2130: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2131: $udom=$env{'user.name'} unless (defined($udom));
2132: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2133: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2134: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2135: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2136: # assigned to this person
2137: # - this should not happen,
1.345 www 2138: # unless something went wrong
2139: # the first time around
2140: # ready to assign
1.364 www 2141: $logentry=$1.'; '.$logentry;
1.496 www 2142: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2143: $kdom,$knum) eq 'ok') {
1.345 www 2144: # key now belongs to user
1.346 www 2145: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2146: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2147: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2148: return 'ok';
2149: } else {
2150: return
2151: 'error: Count not permanently assign key, will need to be re-entered later.';
2152: }
2153: } else {
2154: return 'error: Could not assign key, try again later.';
2155: }
1.364 www 2156: } elsif (!$existing{$ckey}) {
1.345 www 2157: # the key does not exist
2158: return 'error: The key does not exist';
2159: } else {
2160: # the key is somebody else's
2161: return 'error: The key is already in use';
2162: }
1.344 www 2163: }
2164:
1.364 www 2165: # ------------------------------------------ put an additional comment on a key
2166:
2167: sub comment_access_key {
2168: #
2169: # a valid key looks like uname:udom#comments
2170: # comments are being appended
2171: #
2172: my ($ckey,$cdom,$cnum,$logentry)=@_;
2173: $cdom=
1.620 albertel 2174: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2175: $cnum=
1.620 albertel 2176: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2177: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2178: if ($existing{$ckey}) {
2179: $existing{$ckey}.='; '.$logentry;
2180: # ready to assign
1.367 www 2181: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2182: $cdom,$cnum) eq 'ok') {
2183: return 'ok';
2184: } else {
2185: return 'error: Count not store comment.';
2186: }
2187: } else {
2188: # the key does not exist
2189: return 'error: The key does not exist';
2190: }
2191: }
2192:
1.344 www 2193: # ------------------------------------------------------ Generate a set of keys
2194:
2195: sub generate_access_keys {
1.364 www 2196: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2197: $cdom=
1.620 albertel 2198: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2199: $cnum=
1.620 albertel 2200: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2201: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2202: unless (($cdom) && ($cnum)) { return 0; }
2203: if ($number>10000) { return 0; }
2204: sleep(2); # make sure don't get same seed twice
2205: srand(time()^($$+($$<<15))); # from "Programming Perl"
2206: my $total=0;
2207: for (my $i=1;$i<=$number;$i++) {
2208: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2209: sprintf("%lx",int(100000*rand)).'-'.
2210: sprintf("%lx",int(100000*rand));
2211: $newkey=~s/1/g/g; # folks mix up 1 and l
2212: $newkey=~s/0/h/g; # and also 0 and O
2213: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2214: if ($existing{$newkey}) {
2215: $i--;
2216: } else {
1.364 www 2217: if (&put('accesskeys',
2218: { $newkey => '# generated '.localtime().
1.620 albertel 2219: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2220: '; '.$logentry },
2221: $cdom,$cnum) eq 'ok') {
1.344 www 2222: $total++;
2223: }
2224: }
2225: }
1.620 albertel 2226: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2227: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2228: return $total;
2229: }
2230:
2231: # ------------------------------------------------------- Validate an accesskey
2232:
2233: sub validate_access_key {
2234: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2235: $cdom=
1.620 albertel 2236: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2237: $cnum=
1.620 albertel 2238: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2239: $udom=$env{'user.domain'} unless (defined($udom));
2240: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2241: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2242: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2243: }
2244:
2245: # ------------------------------------- Find the section of student in a course
1.652 albertel 2246: sub devalidate_getsection_cache {
2247: my ($udom,$unam,$courseid)=@_;
2248: my $hashid="$udom:$unam:$courseid";
2249: &devalidate_cache_new('getsection',$hashid);
2250: }
1.298 matthew 2251:
1.815 albertel 2252: sub courseid_to_courseurl {
2253: my ($courseid) = @_;
2254: #already url style courseid
2255: return $courseid if ($courseid =~ m{^/});
2256:
2257: if (exists($env{'course.'.$courseid.'.num'})) {
2258: my $cnum = $env{'course.'.$courseid.'.num'};
2259: my $cdom = $env{'course.'.$courseid.'.domain'};
2260: return "/$cdom/$cnum";
2261: }
2262:
2263: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2264: if (exists($courseinfo{'num'})) {
2265: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2266: }
2267:
2268: return undef;
2269: }
2270:
1.298 matthew 2271: sub getsection {
2272: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2273: my $cachetime=1800;
1.551 albertel 2274:
2275: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2276: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2277: if (defined($cached)) { return $result; }
2278:
1.298 matthew 2279: my %Pending;
2280: my %Expired;
2281: #
2282: # Each role can either have not started yet (pending), be active,
2283: # or have expired.
2284: #
2285: # If there is an active role, we are done.
2286: #
2287: # If there is more than one role which has not started yet,
2288: # choose the one which will start sooner
2289: # If there is one role which has not started yet, return it.
2290: #
2291: # If there is more than one expired role, choose the one which ended last.
2292: # If there is a role which has expired, return it.
2293: #
1.815 albertel 2294: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2295: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2296: foreach my $key (keys(%roleshash)) {
1.479 albertel 2297: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2298: my $section=$1;
2299: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2300: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2301: my $now=time;
1.548 albertel 2302: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2303: $Expired{$end}=$section;
2304: next;
2305: }
1.548 albertel 2306: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2307: $Pending{$start}=$section;
2308: next;
2309: }
1.599 albertel 2310: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2311: }
2312: #
2313: # Presumedly there will be few matching roles from the above
2314: # loop and the sorting time will be negligible.
2315: if (scalar(keys(%Pending))) {
2316: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2317: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2318: }
2319: if (scalar(keys(%Expired))) {
2320: my @sorted = sort {$a <=> $b} keys(%Expired);
2321: my $time = pop(@sorted);
1.599 albertel 2322: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2323: }
1.599 albertel 2324: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2325: }
1.70 www 2326:
1.599 albertel 2327: sub save_cache {
2328: &purge_remembered();
1.722 albertel 2329: #&Apache::loncommon::validate_page();
1.620 albertel 2330: undef(%env);
1.780 albertel 2331: undef($env_loaded);
1.599 albertel 2332: }
1.452 albertel 2333:
1.599 albertel 2334: my $to_remember=-1;
2335: my %remembered;
2336: my %accessed;
2337: my $kicks=0;
2338: my $hits=0;
1.849 albertel 2339: sub make_key {
2340: my ($name,$id) = @_;
1.872 albertel 2341: if (length($id) > 65
2342: && length(&escape($id)) > 200) {
2343: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2344: }
1.849 albertel 2345: return &escape($name.':'.$id);
2346: }
2347:
1.599 albertel 2348: sub devalidate_cache_new {
2349: my ($name,$id,$debug) = @_;
2350: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2351: $id=&make_key($name,$id);
1.599 albertel 2352: $memcache->delete($id);
2353: delete($remembered{$id});
2354: delete($accessed{$id});
2355: }
2356:
2357: sub is_cached_new {
2358: my ($name,$id,$debug) = @_;
1.849 albertel 2359: $id=&make_key($name,$id);
1.599 albertel 2360: if (exists($remembered{$id})) {
1.1133 foxr 2361: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2362: $accessed{$id}=[&gettimeofday()];
2363: $hits++;
2364: return ($remembered{$id},1);
2365: }
2366: my $value = $memcache->get($id);
2367: if (!(defined($value))) {
2368: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2369: return (undef,undef);
1.416 albertel 2370: }
1.599 albertel 2371: if ($value eq '__undef__') {
2372: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2373: $value=undef;
2374: }
2375: &make_room($id,$value,$debug);
2376: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2377: return ($value,1);
2378: }
2379:
2380: sub do_cache_new {
2381: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2382: $id=&make_key($name,$id);
1.599 albertel 2383: my $setvalue=$value;
2384: if (!defined($setvalue)) {
2385: $setvalue='__undef__';
2386: }
1.623 albertel 2387: if (!defined($time) ) {
2388: $time=600;
2389: }
1.599 albertel 2390: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2391: my $result = $memcache->set($id,$setvalue,$time);
2392: if (! $result) {
1.872 albertel 2393: &logthis("caching of id -> $id failed");
1.910 albertel 2394: $memcache->disconnect_all();
1.872 albertel 2395: }
1.600 albertel 2396: # need to make a copy of $value
1.919 albertel 2397: &make_room($id,$value,$debug);
1.599 albertel 2398: return $value;
2399: }
2400:
2401: sub make_room {
2402: my ($id,$value,$debug)=@_;
1.919 albertel 2403:
2404: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2405: : $value;
1.599 albertel 2406: if ($to_remember<0) { return; }
2407: $accessed{$id}=[&gettimeofday()];
2408: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2409: my $to_kick;
2410: my $max_time=0;
2411: foreach my $other (keys(%accessed)) {
2412: if (&tv_interval($accessed{$other}) > $max_time) {
2413: $to_kick=$other;
2414: $max_time=&tv_interval($accessed{$other});
2415: }
2416: }
2417: delete($remembered{$to_kick});
2418: delete($accessed{$to_kick});
2419: $kicks++;
2420: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2421: return;
2422: }
2423:
1.599 albertel 2424: sub purge_remembered {
1.604 albertel 2425: #&logthis("Tossing ".scalar(keys(%remembered)));
2426: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2427: undef(%remembered);
2428: undef(%accessed);
1.428 albertel 2429: }
1.70 www 2430: # ------------------------------------- Read an entry from a user's environment
2431:
2432: sub userenvironment {
2433: my ($udom,$unam,@what)=@_;
1.976 raeburn 2434: my $items;
2435: foreach my $item (@what) {
2436: $items.=&escape($item).'&';
2437: }
2438: $items=~s/\&$//;
1.70 www 2439: my %returnhash=();
1.1009 raeburn 2440: my $uhome = &homeserver($unam,$udom);
2441: unless ($uhome eq 'no_host') {
2442: my @answer=split(/\&/,
2443: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2444: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2445: return %returnhash;
2446: }
1.1009 raeburn 2447: my $i;
2448: for ($i=0;$i<=$#what;$i++) {
2449: $returnhash{$what[$i]}=&unescape($answer[$i]);
2450: }
1.70 www 2451: }
2452: return %returnhash;
1.1 albertel 2453: }
2454:
1.617 albertel 2455: # ---------------------------------------------------------- Get a studentphoto
2456: sub studentphoto {
2457: my ($udom,$unam,$ext) = @_;
2458: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2459: if (defined($env{'request.course.id'})) {
1.708 raeburn 2460: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2461: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2462: return(&retrievestudentphoto($udom,$unam,$ext));
2463: } else {
2464: my ($result,$perm_reqd)=
1.707 albertel 2465: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2466: if ($result eq 'ok') {
2467: if (!($perm_reqd eq 'yes')) {
2468: return(&retrievestudentphoto($udom,$unam,$ext));
2469: }
2470: }
2471: }
2472: }
2473: } else {
2474: my ($result,$perm_reqd) =
1.707 albertel 2475: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2476: if ($result eq 'ok') {
2477: if (!($perm_reqd eq 'yes')) {
2478: return(&retrievestudentphoto($udom,$unam,$ext));
2479: }
2480: }
2481: }
2482: return '/adm/lonKaputt/lonlogo_broken.gif';
2483: }
2484:
2485: sub retrievestudentphoto {
2486: my ($udom,$unam,$ext,$type) = @_;
2487: my $home=&Apache::lonnet::homeserver($unam,$udom);
2488: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2489: if ($ret eq 'ok') {
2490: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2491: if ($type eq 'thumbnail') {
2492: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2493: }
2494: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2495: return $tokenurl;
2496: } else {
2497: if ($type eq 'thumbnail') {
2498: return '/adm/lonKaputt/genericstudent_tn.gif';
2499: } else {
2500: return '/adm/lonKaputt/lonlogo_broken.gif';
2501: }
1.617 albertel 2502: }
2503: }
2504:
1.263 www 2505: # -------------------------------------------------------------------- New chat
2506:
2507: sub chatsend {
1.724 raeburn 2508: my ($newentry,$anon,$group)=@_;
1.620 albertel 2509: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2510: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2511: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2512: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2513: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2514: &escape($newentry)).':'.$group,$chome);
1.292 www 2515: }
2516:
2517: # ------------------------------------------ Find current version of a resource
2518:
2519: sub getversion {
2520: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2521: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2522: return ¤tversion(&filelocation('',$fname));
2523: }
2524:
2525: sub currentversion {
2526: my $fname=shift;
2527: my $author=$fname;
2528: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2529: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2530: my $home=&homeserver($uname,$udom);
1.292 www 2531: if ($home eq 'no_host') {
2532: return -1;
2533: }
1.1112 www 2534: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2535: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2536: return -1;
2537: }
1.1112 www 2538: return $answer;
1.263 www 2539: }
2540:
1.1111 www 2541: #
2542: # Return special version number of resource if set by override, empty otherwise
2543: #
2544: sub usedversion {
2545: my $fname=shift;
2546: unless ($fname) { $fname=$env{'request.uri'}; }
2547: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2548: if ($urlversion) { return $urlversion; }
2549: return '';
2550: }
2551:
1.1 albertel 2552: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2553:
1.1 albertel 2554: sub subscribe {
2555: my $fname=shift;
1.761 raeburn 2556: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2557: $fname=~s/[\n\r]//g;
1.1 albertel 2558: my $author=$fname;
2559: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2560: my ($udom,$uname)=split(/\//,$author);
2561: my $home=homeserver($uname,$udom);
1.335 albertel 2562: if ($home eq 'no_host') {
2563: return 'not_found';
1.1 albertel 2564: }
2565: my $answer=reply("sub:$fname",$home);
1.64 www 2566: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2567: $answer.=' by '.$home;
2568: }
1.1 albertel 2569: return $answer;
2570: }
2571:
1.8 www 2572: # -------------------------------------------------------------- Replicate file
2573:
2574: sub repcopy {
2575: my $filename=shift;
1.23 www 2576: $filename=~s/\/+/\//g;
1.1142 raeburn 2577: my $londocroot = $perlvar{'lonDocRoot'};
2578: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2579: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2580: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2581: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2582: return &repcopy_userfile($filename);
2583: }
1.532 albertel 2584: $filename=~s/[\n\r]//g;
1.8 www 2585: my $transname="$filename.in.transfer";
1.828 www 2586: # FIXME: this should flock
1.607 raeburn 2587: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2588: my $remoteurl=subscribe($filename);
1.64 www 2589: if ($remoteurl =~ /^con_lost by/) {
2590: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2591: return 'unavailable';
1.8 www 2592: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2593: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2594: return 'not_found';
1.64 www 2595: } elsif ($remoteurl =~ /^rejected by/) {
2596: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2597: return 'forbidden';
1.20 www 2598: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2599: return 'ok';
1.8 www 2600: } else {
1.290 www 2601: my $author=$filename;
2602: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2603: my ($udom,$uname)=split(/\//,$author);
2604: my $home=homeserver($uname,$udom);
2605: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2606: my @parts=split(/\//,$filename);
2607: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2608: if ($path ne "$londocroot/res") {
1.8 www 2609: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2610: return 'bad_request';
1.8 www 2611: }
2612: my $count;
2613: for ($count=5;$count<$#parts;$count++) {
2614: $path.="/$parts[$count]";
2615: if ((-e $path)!=1) {
2616: mkdir($path,0777);
2617: }
2618: }
2619: my $ua=new LWP::UserAgent;
2620: my $request=new HTTP::Request('GET',"$remoteurl");
2621: my $response=$ua->request($request,$transname);
2622: if ($response->is_error()) {
2623: unlink($transname);
2624: my $message=$response->status_line;
1.672 albertel 2625: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2626: ." LWP get: $message: $filename</font>");
1.607 raeburn 2627: return 'unavailable';
1.8 www 2628: } else {
1.16 www 2629: if ($remoteurl!~/\.meta$/) {
2630: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2631: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2632: if ($mresponse->is_error()) {
2633: unlink($filename.'.meta');
2634: &logthis(
1.672 albertel 2635: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2636: }
2637: }
1.8 www 2638: rename($transname,$filename);
1.607 raeburn 2639: return 'ok';
1.8 www 2640: }
1.290 www 2641: }
1.8 www 2642: }
1.330 www 2643: }
2644:
2645: # ------------------------------------------------ Get server side include body
2646: sub ssi_body {
1.381 albertel 2647: my ($filelink,%form)=@_;
1.606 matthew 2648: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2649: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2650: }
1.953 www 2651: my $output='';
2652: my $response;
1.980 raeburn 2653: if ($filelink=~/^https?\:/) {
1.954 raeburn 2654: ($output,$response)=&externalssi($filelink);
1.953 www 2655: } else {
1.1004 droeschl 2656: $filelink .= $filelink=~/\?/ ? '&' : '?';
2657: $filelink .= 'inhibitmenu=yes';
1.953 www 2658: ($output,$response)=&ssi($filelink,%form);
2659: }
1.778 albertel 2660: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2661: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2662: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2663: if (wantarray) {
2664: return ($output, $response);
2665: } else {
2666: return $output;
2667: }
1.8 www 2668: }
2669:
1.15 www 2670: # --------------------------------------------------------- Server Side Include
2671:
1.782 albertel 2672: sub absolute_url {
2673: my ($host_name) = @_;
2674: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2675: if ($host_name eq '') {
2676: $host_name = $ENV{'SERVER_NAME'};
2677: }
2678: return $protocol.$host_name;
2679: }
2680:
1.942 foxr 2681: #
2682: # Server side include.
2683: # Parameters:
2684: # fn Possibly encrypted resource name/id.
2685: # form Hash that describes how the rendering should be done
2686: # and other things.
1.944 foxr 2687: # Returns:
1.950 raeburn 2688: # Scalar context: The content of the response.
2689: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2690: #
1.15 www 2691: sub ssi {
2692:
1.944 foxr 2693: my ($fn,%form)=@_;
1.15 www 2694: my $ua=new LWP::UserAgent;
1.23 www 2695: my $request;
1.711 albertel 2696:
2697: $form{'no_update_last_known'}=1;
1.895 albertel 2698: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2699: if (%form) {
1.782 albertel 2700: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2701: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2702: } else {
1.782 albertel 2703: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2704: }
2705:
1.15 www 2706: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2707: my $response= $ua->request($request);
1.944 foxr 2708: if (wantarray) {
1.1172.2.3 raeburn 2709: return ($response->content, $response);
1.944 foxr 2710: } else {
1.1172.2.3 raeburn 2711: return $response->content;
1.942 foxr 2712: }
1.324 www 2713: }
2714:
2715: sub externalssi {
2716: my ($url)=@_;
2717: my $ua=new LWP::UserAgent;
2718: my $request=new HTTP::Request('GET',$url);
2719: my $response=$ua->request($request);
1.954 raeburn 2720: if (wantarray) {
2721: return ($response->content, $response);
2722: } else {
2723: return $response->content;
2724: }
1.15 www 2725: }
1.254 www 2726:
1.492 albertel 2727: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2728:
2729: sub allowuploaded {
2730: my ($srcurl,$url)=@_;
2731: $url=&clutter(&declutter($url));
2732: my $dir=$url;
2733: $dir=~s/\/[^\/]+$//;
2734: my %httpref=();
2735: my $httpurl=&hreflocation('',$url);
2736: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2737: &Apache::lonnet::appenv(\%httpref);
1.254 www 2738: }
1.477 raeburn 2739:
1.1172.2.13 raeburn 2740: #
2741: # Determine if the current user should be able to edit a particular resource,
2742: # when viewing in course context.
2743: # (a) When viewing resource used to determine if "Edit" item is included in
2744: # Functions.
2745: # (b) When displaying folder contents in course editor, used to determine if
2746: # "Edit" link will be displayed alongside resource.
2747: #
2748: # input: six args -- filename (decluttered), course number, course domain,
2749: # url, symb (if registered) and group (if this is a group
2750: # item -- e.g., bulletin board, group page etc.).
2751: # output: array of five scalars --
2752: # $cfile -- url for file editing if editable on current server
2753: # $home -- homeserver of resource (i.e., for author if published,
2754: # or course if uploaded.).
2755: # $switchserver -- 1 if server switch will be needed.
2756: # $forceedit -- 1 if icon/link should be to go to edit mode
2757: # $forceview -- 1 if icon/link should be to go to view mode
2758: #
2759:
2760: sub can_edit_resource {
2761: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2762: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2763: #
2764: # For aboutme pages user can only edit his/her own.
2765: #
2766: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2767: my ($sdom,$sname) = ($1,$2);
2768: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2769: $home = $env{'user.home'};
2770: $cfile = $resurl;
2771: if ($env{'form.forceedit'}) {
2772: $forceview = 1;
2773: } else {
2774: $forceedit = 1;
2775: }
2776: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2777: } else {
2778: return;
2779: }
2780: }
2781:
2782: if ($env{'request.course.id'}) {
2783: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2784: if ($group ne '') {
2785: # if this is a group homepage or group bulletin board, check group privs
2786: my $allowed = 0;
2787: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2788: if ((&allowed('mdg',$env{'request.course.id'}.
2789: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2790: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2791: $allowed = 1;
2792: }
2793: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2794: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2795: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2796: $allowed = 1;
2797: }
2798: }
2799: if ($allowed) {
2800: $home=&homeserver($cnum,$cdom);
2801: if ($env{'form.forceedit'}) {
2802: $forceview = 1;
2803: } else {
2804: $forceedit = 1;
2805: }
2806: $cfile = $resurl;
2807: } else {
2808: return;
2809: }
2810: } else {
1.1172.2.15 raeburn 2811: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2812: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2813: return;
2814: }
2815: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2816: #
2817: # No edit allowed where CC has switched to student role.
2818: #
2819: return;
2820: }
2821: }
2822: }
2823:
2824: if ($file ne '') {
2825: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2826: if (&is_course_upload($file,$cnum,$cdom)) {
2827: $uploaded = 1;
2828: $incourse = 1;
2829: if ($file =~/\.(htm|html|css|js|txt)$/) {
2830: $cfile = &hreflocation('',$file);
2831: if ($env{'form.forceedit'}) {
2832: $forceview = 1;
2833: } else {
2834: $forceedit = 1;
2835: }
2836: }
2837: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2838: $incourse = 1;
2839: if ($env{'form.forceedit'}) {
2840: $forceview = 1;
2841: } else {
2842: $forceedit = 1;
2843: }
2844: $cfile = $resurl;
2845: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2846: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2847: $incourse = 1;
2848: if ($env{'form.forceedit'}) {
2849: $forceview = 1;
2850: } else {
2851: $forceedit = 1;
2852: }
2853: $cfile = $resurl;
2854: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2855: $incourse = 1;
2856: $cfile = $resurl.'/smpedit';
2857: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2858: $incourse = 1;
2859: if ($env{'form.forceedit'}) {
2860: $forceview = 1;
2861: } else {
2862: $forceedit = 1;
2863: }
2864: $cfile = $resurl;
1.1172.2.15 raeburn 2865: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2866: $incourse = 1;
2867: if ($env{'form.forceedit'}) {
2868: $forceview = 1;
2869: } else {
2870: $forceedit = 1;
2871: }
2872: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2873: }
2874: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2875: my $template = '/res/lib/templates/simpleproblem.problem';
2876: if (&is_on_map($template)) {
2877: $incourse = 1;
2878: $forceview = 1;
2879: $cfile = $template;
2880: }
2881: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2882: $incourse = 1;
2883: if ($env{'form.forceedit'}) {
2884: $forceview = 1;
2885: } else {
2886: $forceedit = 1;
2887: }
2888: $cfile = $resurl;
2889: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2890: $incourse = 1;
2891: $forceview = 1;
2892: if ($symb) {
2893: my ($map,$id,$res)=&decode_symb($symb);
2894: $env{'request.symb'} = $symb;
2895: $cfile = &clutter($res);
2896: } else {
2897: $cfile = $env{'form.suppurl'};
2898: $cfile =~ s{^http://}{};
2899: $cfile = '/adm/wrapper/ext/'.$cfile;
2900: }
1.1172.2.31 raeburn 2901: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2902: if ($env{'form.forceedit'}) {
2903: $forceview = 1;
2904: } else {
2905: $forceedit = 1;
2906: }
2907: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2908: }
2909: }
2910: if ($uploaded || $incourse) {
2911: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2912: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2913: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2914: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2915: # Check that the user has permission to edit this resource
2916: my $setpriv = 1;
2917: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2918: if (defined($cfudom)) {
2919: $home=&homeserver($cfuname,$cfudom);
2920: $cfile=$file;
2921: }
2922: }
2923: if (($cfile ne '') && (!$incourse || $uploaded) &&
2924: (($home ne '') && ($home ne 'no_host'))) {
2925: my @ids=¤t_machine_ids();
2926: unless (grep(/^\Q$home\E$/,@ids)) {
2927: $switchserver=1;
2928: }
2929: }
2930: }
2931: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2932: }
2933:
2934: sub is_course_upload {
2935: my ($file,$cnum,$cdom) = @_;
2936: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2937: $uploadpath =~ s{^\/}{};
2938: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2939: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2940: return 1;
2941: }
2942: return;
2943: }
2944:
2945: sub in_course {
2946: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2947: if ($hideprivileged) {
2948: my $skipuser;
1.1172.2.23 raeburn 2949: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2950: my @possdoms = ($cdom);
2951: if ($coursehash{'checkforpriv'}) {
2952: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2953: }
2954: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2955: $skipuser = 1;
2956: if ($coursehash{'nothideprivileged'}) {
2957: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2958: my $user;
2959: if ($item =~ /:/) {
2960: $user = $item;
2961: } else {
2962: $user = join(':',split(/[\@]/,$item));
2963: }
2964: if ($user eq $uname.':'.$udom) {
2965: undef($skipuser);
2966: last;
2967: }
2968: }
2969: }
2970: if ($skipuser) {
2971: return 0;
2972: }
2973: }
2974: }
2975: $type ||= 'any';
2976: if (!defined($cdom) || !defined($cnum)) {
2977: my $cid = $env{'request.course.id'};
2978: $cdom = $env{'course.'.$cid.'.domain'};
2979: $cnum = $env{'course.'.$cid.'.num'};
2980: }
2981: my $typesref;
2982: if (($type eq 'any') || ($type eq 'all')) {
2983: $typesref = ['active','previous','future'];
2984: } elsif ($type eq 'previous' || $type eq 'future') {
2985: $typesref = [$type];
2986: }
2987: my %roles = &get_my_roles($uname,$udom,'userroles',
2988: $typesref,undef,[$cdom]);
2989: my ($tmp) = keys(%roles);
2990: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2991: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2992: if (@course_roles > 0) {
2993: return 1;
2994: }
2995: return 0;
2996: }
2997:
1.478 albertel 2998: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2999: # input: action, courseID, current domain, intended
1.637 raeburn 3000: # path to file, source of file, instruction to parse file for objects,
3001: # ref to hash for embedded objects,
3002: # ref to hash for codebase of java objects.
1.1095 raeburn 3003: # reference to scalar to accommodate mime type determined
3004: # from File::MMagic if $parser = parse.
1.637 raeburn 3005: #
1.485 raeburn 3006: # output: url to file (if action was uploaddoc),
3007: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3008: #
1.478 albertel 3009: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3010: # course.
1.477 raeburn 3011: #
1.478 albertel 3012: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3013: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3014: # course's home server.
1.477 raeburn 3015: #
1.478 albertel 3016: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3017: # be copied from $source (current location) to
3018: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3019: # and will then be copied to
3020: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3021: # course's home server.
1.485 raeburn 3022: #
1.481 raeburn 3023: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3024: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3025: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3026: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3027: # in course's home server.
1.637 raeburn 3028: #
1.477 raeburn 3029:
3030: sub process_coursefile {
1.1095 raeburn 3031: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3032: $mimetype)=@_;
1.477 raeburn 3033: my $fetchresult;
1.638 albertel 3034: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3035: if ($action eq 'propagate') {
1.638 albertel 3036: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3037: $home);
1.481 raeburn 3038: } else {
1.477 raeburn 3039: my $fpath = '';
3040: my $fname = $file;
1.478 albertel 3041: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3042: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3043: my $filepath = &build_filepath($fpath);
1.481 raeburn 3044: if ($action eq 'copy') {
3045: if ($source eq '') {
3046: $fetchresult = 'no source file';
3047: return $fetchresult;
3048: } else {
3049: my $destination = $filepath.'/'.$fname;
3050: rename($source,$destination);
3051: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3052: $home);
1.481 raeburn 3053: }
3054: } elsif ($action eq 'uploaddoc') {
3055: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3056: print $fh $env{'form.'.$source};
1.481 raeburn 3057: close($fh);
1.637 raeburn 3058: if ($parser eq 'parse') {
1.1024 raeburn 3059: my $mm = new File::MMagic;
1.1095 raeburn 3060: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3061: if ($type eq 'text/html') {
1.1024 raeburn 3062: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3063: unless ($parse_result eq 'ok') {
3064: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3065: }
1.637 raeburn 3066: }
1.1095 raeburn 3067: if (ref($mimetype)) {
3068: $$mimetype = $type;
3069: }
1.637 raeburn 3070: }
1.477 raeburn 3071: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3072: $home);
1.481 raeburn 3073: if ($fetchresult eq 'ok') {
3074: return '/uploaded/'.$fpath.'/'.$fname;
3075: } else {
3076: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3077: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3078: return '/adm/notfound.html';
3079: }
1.477 raeburn 3080: }
3081: }
1.485 raeburn 3082: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3083: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3084: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3085: }
3086: return $fetchresult;
3087: }
3088:
1.637 raeburn 3089: sub build_filepath {
3090: my ($fpath) = @_;
3091: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3092: unless ($fpath eq '') {
3093: my @parts=split('/',$fpath);
3094: foreach my $part (@parts) {
3095: $filepath.= '/'.$part;
3096: if ((-e $filepath)!=1) {
3097: mkdir($filepath,0777);
3098: }
3099: }
3100: }
3101: return $filepath;
3102: }
3103:
3104: sub store_edited_file {
1.638 albertel 3105: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3106: my $file = $primary_url;
3107: $file =~ s#^/uploaded/$docudom/$docuname/##;
3108: my $fpath = '';
3109: my $fname = $file;
3110: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3111: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3112: my $filepath = &build_filepath($fpath);
3113: open(my $fh,'>'.$filepath.'/'.$fname);
3114: print $fh $content;
3115: close($fh);
1.638 albertel 3116: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3117: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3118: $home);
1.637 raeburn 3119: if ($$fetchresult eq 'ok') {
3120: return '/uploaded/'.$fpath.'/'.$fname;
3121: } else {
1.638 albertel 3122: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3123: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3124: return '/adm/notfound.html';
3125: }
3126: }
3127:
1.531 albertel 3128: sub clean_filename {
1.831 albertel 3129: my ($fname,$args)=@_;
1.315 www 3130: # Replace Windows backslashes by forward slashes
1.257 www 3131: $fname=~s/\\/\//g;
1.831 albertel 3132: if (!$args->{'keep_path'}) {
3133: # Get rid of everything but the actual filename
3134: $fname=~s/^.*\/([^\/]+)$/$1/;
3135: }
1.315 www 3136: # Replace spaces by underscores
3137: $fname=~s/\s+/\_/g;
3138: # Replace all other weird characters by nothing
1.831 albertel 3139: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3140: # Replace all .\d. sequences with _\d. so they no longer look like version
3141: # numbers
3142: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3143: return $fname;
3144: }
1.1051 raeburn 3145: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3146: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3147: # image with the same aspect ratio as the original, but with dimensions which do
3148: # not exceed $resizewidth and $resizeheight.
3149:
1.984 neumanie 3150: sub resizeImage {
1.1051 raeburn 3151: my ($img_path,$resizewidth,$resizeheight) = @_;
3152: my $ima = Image::Magick->new;
3153: my $resized;
3154: if (-e $img_path) {
3155: $ima->Read($img_path);
3156: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3157: my $width = $ima->Get('width');
3158: my $height = $ima->Get('height');
3159: if ($width > $resizewidth) {
3160: my $factor = $width/$resizewidth;
3161: my $newheight = $height/$factor;
3162: $ima->Scale(width=>$resizewidth,height=>$newheight);
3163: $resized = 1;
3164: }
3165: }
3166: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3167: my $width = $ima->Get('width');
3168: my $height = $ima->Get('height');
3169: if ($height > $resizeheight) {
3170: my $factor = $height/$resizeheight;
3171: my $newwidth = $width/$factor;
3172: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3173: $resized = 1;
3174: }
3175: }
3176: if ($resized) {
3177: $ima->Write($img_path);
3178: }
3179: }
3180: return;
1.977 amueller 3181: }
3182:
1.608 albertel 3183: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3184: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3185: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3186: # $context - possible values: coursedoc, existingfile, overwrite,
3187: # canceloverwrite, or ''.
3188: # if 'coursedoc': upload to the current course
3189: # if 'existingfile': write file to tmp/overwrites directory
3190: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3191: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3192: # $subdir - directory in userfile to store the file into
1.858 raeburn 3193: # $parser - instruction to parse file for objects ($parser = parse)
3194: # $allfiles - reference to hash for embedded objects
3195: # $codebase - reference to hash for codebase of java objects
3196: # $desuname - username for permanent storage of uploaded file
3197: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3198: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3199: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3200: # $resizewidth - width (pixels) to which to resize uploaded image
3201: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3202: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3203: # from File::MMagic.
1.858 raeburn 3204: #
1.686 albertel 3205: # output: url of file in userspace, or error: <message>
3206: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3207:
1.531 albertel 3208: sub userfileupload {
1.1090 raeburn 3209: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3210: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3211: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3212: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3213: $fname=&clean_filename($fname);
1.1090 raeburn 3214: # See if there is anything left
1.257 www 3215: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3216: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3217: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3218: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3219: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3220: my $now = time;
1.1090 raeburn 3221: my $filepath;
1.1095 raeburn 3222: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3223: $filepath = 'tmp/helprequests/'.$now;
3224: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3225: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3226: '_'.$env{'user.domain'}.'/pending';
3227: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3228: my ($docuname,$docudom);
3229: if ($destudom) {
3230: $docudom = $destudom;
3231: } else {
3232: $docudom = $env{'user.domain'};
3233: }
3234: if ($destuname) {
3235: $docuname = $destuname;
3236: } else {
3237: $docuname = $env{'user.name'};
3238: }
3239: if (exists($env{'form.group'})) {
3240: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3241: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3242: }
3243: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3244: if ($context eq 'canceloverwrite') {
3245: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3246: if (-e $tempfile) {
3247: my @info = stat($tempfile);
3248: if ($info[9] eq $env{'form.timestamp'}) {
3249: unlink($tempfile);
3250: }
3251: }
3252: return;
1.523 raeburn 3253: }
3254: }
1.1090 raeburn 3255: # Create the directory if not present
1.741 raeburn 3256: my @parts=split(/\//,$filepath);
3257: my $fullpath = $perlvar{'lonDaemons'};
3258: for (my $i=0;$i<@parts;$i++) {
3259: $fullpath .= '/'.$parts[$i];
3260: if ((-e $fullpath)!=1) {
3261: mkdir($fullpath,0777);
3262: }
3263: }
3264: open(my $fh,'>'.$fullpath.'/'.$fname);
3265: print $fh $env{'form.'.$formname};
3266: close($fh);
1.1090 raeburn 3267: if ($context eq 'existingfile') {
3268: my @info = stat($fullpath.'/'.$fname);
3269: return ($fullpath.'/'.$fname,$info[9]);
3270: } else {
3271: return $fullpath.'/'.$fname;
3272: }
1.523 raeburn 3273: }
1.995 raeburn 3274: if ($subdir eq 'scantron') {
3275: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3276: } else {
1.995 raeburn 3277: $fname="$subdir/$fname";
3278: }
1.1090 raeburn 3279: if ($context eq 'coursedoc') {
1.638 albertel 3280: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3281: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3282: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3283: return &finishuserfileupload($docuname,$docudom,
3284: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3285: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3286: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3287: } else {
1.1172.2.21 raeburn 3288: if ($env{'form.folder'}) {
3289: $fname=$env{'form.folder'}.'/'.$fname;
3290: }
1.638 albertel 3291: return &process_coursefile('uploaddoc',$docuname,$docudom,
3292: $fname,$formname,$parser,
1.1095 raeburn 3293: $allfiles,$codebase,$mimetype);
1.481 raeburn 3294: }
1.719 banghart 3295: } elsif (defined($destuname)) {
3296: my $docuname=$destuname;
3297: my $docudom=$destudom;
1.860 raeburn 3298: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3299: $parser,$allfiles,$codebase,
1.1051 raeburn 3300: $thumbwidth,$thumbheight,
1.1095 raeburn 3301: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3302: } else {
1.638 albertel 3303: my $docuname=$env{'user.name'};
3304: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3305: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3306: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3307: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3308: }
1.860 raeburn 3309: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3310: $parser,$allfiles,$codebase,
1.1051 raeburn 3311: $thumbwidth,$thumbheight,
1.1095 raeburn 3312: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3313: }
1.271 www 3314: }
3315:
3316: sub finishuserfileupload {
1.860 raeburn 3317: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3318: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3319: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3320: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3321:
1.860 raeburn 3322: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3323: $file=$fname;
3324: if ($fname=~m|/|) {
3325: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3326: $path.=$fnamepath.'/';
3327: }
1.259 www 3328: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3329: my $count;
3330: for ($count=4;$count<=$#parts;$count++) {
3331: $filepath.="/$parts[$count]";
3332: if ((-e $filepath)!=1) {
3333: mkdir($filepath,0777);
3334: }
3335: }
1.984 neumanie 3336:
1.258 www 3337: # Save the file
3338: {
1.701 albertel 3339: if (!open(FH,'>'.$filepath.'/'.$file)) {
3340: &logthis('Failed to create '.$filepath.'/'.$file);
3341: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3342: return '/adm/notfound.html';
3343: }
1.1090 raeburn 3344: if ($context eq 'overwrite') {
1.1117 foxr 3345: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3346: my $target = $filepath.'/'.$file;
3347: if (-e $source) {
3348: my @info = stat($source);
3349: if ($info[9] eq $env{'form.timestamp'}) {
3350: unless (&File::Copy::move($source,$target)) {
3351: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3352: return "Moving from $source failed";
3353: }
3354: } else {
3355: return "Temporary file: $source had unexpected date/time for last modification";
3356: }
3357: } else {
3358: return "Temporary file: $source missing";
3359: }
3360: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3361: &logthis('Failed to write to '.$filepath.'/'.$file);
3362: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3363: return '/adm/notfound.html';
3364: }
1.570 albertel 3365: close(FH);
1.1051 raeburn 3366: if ($resizewidth && $resizeheight) {
3367: my $mm = new File::MMagic;
3368: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3369: if ($mime_type =~ m{^image/}) {
3370: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3371: }
1.977 amueller 3372: }
1.258 www 3373: }
1.1152 raeburn 3374: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3375: if (ref($mimetype)) {
3376: if ($$mimetype eq '') {
3377: my $mm = new File::MMagic;
3378: my $type = $mm->checktype_filename($filepath.'/'.$file);
3379: $$mimetype = $type;
3380: }
3381: }
3382: }
1.637 raeburn 3383: if ($parser eq 'parse') {
1.1152 raeburn 3384: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3385: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3386: $allfiles,$codebase);
3387: unless ($parse_result eq 'ok') {
3388: &logthis('Failed to parse '.$filepath.$file.
3389: ' for embedded media: '.$parse_result);
3390: }
1.637 raeburn 3391: }
3392: }
1.860 raeburn 3393: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3394: my $input = $filepath.'/'.$file;
3395: my $output = $filepath.'/'.'tn-'.$file;
3396: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3397: system("convert -sample $thumbsize $input $output");
3398: if (-e $filepath.'/'.'tn-'.$file) {
3399: $fetchthumb = 1;
3400: }
3401: }
1.858 raeburn 3402:
1.259 www 3403: # Notify homeserver to grep it
3404: #
1.984 neumanie 3405: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3406: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3407: if ($fetchresult eq 'ok') {
1.860 raeburn 3408: if ($fetchthumb) {
3409: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3410: if ($thumbresult ne 'ok') {
3411: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3412: $docuhome.': '.$thumbresult);
3413: }
3414: }
1.259 www 3415: #
1.258 www 3416: # Return the URL to it
1.494 albertel 3417: return '/uploaded/'.$path.$file;
1.263 www 3418: } else {
1.494 albertel 3419: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3420: ': '.$fetchresult);
1.263 www 3421: return '/adm/notfound.html';
1.858 raeburn 3422: }
1.493 albertel 3423: }
3424:
1.637 raeburn 3425: sub extract_embedded_items {
1.961 raeburn 3426: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3427: my @state = ();
1.1164 raeburn 3428: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3429: my %javafiles = (
3430: codebase => '',
3431: code => '',
3432: archive => ''
3433: );
3434: my %mediafiles = (
3435: src => '',
3436: movie => '',
3437: );
1.648 raeburn 3438: my $p;
3439: if ($content) {
3440: $p = HTML::LCParser->new($content);
3441: } else {
1.961 raeburn 3442: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3443: }
1.641 albertel 3444: while (my $t=$p->get_token()) {
1.640 albertel 3445: if ($t->[0] eq 'S') {
3446: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3447: push(@state, $tagname);
1.648 raeburn 3448: if (lc($tagname) eq 'allow') {
3449: &add_filetype($allfiles,$attr->{'src'},'src');
3450: }
1.640 albertel 3451: if (lc($tagname) eq 'img') {
3452: &add_filetype($allfiles,$attr->{'src'},'src');
3453: }
1.886 albertel 3454: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3455: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3456: &add_filetype($allfiles,$attr->{'href'},'href');
3457: }
1.886 albertel 3458: }
1.645 raeburn 3459: if (lc($tagname) eq 'script') {
1.1164 raeburn 3460: my $src;
1.645 raeburn 3461: if ($attr->{'archive'} =~ /\.jar$/i) {
3462: &add_filetype($allfiles,$attr->{'archive'},'archive');
3463: } else {
1.1164 raeburn 3464: if ($attr->{'src'} ne '') {
3465: $src = $attr->{'src'};
3466: &add_filetype($allfiles,$src,'src');
3467: }
3468: }
3469: my $text = $p->get_trimmed_text();
3470: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3471: my @swfargs = split(/,/,$1);
3472: foreach my $item (@swfargs) {
3473: $item =~ s/["']//g;
3474: $item =~ s/^\s+//;
3475: $item =~ s/\s+$//;
3476: }
3477: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3478: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3479: push(@{$related{$swfargs[0]}},$swfargs[2]);
3480: } else {
3481: $related{$swfargs[0]} = [$swfargs[2]];
3482: }
3483: }
1.645 raeburn 3484: }
3485: }
3486: if (lc($tagname) eq 'link') {
3487: if (lc($attr->{'rel'}) eq 'stylesheet') {
3488: &add_filetype($allfiles,$attr->{'href'},'href');
3489: }
3490: }
1.640 albertel 3491: if (lc($tagname) eq 'object' ||
3492: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3493: foreach my $item (keys(%javafiles)) {
3494: $javafiles{$item} = '';
3495: }
1.1164 raeburn 3496: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3497: $lastids{lc($tagname)} = $attr->{'id'};
3498: }
1.640 albertel 3499: }
3500: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3501: my $name = lc($attr->{'name'});
3502: foreach my $item (keys(%javafiles)) {
3503: if ($name eq $item) {
3504: $javafiles{$item} = $attr->{'value'};
3505: last;
3506: }
3507: }
1.1164 raeburn 3508: my $pathfrom;
1.640 albertel 3509: foreach my $item (keys(%mediafiles)) {
3510: if ($name eq $item) {
1.1164 raeburn 3511: $pathfrom = $attr->{'value'};
3512: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3513: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3514: last;
3515: }
3516: }
1.1164 raeburn 3517: if ($name eq 'flashvars') {
3518: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3519: }
3520: if ($pathfrom ne '') {
3521: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3522: $pathfrom);
3523: }
1.640 albertel 3524: }
3525: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3526: foreach my $item (keys(%javafiles)) {
3527: if ($attr->{$item}) {
3528: $javafiles{$item} = $attr->{$item};
3529: last;
3530: }
3531: }
3532: foreach my $item (keys(%mediafiles)) {
3533: if ($attr->{$item}) {
3534: &add_filetype($allfiles,$attr->{$item},$item);
3535: last;
3536: }
3537: }
1.1164 raeburn 3538: if (lc($tagname) eq 'embed') {
3539: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3540: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3541: $attr->{'src'});
3542: }
3543: }
1.640 albertel 3544: }
1.1172.2.35 raeburn 3545: if (lc($tagname) eq 'iframe') {
3546: my $src = $attr->{'src'} ;
3547: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3548: &add_filetype($allfiles,$src,'src');
3549: } elsif ($src =~ m{^/}) {
3550: if ($env{'request.course.id'}) {
3551: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3552: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3553: my $url = &hreflocation('',$fullpath);
3554: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3555: my $relpath = $1;
3556: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3557: &add_filetype($allfiles,$1,'src');
3558: }
3559: }
3560: }
3561: }
3562: }
1.1164 raeburn 3563: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3564: pop(@state);
1.1164 raeburn 3565: }
1.640 albertel 3566: } elsif ($t->[0] eq 'E') {
3567: my ($tagname) = ($t->[1]);
3568: if ($javafiles{'codebase'} ne '') {
3569: $javafiles{'codebase'} .= '/';
3570: }
3571: if (lc($tagname) eq 'applet' ||
3572: lc($tagname) eq 'object' ||
3573: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3574: ) {
3575: foreach my $item (keys(%javafiles)) {
3576: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3577: my $file=$javafiles{'codebase'}.$javafiles{$item};
3578: &add_filetype($allfiles,$file,$item);
3579: }
3580: }
3581: }
3582: pop @state;
3583: }
3584: }
1.1164 raeburn 3585: foreach my $id (sort(keys(%flashvars))) {
3586: if ($shockwave{$id} ne '') {
3587: my @pairs = split(/\&/,$flashvars{$id});
3588: foreach my $pair (@pairs) {
3589: my ($key,$value) = split(/\=/,$pair);
3590: if ($key eq 'thumb') {
3591: &add_filetype($allfiles,$value,$key);
3592: } elsif ($key eq 'content') {
3593: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3594: my ($ext) = ($value =~ /\.([^.]+)$/);
3595: if ($ext ne '') {
3596: &add_filetype($allfiles,$path.$value,$ext);
3597: }
3598: }
3599: }
3600: }
3601: }
1.637 raeburn 3602: return 'ok';
3603: }
3604:
1.639 albertel 3605: sub add_filetype {
3606: my ($allfiles,$file,$type)=@_;
3607: if (exists($allfiles->{$file})) {
3608: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3609: push(@{$allfiles->{$file}}, &escape($type));
3610: }
3611: } else {
3612: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3613: }
3614: }
3615:
1.1164 raeburn 3616: sub embedded_dependency {
3617: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3618: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3619: if (($identifier ne '') &&
3620: (ref($related->{$identifier}) eq 'ARRAY') &&
3621: ($pathfrom ne '')) {
3622: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3623: foreach my $dep (@{$related->{$identifier}}) {
3624: &add_filetype($allfiles,$path.$dep,'object');
3625: }
3626: }
3627: }
3628: return;
3629: }
3630:
1.493 albertel 3631: sub removeuploadedurl {
1.984 neumanie 3632: my ($url)=@_;
3633: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3634: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3635: }
3636:
3637: sub removeuserfile {
3638: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3639: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3640: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3641: if ($result eq 'ok') {
1.798 raeburn 3642: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3643: my $metafile = $fname.'.meta';
3644: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3645: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3646: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3647: my $sqlresult =
1.823 albertel 3648: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3649: 'portfolio_metadata',$group,
3650: 'delete');
1.798 raeburn 3651: }
3652: }
3653: return $result;
1.257 www 3654: }
1.15 www 3655:
1.530 albertel 3656: sub mkdiruserfile {
3657: my ($docuname,$docudom,$dir)=@_;
3658: my $home=&homeserver($docuname,$docudom);
3659: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3660: }
3661:
1.531 albertel 3662: sub renameuserfile {
3663: my ($docuname,$docudom,$old,$new)=@_;
3664: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3665: my $result = &reply("renameuserfile:$docudom:$docuname:".
3666: &escape("$old").':'.&escape("$new"),$home);
3667: if ($result eq 'ok') {
3668: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3669: my $oldmeta = $old.'.meta';
3670: my $newmeta = $new.'.meta';
3671: my $metaresult =
3672: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3673: my $url = "/uploaded/$docudom/$docuname/$old";
3674: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3675: my $sqlresult =
1.823 albertel 3676: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3677: 'portfolio_metadata',$group,
3678: 'delete');
1.798 raeburn 3679: }
3680: }
3681: return $result;
1.531 albertel 3682: }
3683:
1.14 www 3684: # ------------------------------------------------------------------------- Log
3685:
3686: sub log {
3687: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3688: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3689: }
3690:
3691: # ------------------------------------------------------------------ Course Log
1.352 www 3692: #
3693: # This routine flushes several buffers of non-mission-critical nature
3694: #
1.157 www 3695:
3696: sub flushcourselogs {
1.352 www 3697: &logthis('Flushing log buffers');
3698: #
3699: # course logs
3700: # This is a log of all transactions in a course, which can be used
3701: # for data mining purposes
3702: #
3703: # It also collects the courseid database, which lists last transaction
3704: # times and course titles for all courseids
3705: #
3706: my %courseidbuffer=();
1.921 raeburn 3707: foreach my $crsid (keys(%courselogs)) {
1.352 www 3708: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3709: &escape($courselogs{$crsid}),
3710: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3711: delete $courselogs{$crsid};
3712: } else {
3713: &logthis('Failed to flush log buffer for '.$crsid);
3714: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3715: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3716: " exceeded maximum size, deleting.</font>");
3717: delete $courselogs{$crsid};
3718: }
1.352 www 3719: }
1.920 raeburn 3720: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3721: 'description' => $coursedescrbuf{$crsid},
3722: 'inst_code' => $courseinstcodebuf{$crsid},
3723: 'type' => $coursetypebuf{$crsid},
3724: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3725: };
1.191 harris41 3726: }
1.352 www 3727: #
3728: # Write course id database (reverse lookup) to homeserver of courses
3729: # Is used in pickcourse
3730: #
1.840 albertel 3731: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3732: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3733: $courseidbuffer{$crs_home},
3734: $crs_home,'timeonly');
1.352 www 3735: }
3736: #
3737: # File accesses
3738: # Writes to the dynamic metadata of resources to get hit counts, etc.
3739: #
1.449 matthew 3740: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3741: if ($entry =~ /___count$/) {
3742: my ($dom,$name);
1.807 albertel 3743: ($dom,$name,undef)=
1.811 albertel 3744: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3745: if (! defined($dom) || $dom eq '' ||
3746: ! defined($name) || $name eq '') {
1.620 albertel 3747: my $cid = $env{'request.course.id'};
3748: $dom = $env{'request.'.$cid.'.domain'};
3749: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3750: }
1.450 matthew 3751: my $value = $accesshash{$entry};
3752: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3753: my %temphash=($url => $value);
1.449 matthew 3754: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3755: if ($result eq 'ok') {
3756: delete $accesshash{$entry};
3757: }
3758: } else {
1.811 albertel 3759: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3760: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3761: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3762: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3763: delete $accesshash{$entry};
3764: }
1.185 www 3765: }
1.191 harris41 3766: }
1.352 www 3767: #
3768: # Roles
3769: # Reverse lookup of user roles for course faculty/staff and co-authorship
3770: #
1.800 albertel 3771: foreach my $entry (keys(%userrolehash)) {
1.351 www 3772: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3773: split(/\:/,$entry);
3774: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3775: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3776: $rudom,$runame) eq 'ok') {
3777: delete $userrolehash{$entry};
3778: }
3779: }
1.662 raeburn 3780: #
3781: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3782: #
3783: my %domrolebuffer = ();
1.1000 raeburn 3784: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3785: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3786: if ($domrolebuffer{$rudom}) {
3787: $domrolebuffer{$rudom}.='&'.&escape($entry).
3788: '='.&escape($domainrolehash{$entry});
3789: } else {
3790: $domrolebuffer{$rudom}.=&escape($entry).
3791: '='.&escape($domainrolehash{$entry});
3792: }
3793: delete $domainrolehash{$entry};
3794: }
3795: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3796: my %servers = &get_servers($dom,'library');
3797: foreach my $tryserver (keys(%servers)) {
3798: unless (&reply('domroleput:'.$dom.':'.
3799: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3800: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3801: }
1.662 raeburn 3802: }
3803: }
1.186 www 3804: $dumpcount++;
1.157 www 3805: }
3806:
3807: sub courselog {
3808: my $what=shift;
1.158 www 3809: $what=time.':'.$what;
1.620 albertel 3810: unless ($env{'request.course.id'}) { return ''; }
3811: $coursedombuf{$env{'request.course.id'}}=
3812: $env{'course.'.$env{'request.course.id'}.'.domain'};
3813: $coursenumbuf{$env{'request.course.id'}}=
3814: $env{'course.'.$env{'request.course.id'}.'.num'};
3815: $coursehombuf{$env{'request.course.id'}}=
3816: $env{'course.'.$env{'request.course.id'}.'.home'};
3817: $coursedescrbuf{$env{'request.course.id'}}=
3818: $env{'course.'.$env{'request.course.id'}.'.description'};
3819: $courseinstcodebuf{$env{'request.course.id'}}=
3820: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3821: $courseownerbuf{$env{'request.course.id'}}=
3822: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3823: $coursetypebuf{$env{'request.course.id'}}=
3824: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3825: if (defined $courselogs{$env{'request.course.id'}}) {
3826: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3827: } else {
1.620 albertel 3828: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3829: }
1.620 albertel 3830: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3831: &flushcourselogs();
3832: }
1.158 www 3833: }
3834:
3835: sub courseacclog {
3836: my $fnsymb=shift;
1.620 albertel 3837: unless ($env{'request.course.id'}) { return ''; }
3838: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3839: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3840: $what.=':POST';
1.583 matthew 3841: # FIXME: Probably ought to escape things....
1.800 albertel 3842: foreach my $key (keys(%env)) {
3843: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3844: my $formitem = $1;
3845: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3846: $what.=':'.$formitem.'='.$env{$key};
3847: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3848: $what.=':'.$formitem.'='.$env{$key};
3849: }
1.158 www 3850: }
1.191 harris41 3851: }
1.583 matthew 3852: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3853: # FIXME: We should not be depending on a form parameter that someone
3854: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3855: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3856: $what.= ':POST';
3857: # FIXME: Probably ought to escape things....
3858: foreach my $element ('courseexp','crsfulltext','crsrelated',
3859: 'crsdiscuss') {
1.620 albertel 3860: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3861: }
3862: }
1.158 www 3863: }
3864: &courselog($what);
1.149 www 3865: }
3866:
1.185 www 3867: sub countacc {
3868: my $url=&declutter(shift);
1.458 matthew 3869: return if (! defined($url) || $url eq '');
1.620 albertel 3870: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3871: #
3872: # Mark that this url was used in this course
3873: #
1.620 albertel 3874: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3875: #
3876: # Increase the access count for this resource in this child process
3877: #
1.281 www 3878: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3879: $accesshash{$key}++;
1.185 www 3880: }
1.349 www 3881:
1.361 www 3882: sub linklog {
3883: my ($from,$to)=@_;
3884: $from=&declutter($from);
3885: $to=&declutter($to);
3886: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3887: $accesshash{$to.'___'.$from.'___goto'}=1;
3888: }
1.1160 www 3889:
3890: sub statslog {
3891: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3892: if ($users<2) { return; }
3893: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3894: 'course' => $env{'request.course.id'},
3895: 'sections' => '"all"',
3896: 'num_students' => $users,
3897: 'part' => $part,
3898: 'symb' => $symb,
3899: 'mean_tries' => $av_attempts,
3900: 'deg_of_diff' => $degdiff});
3901: foreach my $key (keys(%dynstore)) {
3902: $accesshash{$key}=$dynstore{$key};
3903: }
3904: }
1.361 www 3905:
1.349 www 3906: sub userrolelog {
3907: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3908: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3909: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3910: $userrolehash
3911: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3912: =$tend.':'.$tstart;
1.662 raeburn 3913: }
1.1169 droeschl 3914: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3915: $userrolehash
3916: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3917: =$tend.':'.$tstart;
3918: }
1.1169 droeschl 3919: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3920: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3921: $domainrolehash
3922: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3923: = $tend.':'.$tstart;
3924: }
1.351 www 3925: }
3926:
1.957 raeburn 3927: sub courserolelog {
3928: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3929: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3930: my $cdom = $1;
3931: my $cnum = $2;
3932: my $sec = $3;
3933: my $namespace = 'rolelog';
3934: my %storehash = (
3935: role => $trole,
3936: start => $tstart,
3937: end => $tend,
3938: selfenroll => $selfenroll,
3939: context => $context,
3940: );
3941: if ($trole eq 'gr') {
3942: $namespace = 'groupslog';
3943: $storehash{'group'} = $sec;
3944: } else {
3945: $storehash{'section'} = $sec;
3946: }
3947: &write_log('course',$namespace,\%storehash,$delflag,$username,
3948: $domain,$cnum,$cdom);
3949: if (($trole ne 'st') || ($sec ne '')) {
3950: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3951: }
3952: }
3953: return;
3954: }
3955:
1.1172.2.9 raeburn 3956: sub domainrolelog {
3957: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3958: if ($area =~ m{^/($match_domain)/$}) {
3959: my $cdom = $1;
3960: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3961: my $namespace = 'rolelog';
3962: my %storehash = (
3963: role => $trole,
3964: start => $tstart,
3965: end => $tend,
3966: context => $context,
3967: );
3968: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3969: $domain,$domconfiguser,$cdom);
3970: }
3971: return;
3972:
3973: }
3974:
3975: sub coauthorrolelog {
3976: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3977: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3978: my $audom = $1;
3979: my $auname = $2;
3980: my $namespace = 'rolelog';
3981: my %storehash = (
3982: role => $trole,
3983: start => $tstart,
3984: end => $tend,
3985: context => $context,
3986: );
3987: &write_log('author',$namespace,\%storehash,$delflag,$username,
3988: $domain,$auname,$audom);
3989: }
3990: return;
3991: }
3992:
1.351 www 3993: sub get_course_adv_roles {
1.948 raeburn 3994: my ($cid,$codes) = @_;
1.620 albertel 3995: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3996: my %coursehash=&coursedescription($cid);
1.988 raeburn 3997: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3998: my %nothide=();
1.800 albertel 3999: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4000: if ($user !~ /:/) {
4001: $nothide{join(':',split(/[\@]/,$user))}=1;
4002: } else {
4003: $nothide{$user}=1;
4004: }
1.470 www 4005: }
1.1172.2.23 raeburn 4006: my @possdoms = ($coursehash{'domain'});
4007: if ($coursehash{'checkforpriv'}) {
4008: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4009: }
1.351 www 4010: my %returnhash=();
4011: my %dumphash=
4012: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4013: my $now=time;
1.997 raeburn 4014: my %privileged;
1.1000 raeburn 4015: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4016: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4017: if (($tstart) && ($tstart<0)) { next; }
4018: if (($tend) && ($tend<$now)) { next; }
4019: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4020: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4021: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4022: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4023: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4024: if ($role eq 'cr') { next; }
1.948 raeburn 4025: if ($codes) {
4026: if ($section) { $role .= ':'.$section; }
4027: if ($returnhash{$role}) {
4028: $returnhash{$role}.=','.$username.':'.$domain;
4029: } else {
4030: $returnhash{$role}=$username.':'.$domain;
4031: }
1.351 www 4032: } else {
1.988 raeburn 4033: my $key=&plaintext($role,$crstype);
1.973 bisitz 4034: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4035: if ($returnhash{$key}) {
4036: $returnhash{$key}.=','.$username.':'.$domain;
4037: } else {
4038: $returnhash{$key}=$username.':'.$domain;
4039: }
1.351 www 4040: }
1.948 raeburn 4041: }
1.400 www 4042: return %returnhash;
4043: }
4044:
4045: sub get_my_roles {
1.937 raeburn 4046: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4047: unless (defined($uname)) { $uname=$env{'user.name'}; }
4048: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4049: my (%dumphash,%nothide);
1.1086 raeburn 4050: if ($context eq 'userroles') {
1.1166 raeburn 4051: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4052: } else {
1.1172.2.23 raeburn 4053: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4054: if ($hidepriv) {
4055: my %coursehash=&coursedescription($udom.'_'.$uname);
4056: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4057: if ($user !~ /:/) {
4058: $nothide{join(':',split(/[\@]/,$user))} = 1;
4059: } else {
4060: $nothide{$user} = 1;
4061: }
4062: }
4063: }
1.858 raeburn 4064: }
1.400 www 4065: my %returnhash=();
4066: my $now=time;
1.999 raeburn 4067: my %privileged;
1.800 albertel 4068: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4069: my ($role,$tend,$tstart);
4070: if ($context eq 'userroles') {
1.1149 raeburn 4071: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4072: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4073: } else {
4074: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4075: }
1.400 www 4076: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4077: my $status = 'active';
1.939 raeburn 4078: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4079: $status = 'previous';
4080: }
4081: if (($tstart) && ($now<$tstart)) {
4082: $status = 'future';
4083: }
4084: if (ref($types) eq 'ARRAY') {
4085: if (!grep(/^\Q$status\E$/,@{$types})) {
4086: next;
4087: }
4088: } else {
4089: if ($status ne 'active') {
4090: next;
4091: }
4092: }
1.867 raeburn 4093: my ($rolecode,$username,$domain,$section,$area);
4094: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4095: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4096: (undef,$domain,$username,$section) = split(/\//,$area);
4097: } else {
4098: ($role,$username,$domain,$section) = split(/\:/,$entry);
4099: }
1.832 raeburn 4100: if (ref($roledoms) eq 'ARRAY') {
4101: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4102: next;
4103: }
4104: }
4105: if (ref($roles) eq 'ARRAY') {
4106: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4107: if ($role =~ /^cr\//) {
4108: if (!grep(/^cr$/,@{$roles})) {
4109: next;
4110: }
1.1104 raeburn 4111: } elsif ($role =~ /^gr\//) {
4112: if (!grep(/^gr$/,@{$roles})) {
4113: next;
4114: }
1.922 raeburn 4115: } else {
4116: next;
4117: }
1.832 raeburn 4118: }
1.867 raeburn 4119: }
1.937 raeburn 4120: if ($hidepriv) {
1.1172.2.23 raeburn 4121: my @privroles = ('dc','su');
1.999 raeburn 4122: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4123: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4124: } else {
1.1172.2.23 raeburn 4125: my $possdoms = [$domain];
4126: if (ref($roledoms) eq 'ARRAY') {
4127: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4128: }
1.1172.2.23 raeburn 4129: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4130: if (!$nothide{$username.':'.$domain}) {
4131: next;
4132: }
4133: }
1.937 raeburn 4134: }
4135: }
1.933 raeburn 4136: if ($withsec) {
4137: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4138: $tstart.':'.$tend;
4139: } else {
4140: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4141: }
1.832 raeburn 4142: }
1.373 www 4143: return %returnhash;
1.399 www 4144: }
4145:
4146: # ----------------------------------------------------- Frontpage Announcements
4147: #
4148: #
4149:
4150: sub postannounce {
4151: my ($server,$text)=@_;
1.844 albertel 4152: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4153: unless ($text=~/\w/) { $text=''; }
4154: return &reply('setannounce:'.&escape($text),$server);
4155: }
4156:
4157: sub getannounce {
1.448 albertel 4158:
4159: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4160: my $announcement='';
1.800 albertel 4161: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4162: close($fh);
1.399 www 4163: if ($announcement=~/\w/) {
4164: return
4165: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4166: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4167: } else {
4168: return '';
4169: }
4170: } else {
4171: return '';
4172: }
1.351 www 4173: }
1.353 www 4174:
4175: # ---------------------------------------------------------- Course ID routines
4176: # Deal with domain's nohist_courseid.db files
4177: #
4178:
4179: sub courseidput {
1.921 raeburn 4180: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4181: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4182: my $outcome;
4183: if ($caller eq 'timeonly') {
4184: my $cids = '';
4185: foreach my $item (keys(%$storehash)) {
4186: $cids.=&escape($item).'&';
4187: }
4188: $cids=~s/\&$//;
4189: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4190: $coursehome);
4191: } else {
4192: my $items = '';
4193: foreach my $item (keys(%$storehash)) {
4194: $items.= &escape($item).'='.
4195: &freeze_escape($$storehash{$item}).'&';
4196: }
4197: $items=~s/\&$//;
4198: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4199: $coursehome);
1.918 raeburn 4200: }
4201: if ($outcome eq 'unknown_cmd') {
4202: my $what;
4203: foreach my $cid (keys(%$storehash)) {
4204: $what .= &escape($cid).'=';
1.921 raeburn 4205: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4206: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4207: }
4208: $what =~ s/\:$/&/;
4209: }
4210: $what =~ s/\&$//;
4211: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4212: } else {
4213: return $outcome;
4214: }
1.353 www 4215: }
4216:
4217: sub courseiddump {
1.921 raeburn 4218: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4219: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4220: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4221: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4222: $hasuniquecode)=@_;
1.918 raeburn 4223: my $as_hash = 1;
4224: my %returnhash;
4225: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4226: my %libserv = &all_library();
4227: foreach my $tryserver (keys(%libserv)) {
4228: if ( ( $hostidflag == 1
4229: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4230: || (!defined($hostidflag)) ) {
4231:
1.918 raeburn 4232: if (($domfilter eq '') ||
4233: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4234: my $rep;
4235: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4236: $rep = &LONCAPA::Lond::dump_course_id_handler(
4237: join(":", (&host_domain($tryserver), $sincefilter,
4238: &escape($descfilter), &escape($instcodefilter),
4239: &escape($ownerfilter), &escape($coursefilter),
4240: &escape($typefilter), &escape($regexp_ok),
4241: $as_hash, &escape($selfenrollonly),
4242: &escape($catfilter), $showhidden, $caller,
4243: &escape($cloner), &escape($cc_clone), $cloneonly,
4244: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4245: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4246: } else {
4247: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4248: $sincefilter.':'.&escape($descfilter).':'.
4249: &escape($instcodefilter).':'.&escape($ownerfilter).
4250: ':'.&escape($coursefilter).':'.&escape($typefilter).
4251: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4252: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4253: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4254: &escape($cc_clone).':'.$cloneonly.':'.
4255: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4256: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4257: $tryserver);
4258: }
4259:
1.918 raeburn 4260: my @pairs=split(/\&/,$rep);
4261: foreach my $item (@pairs) {
4262: my ($key,$value)=split(/\=/,$item,2);
4263: $key = &unescape($key);
4264: next if ($key =~ /^error: 2 /);
4265: my $result = &thaw_unescape($value);
4266: if (ref($result) eq 'HASH') {
4267: $returnhash{$key}=$result;
4268: } else {
1.921 raeburn 4269: my @responses = split(/:/,$value);
4270: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4271: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4272: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4273: }
1.1008 raeburn 4274: }
1.353 www 4275: }
4276: }
4277: }
4278: }
4279: return %returnhash;
4280: }
4281:
1.1055 raeburn 4282: sub courselastaccess {
4283: my ($cdom,$cnum,$hostidref) = @_;
4284: my %returnhash;
4285: if ($cdom && $cnum) {
4286: my $chome = &homeserver($cnum,$cdom);
4287: if ($chome ne 'no_host') {
4288: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4289: &extract_lastaccess(\%returnhash,$rep);
4290: }
4291: } else {
4292: if (!$cdom) { $cdom=''; }
4293: my %libserv = &all_library();
4294: foreach my $tryserver (keys(%libserv)) {
4295: if (ref($hostidref) eq 'ARRAY') {
4296: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4297: }
4298: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4299: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4300: &extract_lastaccess(\%returnhash,$rep);
4301: }
4302: }
4303: }
4304: return %returnhash;
4305: }
4306:
4307: sub extract_lastaccess {
4308: my ($returnhash,$rep) = @_;
4309: if (ref($returnhash) eq 'HASH') {
4310: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4311: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4312: $rep eq '') {
4313: my @pairs=split(/\&/,$rep);
4314: foreach my $item (@pairs) {
4315: my ($key,$value)=split(/\=/,$item,2);
4316: $key = &unescape($key);
4317: next if ($key =~ /^error: 2 /);
4318: $returnhash->{$key} = &thaw_unescape($value);
4319: }
4320: }
4321: }
4322: return;
4323: }
4324:
1.658 raeburn 4325: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4326:
4327: sub dcmailput {
1.685 raeburn 4328: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4329: my $status = &Apache::lonnet::critical(
1.740 www 4330: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4331: &escape($message),$server);
1.662 raeburn 4332: return $status;
4333: }
4334:
1.658 raeburn 4335: sub dcmaildump {
4336: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4337: my %returnhash=();
1.846 albertel 4338:
4339: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4340: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4341: &escape($enddate).':';
4342: my @esc_senders=map { &escape($_)} @$senders;
4343: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4344: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4345: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4346: if (($key) && ($value)) {
4347: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4348: }
4349: }
4350: }
4351: return %returnhash;
4352: }
1.662 raeburn 4353: # ---------------------------------------------------------- Domain roles
4354:
4355: sub get_domain_roles {
4356: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4357: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4358: $startdate = '.';
4359: }
1.1018 raeburn 4360: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4361: $enddate = '.';
4362: }
1.922 raeburn 4363: my $rolelist;
4364: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4365: $rolelist = join('&',@{$roles});
1.922 raeburn 4366: }
1.662 raeburn 4367: my %personnel = ();
1.841 albertel 4368:
4369: my %servers = &get_servers($dom,'library');
4370: foreach my $tryserver (keys(%servers)) {
4371: %{$personnel{$tryserver}}=();
4372: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4373: &escape($startdate).':'.
4374: &escape($enddate).':'.
4375: &escape($rolelist), $tryserver))) {
4376: my ($key,$value) = split(/\=/,$line,2);
4377: if (($key) && ($value)) {
4378: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4379: }
4380: }
1.662 raeburn 4381: }
4382: return %personnel;
4383: }
1.658 raeburn 4384:
1.1057 www 4385: # ----------------------------------------------------------- Interval timing
1.149 www 4386:
1.1153 www 4387: {
4388: # Caches needed for speedup of navmaps
4389: # We don't want to cache this for very long at all (5 seconds at most)
4390: #
4391: # The user for whom we cache
4392: my $cachedkey='';
4393: # The cached times for this user
4394: my %cachedtimes=();
4395: # When this was last done
4396: my $cachedtime=();
4397:
4398: sub load_all_first_access {
1.1154 raeburn 4399: my ($uname,$udom)=@_;
1.1156 www 4400: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4401: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4402: return;
4403: }
4404: $cachedtime=time;
4405: $cachedkey=$uname.':'.$udom;
4406: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4407: }
4408:
1.504 albertel 4409: sub get_first_access {
1.1162 raeburn 4410: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4411: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4412: if ($argsymb) { $symb=$argsymb; }
4413: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4414: if ($argmap) { $map = $argmap; }
1.926 albertel 4415: if ($type eq 'course') {
4416: $res='course';
4417: } elsif ($type eq 'map') {
1.588 albertel 4418: $res=&symbread($map);
4419: } else {
4420: $res=$symb;
4421: }
1.1153 www 4422: &load_all_first_access($uname,$udom);
4423: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4424: }
4425:
4426: sub set_first_access {
1.1162 raeburn 4427: my ($type,$interval)=@_;
1.790 albertel 4428: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4429: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4430: if ($type eq 'course') {
4431: $res='course';
4432: } elsif ($type eq 'map') {
1.588 albertel 4433: $res=&symbread($map);
4434: } else {
4435: $res=$symb;
4436: }
1.1153 www 4437: $cachedkey='';
1.1162 raeburn 4438: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4439: if (!$firstaccess) {
1.1162 raeburn 4440: my $start = time;
4441: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4442: $udom,$uname);
4443: if ($putres eq 'ok') {
4444: &put('timerinterval',{"$courseid\0$res"=>$interval},
4445: $udom,$uname);
4446: &appenv(
4447: {
4448: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4449: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4450: }
4451: );
4452: }
4453: return $putres;
1.505 albertel 4454: }
4455: return 'already_set';
1.504 albertel 4456: }
1.1153 www 4457: }
1.1172.2.32 raeburn 4458:
4459: sub checkout {
4460: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4461: my $now=time;
4462: my $lonhost=$perlvar{'lonHostID'};
4463: my $infostr=&escape(
4464: 'CHECKOUTTOKEN&'.
4465: $tuname.'&'.
4466: $tudom.'&'.
4467: $tcrsid.'&'.
4468: $symb.'&'.
4469: $now.'&'.$ENV{'REMOTE_ADDR'});
4470: my $token=&reply('tmpput:'.$infostr,$lonhost);
4471: if ($token=~/^error\:/) {
4472: &logthis("<font color=\"blue\">WARNING: ".
4473: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4474: "</font>");
4475: return '';
4476: }
4477:
4478: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4479: $token=~tr/a-z/A-Z/;
4480:
4481: my %infohash=('resource.0.outtoken' => $token,
4482: 'resource.0.checkouttime' => $now,
4483: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4484:
4485: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4486: return '';
4487: } else {
4488: &logthis("<font color=\"blue\">WARNING: ".
4489: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4490: "</font>");
4491: }
4492:
4493: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4494: &escape('Checkout '.$infostr.' - '.
4495: $token)) ne 'ok') {
4496: return '';
4497: } else {
4498: &logthis("<font color=\"blue\">WARNING: ".
4499: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4500: "</font>");
4501: }
4502: return $token;
4503: }
4504:
4505: # ------------------------------------------------------------ Check in an item
4506:
4507: sub checkin {
4508: my $token=shift;
4509: my $now=time;
4510: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4511: $lonhost=~tr/A-Z/a-z/;
4512: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4513: $dtoken=~s/\W/\_/g;
4514: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4515: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4516:
4517: unless (($tuname) && ($tudom)) {
4518: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4519: return '';
4520: }
4521:
4522: unless (&allowed('mgr',$tcrsid)) {
4523: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4524: $env{'user.name'}.' - '.$env{'user.domain'});
4525: return '';
4526: }
4527:
4528: my %infohash=('resource.0.intoken' => $token,
4529: 'resource.0.checkintime' => $now,
4530: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4531:
4532: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4533: return '';
4534: }
4535:
4536: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4537: &escape('Checkin - '.$token)) ne 'ok') {
4538: return '';
4539: }
4540:
4541: return ($symb,$tuname,$tudom,$tcrsid);
4542: }
4543:
1.110 www 4544: # --------------------------------------------- Set Expire Date for Spreadsheet
4545:
4546: sub expirespread {
4547: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4548: my $cid=$env{'request.course.id'};
1.110 www 4549: if ($cid) {
4550: my $now=time;
4551: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4552: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4553: $env{'course.'.$cid.'.num'}.
1.110 www 4554: ':nohist_expirationdates:'.
4555: &escape($key).'='.$now,
1.620 albertel 4556: $env{'course.'.$cid.'.home'})
1.110 www 4557: }
4558: return 'ok';
1.14 www 4559: }
4560:
1.109 www 4561: # ----------------------------------------------------- Devalidate Spreadsheets
4562:
4563: sub devalidate {
1.325 www 4564: my ($symb,$uname,$udom)=@_;
1.620 albertel 4565: my $cid=$env{'request.course.id'};
1.109 www 4566: if ($cid) {
1.391 matthew 4567: # delete the stored spreadsheets for
4568: # - the student level sheet of this user in course's homespace
4569: # - the assessment level sheet for this resource
4570: # for this user in user's homespace
1.553 albertel 4571: # - current conditional state info
1.325 www 4572: my $key=$uname.':'.$udom.':';
1.109 www 4573: my $status=
1.299 matthew 4574: &del('nohist_calculatedsheets',
1.391 matthew 4575: [$key.'studentcalc:'],
1.620 albertel 4576: $env{'course.'.$cid.'.domain'},
4577: $env{'course.'.$cid.'.num'})
1.133 albertel 4578: .' '.
4579: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4580: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4581: unless ($status eq 'ok ok') {
4582: &logthis('Could not devalidate spreadsheet '.
1.325 www 4583: $uname.' at '.$udom.' for '.
1.109 www 4584: $symb.': '.$status);
1.133 albertel 4585: }
1.553 albertel 4586: &delenv('user.state.'.$cid);
1.109 www 4587: }
4588: }
4589:
1.265 albertel 4590: sub get_scalar {
4591: my ($string,$end) = @_;
4592: my $value;
4593: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4594: $value = $1;
4595: } elsif ($$string =~ s/^([^&]*?)&//) {
4596: $value = $1;
4597: }
4598: return &unescape($value);
4599: }
4600:
4601: sub array2str {
4602: my (@array) = @_;
4603: my $result=&arrayref2str(\@array);
4604: $result=~s/^__ARRAY_REF__//;
4605: $result=~s/__END_ARRAY_REF__$//;
4606: return $result;
4607: }
4608:
1.204 albertel 4609: sub arrayref2str {
4610: my ($arrayref) = @_;
1.265 albertel 4611: my $result='__ARRAY_REF__';
1.204 albertel 4612: foreach my $elem (@$arrayref) {
1.265 albertel 4613: if(ref($elem) eq 'ARRAY') {
4614: $result.=&arrayref2str($elem).'&';
4615: } elsif(ref($elem) eq 'HASH') {
4616: $result.=&hashref2str($elem).'&';
4617: } elsif(ref($elem)) {
4618: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4619: } else {
4620: $result.=&escape($elem).'&';
4621: }
4622: }
4623: $result=~s/\&$//;
1.265 albertel 4624: $result .= '__END_ARRAY_REF__';
1.204 albertel 4625: return $result;
4626: }
4627:
1.168 albertel 4628: sub hash2str {
1.204 albertel 4629: my (%hash) = @_;
4630: my $result=&hashref2str(\%hash);
1.265 albertel 4631: $result=~s/^__HASH_REF__//;
4632: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4633: return $result;
4634: }
4635:
4636: sub hashref2str {
4637: my ($hashref)=@_;
1.265 albertel 4638: my $result='__HASH_REF__';
1.800 albertel 4639: foreach my $key (sort(keys(%$hashref))) {
4640: if (ref($key) eq 'ARRAY') {
4641: $result.=&arrayref2str($key).'=';
4642: } elsif (ref($key) eq 'HASH') {
4643: $result.=&hashref2str($key).'=';
4644: } elsif (ref($key)) {
1.265 albertel 4645: $result.='=';
1.800 albertel 4646: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4647: } else {
1.1132 raeburn 4648: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4649: }
4650:
1.800 albertel 4651: if(ref($hashref->{$key}) eq 'ARRAY') {
4652: $result.=&arrayref2str($hashref->{$key}).'&';
4653: } elsif(ref($hashref->{$key}) eq 'HASH') {
4654: $result.=&hashref2str($hashref->{$key}).'&';
4655: } elsif(ref($hashref->{$key})) {
1.265 albertel 4656: $result.='&';
1.800 albertel 4657: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4658: } else {
1.800 albertel 4659: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4660: }
4661: }
1.168 albertel 4662: $result=~s/\&$//;
1.265 albertel 4663: $result .= '__END_HASH_REF__';
1.168 albertel 4664: return $result;
4665: }
4666:
4667: sub str2hash {
1.265 albertel 4668: my ($string)=@_;
4669: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4670: return %$hash;
4671: }
4672:
4673: sub str2hashref {
1.168 albertel 4674: my ($string) = @_;
1.265 albertel 4675:
4676: my %hash;
4677:
4678: if($string !~ /^__HASH_REF__/) {
4679: if (! ($string eq '' || !defined($string))) {
4680: $hash{'error'}='Not hash reference';
4681: }
4682: return (\%hash, $string);
4683: }
4684:
4685: $string =~ s/^__HASH_REF__//;
4686:
4687: while($string !~ /^__END_HASH_REF__/) {
4688: #key
4689: my $key='';
4690: if($string =~ /^__HASH_REF__/) {
4691: ($key, $string)=&str2hashref($string);
4692: if(defined($key->{'error'})) {
4693: $hash{'error'}='Bad data';
4694: return (\%hash, $string);
4695: }
4696: } elsif($string =~ /^__ARRAY_REF__/) {
4697: ($key, $string)=&str2arrayref($string);
4698: if($key->[0] eq 'Array reference error') {
4699: $hash{'error'}='Bad data';
4700: return (\%hash, $string);
4701: }
4702: } else {
4703: $string =~ s/^(.*?)=//;
1.267 albertel 4704: $key=&unescape($1);
1.265 albertel 4705: }
4706: $string =~ s/^=//;
4707:
4708: #value
4709: my $value='';
4710: if($string =~ /^__HASH_REF__/) {
4711: ($value, $string)=&str2hashref($string);
4712: if(defined($value->{'error'})) {
4713: $hash{'error'}='Bad data';
4714: return (\%hash, $string);
4715: }
4716: } elsif($string =~ /^__ARRAY_REF__/) {
4717: ($value, $string)=&str2arrayref($string);
4718: if($value->[0] eq 'Array reference error') {
4719: $hash{'error'}='Bad data';
4720: return (\%hash, $string);
4721: }
4722: } else {
4723: $value=&get_scalar(\$string,'__END_HASH_REF__');
4724: }
4725: $string =~ s/^&//;
4726:
4727: $hash{$key}=$value;
1.204 albertel 4728: }
1.265 albertel 4729:
4730: $string =~ s/^__END_HASH_REF__//;
4731:
4732: return (\%hash, $string);
1.204 albertel 4733: }
4734:
4735: sub str2array {
1.265 albertel 4736: my ($string)=@_;
4737: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4738: return @$array;
4739: }
4740:
4741: sub str2arrayref {
1.204 albertel 4742: my ($string) = @_;
1.265 albertel 4743: my @array;
4744:
4745: if($string !~ /^__ARRAY_REF__/) {
4746: if (! ($string eq '' || !defined($string))) {
4747: $array[0]='Array reference error';
4748: }
4749: return (\@array, $string);
4750: }
4751:
4752: $string =~ s/^__ARRAY_REF__//;
4753:
4754: while($string !~ /^__END_ARRAY_REF__/) {
4755: my $value='';
4756: if($string =~ /^__HASH_REF__/) {
4757: ($value, $string)=&str2hashref($string);
4758: if(defined($value->{'error'})) {
4759: $array[0] ='Array reference error';
4760: return (\@array, $string);
4761: }
4762: } elsif($string =~ /^__ARRAY_REF__/) {
4763: ($value, $string)=&str2arrayref($string);
4764: if($value->[0] eq 'Array reference error') {
4765: $array[0] ='Array reference error';
4766: return (\@array, $string);
4767: }
4768: } else {
4769: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4770: }
4771: $string =~ s/^&//;
4772:
4773: push(@array, $value);
1.191 harris41 4774: }
1.265 albertel 4775:
4776: $string =~ s/^__END_ARRAY_REF__//;
4777:
4778: return (\@array, $string);
1.168 albertel 4779: }
4780:
1.167 albertel 4781: # -------------------------------------------------------------------Temp Store
4782:
1.168 albertel 4783: sub tmpreset {
4784: my ($symb,$namespace,$domain,$stuname) = @_;
4785: if (!$symb) {
4786: $symb=&symbread();
1.620 albertel 4787: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4788: }
4789: $symb=escape($symb);
4790:
1.620 albertel 4791: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4792: $namespace=~s/\//\_/g;
4793: $namespace=~s/\W//g;
4794:
1.620 albertel 4795: if (!$domain) { $domain=$env{'user.domain'}; }
4796: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4797: if ($domain eq 'public' && $stuname eq 'public') {
4798: $stuname=$ENV{'REMOTE_ADDR'};
4799: }
1.1117 foxr 4800: my $path=LONCAPA::tempdir();
1.168 albertel 4801: my %hash;
4802: if (tie(%hash,'GDBM_File',
4803: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4804: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4805: foreach my $key (keys(%hash)) {
1.180 albertel 4806: if ($key=~ /:$symb/) {
1.168 albertel 4807: delete($hash{$key});
4808: }
4809: }
4810: }
4811: }
4812:
1.167 albertel 4813: sub tmpstore {
1.168 albertel 4814: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4815:
4816: if (!$symb) {
4817: $symb=&symbread();
1.620 albertel 4818: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4819: }
4820: $symb=escape($symb);
4821:
4822: if (!$namespace) {
4823: # I don't think we would ever want to store this for a course.
4824: # it seems this will only be used if we don't have a course.
1.620 albertel 4825: #$namespace=$env{'request.course.id'};
1.168 albertel 4826: #if (!$namespace) {
1.620 albertel 4827: $namespace=$env{'request.state'};
1.168 albertel 4828: #}
4829: }
4830: $namespace=~s/\//\_/g;
4831: $namespace=~s/\W//g;
1.620 albertel 4832: if (!$domain) { $domain=$env{'user.domain'}; }
4833: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4834: if ($domain eq 'public' && $stuname eq 'public') {
4835: $stuname=$ENV{'REMOTE_ADDR'};
4836: }
1.168 albertel 4837: my $now=time;
4838: my %hash;
1.1117 foxr 4839: my $path=LONCAPA::tempdir();
1.168 albertel 4840: if (tie(%hash,'GDBM_File',
4841: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4842: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4843: $hash{"version:$symb"}++;
4844: my $version=$hash{"version:$symb"};
4845: my $allkeys='';
4846: foreach my $key (keys(%$storehash)) {
4847: $allkeys.=$key.':';
1.591 albertel 4848: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4849: }
4850: $hash{"$version:$symb:timestamp"}=$now;
4851: $allkeys.='timestamp';
4852: $hash{"$version:keys:$symb"}=$allkeys;
4853: if (untie(%hash)) {
4854: return 'ok';
4855: } else {
4856: return "error:$!";
4857: }
4858: } else {
4859: return "error:$!";
4860: }
4861: }
1.167 albertel 4862:
1.168 albertel 4863: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4864:
1.168 albertel 4865: sub tmprestore {
4866: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4867:
1.168 albertel 4868: if (!$symb) {
4869: $symb=&symbread();
1.620 albertel 4870: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4871: }
4872: $symb=escape($symb);
4873:
1.620 albertel 4874: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4875:
1.620 albertel 4876: if (!$domain) { $domain=$env{'user.domain'}; }
4877: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4878: if ($domain eq 'public' && $stuname eq 'public') {
4879: $stuname=$ENV{'REMOTE_ADDR'};
4880: }
1.168 albertel 4881: my %returnhash;
4882: $namespace=~s/\//\_/g;
4883: $namespace=~s/\W//g;
4884: my %hash;
1.1117 foxr 4885: my $path=LONCAPA::tempdir();
1.168 albertel 4886: if (tie(%hash,'GDBM_File',
4887: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4888: &GDBM_READER(),0640)) {
1.168 albertel 4889: my $version=$hash{"version:$symb"};
4890: $returnhash{'version'}=$version;
4891: my $scope;
4892: for ($scope=1;$scope<=$version;$scope++) {
4893: my $vkeys=$hash{"$scope:keys:$symb"};
4894: my @keys=split(/:/,$vkeys);
4895: my $key;
4896: $returnhash{"$scope:keys"}=$vkeys;
4897: foreach $key (@keys) {
1.591 albertel 4898: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4899: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4900: }
4901: }
1.168 albertel 4902: if (!(untie(%hash))) {
4903: return "error:$!";
4904: }
4905: } else {
4906: return "error:$!";
4907: }
4908: return %returnhash;
1.167 albertel 4909: }
4910:
1.9 www 4911: # ----------------------------------------------------------------------- Store
4912:
4913: sub store {
1.124 www 4914: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4915: my $home='';
4916:
1.168 albertel 4917: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4918:
1.213 www 4919: $symb=&symbclean($symb);
1.122 albertel 4920: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4921:
1.620 albertel 4922: if (!$domain) { $domain=$env{'user.domain'}; }
4923: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4924:
4925: &devalidate($symb,$stuname,$domain);
1.109 www 4926:
4927: $symb=escape($symb);
1.187 www 4928: if (!$namespace) {
1.620 albertel 4929: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4930: return '';
4931: }
4932: }
1.620 albertel 4933: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4934:
4935: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4936: $$storehash{'host'}=$perlvar{'lonHostID'};
4937:
1.12 www 4938: my $namevalue='';
1.800 albertel 4939: foreach my $key (keys(%$storehash)) {
4940: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4941: }
1.12 www 4942: $namevalue=~s/\&$//;
1.187 www 4943: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4944: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4945: }
4946:
1.47 www 4947: # -------------------------------------------------------------- Critical Store
4948:
4949: sub cstore {
1.124 www 4950: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4951: my $home='';
4952:
1.168 albertel 4953: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4954:
1.213 www 4955: $symb=&symbclean($symb);
1.122 albertel 4956: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4957:
1.620 albertel 4958: if (!$domain) { $domain=$env{'user.domain'}; }
4959: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4960:
4961: &devalidate($symb,$stuname,$domain);
1.109 www 4962:
4963: $symb=escape($symb);
1.187 www 4964: if (!$namespace) {
1.620 albertel 4965: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4966: return '';
4967: }
4968: }
1.620 albertel 4969: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4970:
4971: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4972: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4973:
1.47 www 4974: my $namevalue='';
1.800 albertel 4975: foreach my $key (keys(%$storehash)) {
4976: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4977: }
1.47 www 4978: $namevalue=~s/\&$//;
1.187 www 4979: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4980: return critical
4981: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4982: }
4983:
1.9 www 4984: # --------------------------------------------------------------------- Restore
4985:
4986: sub restore {
1.124 www 4987: my ($symb,$namespace,$domain,$stuname) = @_;
4988: my $home='';
4989:
1.168 albertel 4990: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4991:
1.122 albertel 4992: if (!$symb) {
1.1172.2.26 raeburn 4993: return if ($namespace eq 'courserequests');
4994: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4995: } else {
1.1172.2.26 raeburn 4996: unless ($namespace eq 'courserequests') {
4997: $symb=&escape(&symbclean($symb));
4998: }
1.122 albertel 4999: }
1.188 www 5000: if (!$namespace) {
1.620 albertel 5001: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5002: return '';
5003: }
5004: }
1.620 albertel 5005: if (!$domain) { $domain=$env{'user.domain'}; }
5006: if (!$stuname) { $stuname=$env{'user.name'}; }
5007: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5008: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5009:
1.12 www 5010: my %returnhash=();
1.800 albertel 5011: foreach my $line (split(/\&/,$answer)) {
5012: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5013: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5014: }
1.75 www 5015: my $version;
5016: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5017: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5018: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5019: }
1.75 www 5020: }
1.13 www 5021: return %returnhash;
1.34 www 5022: }
5023:
5024: # ---------------------------------------------------------- Course Description
1.1118 foxr 5025: #
5026: #
1.34 www 5027:
5028: sub coursedescription {
1.731 albertel 5029: my ($courseid,$args)=@_;
1.34 www 5030: $courseid=~s/^\///;
1.49 www 5031: $courseid=~s/\_/\//g;
1.34 www 5032: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5033: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5034: my $normalid=$cdomain.'_'.$cnum;
5035: # need to always cache even if we get errors otherwise we keep
5036: # trying and trying and trying to get the course description.
5037: my %envhash=();
5038: my %returnhash=();
1.731 albertel 5039:
5040: my $expiretime=600;
5041: if ($env{'request.course.id'} eq $normalid) {
5042: $expiretime=120;
5043: }
5044:
5045: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5046: if (!$args->{'freshen_cache'}
5047: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5048: foreach my $key (keys(%env)) {
5049: next if ($key !~ /^\Q$prefix\E(.*)/);
5050: my ($setting) = $1;
5051: $returnhash{$setting} = $env{$key};
5052: }
5053: return %returnhash;
5054: }
5055:
1.1118 foxr 5056: # get the data again
5057:
1.731 albertel 5058: if (!$args->{'one_time'}) {
5059: $envhash{'course.'.$normalid.'.last_cache'}=time;
5060: }
1.811 albertel 5061:
1.34 www 5062: if ($chome ne 'no_host') {
1.302 albertel 5063: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5064: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5065: my $username = $env{'user.name'}; # Defult username
5066: if(defined $args->{'user'}) {
5067: $username = $args->{'user'};
5068: }
1.129 albertel 5069: $returnhash{'home'}= $chome;
5070: $returnhash{'domain'} = $cdomain;
5071: $returnhash{'num'} = $cnum;
1.741 raeburn 5072: if (!defined($returnhash{'type'})) {
5073: $returnhash{'type'} = 'Course';
5074: }
1.130 albertel 5075: while (my ($name,$value) = each %returnhash) {
1.53 www 5076: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5077: }
1.270 www 5078: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5079: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5080: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5081: $envhash{'course.'.$normalid.'.home'}=$chome;
5082: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5083: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5084: }
5085: }
1.731 albertel 5086: if (!$args->{'one_time'}) {
1.949 raeburn 5087: &appenv(\%envhash);
1.731 albertel 5088: }
1.302 albertel 5089: return %returnhash;
1.461 www 5090: }
5091:
1.1080 raeburn 5092: sub update_released_required {
5093: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5094: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5095: $cid = $env{'request.course.id'};
5096: $cdom = $env{'course.'.$cid.'.domain'};
5097: $cnum = $env{'course.'.$cid.'.num'};
5098: $chome = $env{'course.'.$cid.'.home'};
5099: }
5100: if ($needsrelease) {
5101: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5102: my $needsupdate;
5103: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5104: $needsupdate = 1;
5105: } else {
5106: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5107: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5108: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5109: $needsupdate = 1;
5110: }
5111: }
5112: if ($needsupdate) {
5113: my %needshash = (
5114: 'internal.releaserequired' => $needsrelease,
5115: );
5116: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5117: if ($putresult eq 'ok') {
5118: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5119: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5120: if (ref($crsinfo{$cid}) eq 'HASH') {
5121: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5122: &courseidput($cdom,\%crsinfo,$chome,'notime');
5123: }
5124: }
5125: }
5126: }
5127: return;
5128: }
5129:
1.461 www 5130: # -------------------------------------------------See if a user is privileged
5131:
5132: sub privileged {
1.1172.2.23 raeburn 5133: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5134: my $now = time;
1.1172.2.23 raeburn 5135: my $roles;
5136: if (ref($possroles) eq 'ARRAY') {
5137: $roles = $possroles;
5138: } else {
5139: $roles = ['dc','su'];
5140: }
5141: if (ref($possdomains) eq 'ARRAY') {
5142: my %privileged = &privileged_by_domain($possdomains,$roles);
5143: foreach my $dom (@{$possdomains}) {
5144: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5145: (ref($privileged{$dom}) eq 'HASH')) {
5146: foreach my $role (@{$roles}) {
5147: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5148: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5149: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5150: return 1 unless (($end && $end < $now) ||
5151: ($start && $start > $now));
5152: }
5153: }
5154: }
5155: }
5156: }
5157: } else {
5158: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5159: my $now = time;
1.1170 droeschl 5160:
1.1172.2.23 raeburn 5161: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5162: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5163: if (grep(/^\Q$trole\E$/,@{$roles})) {
5164: return 1 unless ($tend && $tend < $now)
5165: or ($tstart && $tstart > $now);
1.1170 droeschl 5166: }
1.1172.2.23 raeburn 5167: }
5168: }
1.461 www 5169: return 0;
1.9 www 5170: }
1.1 albertel 5171:
1.1172.2.23 raeburn 5172: sub privileged_by_domain {
5173: my ($domains,$roles) = @_;
5174: my %privileged = ();
5175: my $cachetime = 60*60*24;
5176: my $now = time;
5177: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5178: return %privileged;
5179: }
5180: foreach my $dom (@{$domains}) {
5181: next if (ref($privileged{$dom}) eq 'HASH');
5182: my $needroles;
5183: foreach my $role (@{$roles}) {
5184: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5185: if (defined($cached)) {
5186: if (ref($result) eq 'HASH') {
5187: $privileged{$dom}{$role} = $result;
5188: }
5189: } else {
5190: $needroles = 1;
5191: }
5192: }
5193: if ($needroles) {
5194: my %dompersonnel = &get_domain_roles($dom,$roles);
5195: $privileged{$dom} = {};
5196: foreach my $server (keys(%dompersonnel)) {
5197: if (ref($dompersonnel{$server}) eq 'HASH') {
5198: foreach my $item (keys(%{$dompersonnel{$server}})) {
5199: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5200: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5201: next if ($end && $end < $now);
5202: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5203: $dompersonnel{$server}{$item};
5204: }
5205: }
5206: }
5207: if (ref($privileged{$dom}) eq 'HASH') {
5208: foreach my $role (@{$roles}) {
5209: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5210: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5211: } else {
5212: my %hash = ();
5213: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5214: }
5215: }
5216: }
5217: }
5218: }
5219: return %privileged;
5220: }
5221:
1.103 harris41 5222: # -------------------------------------------------------- Get user privileges
1.11 www 5223:
5224: sub rolesinit {
1.1169 droeschl 5225: my ($domain, $username) = @_;
5226: my %userroles = ('user.login.time' => time);
5227: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5228:
5229: # firstaccess and timerinterval are related to timed maps/resources.
5230: # also, blocking can be triggered by an activating timer
5231: # it's saved in the user's %env.
5232: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5233: my %timerinterval = &dump('timerinterval', $domain, $username);
5234: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5235: %timerintchk, %timerintenv);
5236:
1.1162 raeburn 5237: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5238: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5239: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5240: }
1.1169 droeschl 5241:
1.1162 raeburn 5242: foreach my $key (keys(%timerinterval)) {
5243: my ($cid,$rest) = split(/\0/,$key);
5244: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5245: }
1.1169 droeschl 5246:
1.11 www 5247: my %allroles=();
1.1162 raeburn 5248: my %allgroups=();
1.11 www 5249:
1.1169 droeschl 5250: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5251: my $role = $rolesdump{$area};
5252: $area =~ s/\_\w\w$//;
5253:
5254: my ($trole, $tend, $tstart, $group_privs);
5255:
5256: if ($role =~ /^cr/) {
5257: # Custom role, defined by a user
5258: # e.g., user.role.cr/msu/smith/mynewrole
5259: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5260: $trole = $1;
5261: ($tend, $tstart) = split('_', $2);
5262: } else {
5263: $trole = $role;
5264: }
5265: } elsif ($role =~ m|^gr/|) {
5266: # Role of member in a group, defined within a course/community
5267: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5268: ($trole, $tend, $tstart) = split(/_/, $role);
5269: next if $tstart eq '-1';
5270: ($trole, $group_privs) = split(/\//, $trole);
5271: $group_privs = &unescape($group_privs);
5272: } else {
5273: # Just a normal role, defined in roles.tab
5274: ($trole, $tend, $tstart) = split(/_/,$role);
5275: }
5276:
5277: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5278: $username);
5279: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5280:
5281: # role expired or not available yet?
5282: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5283: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5284:
5285: next if $area eq '' or $trole eq '';
5286:
5287: my $spec = "$trole.$area";
5288: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5289:
5290: if ($trole =~ /^cr\//) {
5291: # Custom role, defined by a user
5292: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5293: } elsif ($trole eq 'gr') {
5294: # Role of a member in a group, defined within a course/community
5295: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5296: next;
5297: } else {
5298: # Normal role, defined in roles.tab
5299: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5300: }
5301:
5302: my $cid = $tdomain.'_'.$trest;
5303: unless ($firstaccchk{$cid}) {
5304: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5305: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5306: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5307: $coursetimerstarts{$cid}{$item};
5308: }
5309: }
5310: $firstaccchk{$cid} = 1;
5311: }
5312: unless ($timerintchk{$cid}) {
5313: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5314: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5315: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5316: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5317: }
1.12 www 5318: }
1.1169 droeschl 5319: $timerintchk{$cid} = 1;
1.191 harris41 5320: }
1.11 www 5321: }
1.1169 droeschl 5322:
5323: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5324: \%allroles, \%allgroups);
5325: $env{'user.adv'} = $userroles{'user.adv'};
5326:
1.1162 raeburn 5327: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5328: }
5329:
1.567 raeburn 5330: sub set_arearole {
1.1172.2.19 raeburn 5331: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5332: unless ($nolog) {
1.567 raeburn 5333: # log the associated role with the area
1.1172.2.19 raeburn 5334: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5335: }
1.743 albertel 5336: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5337: }
5338:
5339: sub custom_roleprivs {
5340: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5341: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5342: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5343: if (&hostname($homsvr) ne '') {
1.567 raeburn 5344: my ($rdummy,$roledef)=
5345: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5346: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5347: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5348: if (defined($syspriv)) {
1.1043 raeburn 5349: if ($trest =~ /^$match_community$/) {
5350: $syspriv =~ s/bre\&S//;
5351: }
1.567 raeburn 5352: $$allroles{'cm./'}.=':'.$syspriv;
5353: $$allroles{$spec.'./'}.=':'.$syspriv;
5354: }
5355: if ($tdomain ne '') {
5356: if (defined($dompriv)) {
5357: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5358: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5359: }
5360: if (($trest ne '') && (defined($coursepriv))) {
5361: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5362: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5363: }
5364: }
5365: }
5366: }
5367: }
5368:
1.678 raeburn 5369: sub group_roleprivs {
5370: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5371: my $access = 1;
5372: my $now = time;
5373: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5374: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5375: if ($access) {
1.811 albertel 5376: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5377: $$allgroups{$course}{$group} .=':'.$group_privs;
5378: }
5379: }
1.567 raeburn 5380:
5381: sub standard_roleprivs {
5382: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5383: if (defined($pr{$trole.':s'})) {
5384: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5385: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5386: }
5387: if ($tdomain ne '') {
5388: if (defined($pr{$trole.':d'})) {
5389: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5390: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5391: }
5392: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5393: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5394: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5395: }
5396: }
5397: }
5398:
5399: sub set_userprivs {
1.1064 raeburn 5400: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5401: my $author=0;
5402: my $adv=0;
1.678 raeburn 5403: my %grouproles = ();
5404: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5405: my @groupkeys;
1.1000 raeburn 5406: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5407: push(@groupkeys,$role);
5408: }
5409: if (ref($groups_roles) eq 'HASH') {
5410: foreach my $key (keys(%{$groups_roles})) {
5411: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5412: push(@groupkeys,$key);
5413: }
5414: }
5415: }
5416: if (@groupkeys > 0) {
5417: foreach my $role (@groupkeys) {
5418: my ($trole,$area,$sec,$extendedarea);
5419: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5420: $trole = $1;
5421: $area = $2;
5422: $sec = $3;
5423: $extendedarea = $area.$sec;
5424: if (exists($$allgroups{$area})) {
5425: foreach my $group (keys(%{$$allgroups{$area}})) {
5426: my $spec = $trole.'.'.$extendedarea;
5427: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5428: $$allgroups{$area}{$group};
1.1064 raeburn 5429: }
1.678 raeburn 5430: }
5431: }
5432: }
5433: }
5434: }
1.800 albertel 5435: foreach my $group (keys(%grouproles)) {
5436: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5437: }
1.800 albertel 5438: foreach my $role (keys(%{$allroles})) {
5439: my %thesepriv;
1.941 raeburn 5440: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5441: foreach my $item (split(/:/,$$allroles{$role})) {
5442: if ($item ne '') {
5443: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5444: if ($restrictions eq '') {
5445: $thesepriv{$privilege}='F';
5446: } elsif ($thesepriv{$privilege} ne 'F') {
5447: $thesepriv{$privilege}.=$restrictions;
5448: }
5449: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5450: }
5451: }
5452: my $thesestr='';
1.1104 raeburn 5453: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5454: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5455: }
5456: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5457: }
5458: return ($author,$adv);
5459: }
5460:
1.994 raeburn 5461: sub role_status {
1.1104 raeburn 5462: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5463: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5464: my ($one,$two) = split(m{\./},$rolekey,2);
5465: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5466: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5467: $$where = '/'.$two;
1.994 raeburn 5468: $$trolecode=$$role.'.'.$$where;
5469: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5470: $$tstatus='is';
1.1104 raeburn 5471: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5472: $$tstatus='future';
1.1034 raeburn 5473: if ($$tstart<$now) {
5474: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5475: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5476: my (%allroles,%allgroups,$group_privs,
5477: %groups_roles,@rolecodes);
1.1002 raeburn 5478: my %userroles = (
5479: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5480: );
1.1064 raeburn 5481: @rolecodes = ('cm');
1.1002 raeburn 5482: my $spec=$$role.'.'.$$where;
5483: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5484: if ($$role =~ /^cr\//) {
5485: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5486: push(@rolecodes,'cr');
1.1002 raeburn 5487: } elsif ($$role eq 'gr') {
1.1064 raeburn 5488: push(@rolecodes,$$role);
1.1002 raeburn 5489: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5490: $env{'user.name'});
1.1064 raeburn 5491: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5492: (undef,my $group_privs) = split(/\//,$trole);
5493: $group_privs = &unescape($group_privs);
5494: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5495: 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 5496: &get_groups_roles($tdomain,$trest,
5497: \%course_roles,\@rolecodes,
5498: \%groups_roles);
1.1002 raeburn 5499: } else {
1.1064 raeburn 5500: push(@rolecodes,$$role);
1.1002 raeburn 5501: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5502: }
1.1064 raeburn 5503: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5504: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5505: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5506: }
5507: }
1.1034 raeburn 5508: $$tstatus = 'is';
1.1002 raeburn 5509: }
1.994 raeburn 5510: }
5511: if ($$tend) {
1.1104 raeburn 5512: if ($$tend<$update) {
1.994 raeburn 5513: $$tstatus='expired';
5514: } elsif ($$tend<$now) {
5515: $$tstatus='will_not';
5516: }
5517: }
5518: }
5519: }
5520: }
5521:
1.1104 raeburn 5522: sub get_groups_roles {
5523: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5524: return unless((ref($cdom_courseroles) eq 'HASH') &&
5525: (ref($rolecodes) eq 'ARRAY') &&
5526: (ref($groups_roles) eq 'HASH'));
5527: if (keys(%{$cdom_courseroles}) > 0) {
5528: my ($cnum) = ($rest =~ /^($match_courseid)/);
5529: if ($cdom ne '' && $cnum ne '') {
5530: foreach my $key (keys(%{$cdom_courseroles})) {
5531: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5532: my $crsrole = $1;
5533: my $crssec = $2;
5534: if ($crsrole =~ /^cr/) {
5535: unless (grep(/^cr$/,@{$rolecodes})) {
5536: push(@{$rolecodes},'cr');
5537: }
5538: } else {
5539: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5540: push(@{$rolecodes},$crsrole);
5541: }
5542: }
5543: my $rolekey = "$crsrole./$cdom/$cnum";
5544: if ($crssec ne '') {
5545: $rolekey .= "/$crssec";
5546: }
5547: $rolekey .= './';
5548: $groups_roles->{$rolekey} = $rolecodes;
5549: }
5550: }
5551: }
5552: }
5553: return;
5554: }
5555:
5556: sub delete_env_groupprivs {
5557: my ($where,$courseroles,$possroles) = @_;
5558: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5559: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5560: unless (ref($courseroles->{$udom}) eq 'HASH') {
5561: %{$courseroles->{$udom}} =
5562: &get_my_roles('','','userroles',['active'],
5563: $possroles,[$udom],1);
5564: }
5565: if (ref($courseroles->{$udom}) eq 'HASH') {
5566: foreach my $item (keys(%{$courseroles->{$udom}})) {
5567: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5568: my $area = '/'.$cdom.'/'.$cnum;
5569: my $privkey = "user.priv.$crsrole.$area";
5570: if ($crssec ne '') {
5571: $privkey .= '/'.$crssec;
5572: }
5573: $privkey .= ".$area/$group";
5574: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5575: }
5576: }
5577: return;
5578: }
5579:
1.994 raeburn 5580: sub check_adhoc_privs {
1.1104 raeburn 5581: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5582: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5583: my $setprivs;
1.994 raeburn 5584: if ($env{$cckey}) {
5585: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5586: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5587: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5588: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5589: $setprivs = 1;
1.994 raeburn 5590: }
5591: } else {
1.1088 raeburn 5592: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5593: $setprivs = 1;
1.994 raeburn 5594: }
1.1172.2.9 raeburn 5595: return $setprivs;
1.994 raeburn 5596: }
5597:
5598: sub set_adhoc_privileges {
5599: # role can be cc or ca
1.1088 raeburn 5600: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5601: my $area = '/'.$dcdom.'/'.$pickedcourse;
5602: my $spec = $role.'.'.$area;
5603: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5604: $env{'user.name'},1);
1.994 raeburn 5605: my %ccrole = ();
5606: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5607: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5608: &appenv(\%userroles,[$role,'cm']);
5609: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5610: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5611: &appenv( {'request.role' => $spec,
5612: 'request.role.domain' => $dcdom,
5613: 'request.course.sec' => ''
5614: }
5615: );
5616: my $tadv=0;
5617: if (&allowed('adv') eq 'F') { $tadv=1; }
5618: &appenv({'request.role.adv' => $tadv});
5619: }
1.994 raeburn 5620: }
5621:
1.12 www 5622: # --------------------------------------------------------------- get interface
5623:
5624: sub get {
1.131 albertel 5625: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5626: my $items='';
1.800 albertel 5627: foreach my $item (@$storearr) {
5628: $items.=&escape($item).'&';
1.191 harris41 5629: }
1.12 www 5630: $items=~s/\&$//;
1.620 albertel 5631: if (!$udomain) { $udomain=$env{'user.domain'}; }
5632: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5633: my $uhome=&homeserver($uname,$udomain);
5634:
1.133 albertel 5635: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5636: my @pairs=split(/\&/,$rep);
1.273 albertel 5637: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5638: return @pairs;
5639: }
1.15 www 5640: my %returnhash=();
1.42 www 5641: my $i=0;
1.800 albertel 5642: foreach my $item (@$storearr) {
5643: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5644: $i++;
1.191 harris41 5645: }
1.15 www 5646: return %returnhash;
1.27 www 5647: }
5648:
5649: # --------------------------------------------------------------- del interface
5650:
5651: sub del {
1.133 albertel 5652: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5653: my $items='';
1.800 albertel 5654: foreach my $item (@$storearr) {
5655: $items.=&escape($item).'&';
1.191 harris41 5656: }
1.984 neumanie 5657:
1.27 www 5658: $items=~s/\&$//;
1.620 albertel 5659: if (!$udomain) { $udomain=$env{'user.domain'}; }
5660: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5661: my $uhome=&homeserver($uname,$udomain);
5662: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5663: }
5664:
5665: # -------------------------------------------------------------- dump interface
5666:
1.1172.2.22 raeburn 5667: sub unserialize {
5668: my ($rep, $escapedkeys) = @_;
5669:
5670: return {} if $rep =~ /^error/;
5671:
5672: my %returnhash=();
5673: foreach my $item (split(/\&/,$rep)) {
5674: my ($key, $value) = split(/=/, $item, 2);
5675: $key = unescape($key) unless $escapedkeys;
5676: next if $key =~ /^error: 2 /;
5677: $returnhash{$key} = &thaw_unescape($value);
5678: }
5679: return \%returnhash;
5680: }
5681:
5682: # see Lond::dump_with_regexp
5683: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5684: sub dump {
1.1172.2.22 raeburn 5685: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5686: if (!$udomain) { $udomain=$env{'user.domain'}; }
5687: if (!$uname) { $uname=$env{'user.name'}; }
5688: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5689:
1.1172.2.22 raeburn 5690: my $reply;
5691: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5692: # user is hosted on this machine
5693: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5694: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5695: return %{&unserialize($reply, $escapedkeys)};
5696: }
1.755 albertel 5697: if ($regexp) {
5698: $regexp=&escape($regexp);
5699: } else {
5700: $regexp='.';
5701: }
1.1166 raeburn 5702: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5703: my @pairs=split(/\&/,$rep);
5704: my %returnhash=();
1.1098 foxr 5705: if (!($rep =~ /^error/ )) {
5706: foreach my $item (@pairs) {
5707: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5708: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5709: next if ($key =~ /^error: 2 /);
5710: $returnhash{$key}=&thaw_unescape($value);
5711: }
1.755 albertel 5712: }
5713: return %returnhash;
1.407 www 5714: }
5715:
1.1098 foxr 5716:
1.717 albertel 5717: # --------------------------------------------------------- dumpstore interface
5718:
5719: sub dumpstore {
5720: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5721: # same as dump but keys must be escaped. They may contain colon separated
5722: # lists of values that may themself contain colons (e.g. symbs).
5723: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5724: }
5725:
1.407 www 5726: # -------------------------------------------------------------- keys interface
5727:
5728: sub getkeys {
5729: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5730: if (!$udomain) { $udomain=$env{'user.domain'}; }
5731: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5732: my $uhome=&homeserver($uname,$udomain);
5733: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5734: my @keyarray=();
1.800 albertel 5735: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5736: next if ($key =~ /^error: 2 /);
1.800 albertel 5737: push(@keyarray,&unescape($key));
1.407 www 5738: }
5739: return @keyarray;
1.318 matthew 5740: }
5741:
1.319 matthew 5742: # --------------------------------------------------------------- currentdump
5743: sub currentdump {
1.328 matthew 5744: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5745: $courseid = $env{'request.course.id'} if (! defined($courseid));
5746: $sdom = $env{'user.domain'} if (! defined($sdom));
5747: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5748: my $uhome = &homeserver($sname,$sdom);
5749: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5750: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5751: #
1.318 matthew 5752: my %returnhash=();
1.319 matthew 5753: #
5754: if ($rep eq "unknown_cmd") {
5755: # an old lond will not know currentdump
5756: # Do a dump and make it look like a currentdump
1.822 albertel 5757: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5758: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5759: my %hash = @tmp;
5760: @tmp=();
1.424 matthew 5761: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5762: } else {
5763: my @pairs=split(/\&/,$rep);
1.800 albertel 5764: foreach my $pair (@pairs) {
5765: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5766: my ($symb,$param) = split(/:/,$key);
5767: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5768: &thaw_unescape($value);
1.319 matthew 5769: }
1.191 harris41 5770: }
1.12 www 5771: return %returnhash;
1.424 matthew 5772: }
5773:
5774: sub convert_dump_to_currentdump{
5775: my %hash = %{shift()};
5776: my %returnhash;
5777: # Code ripped from lond, essentially. The only difference
5778: # here is the unescaping done by lonnet::dump(). Conceivably
5779: # we might run in to problems with parameter names =~ /^v\./
5780: while (my ($key,$value) = each(%hash)) {
5781: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5782: $symb = &unescape($symb);
5783: $param = &unescape($param);
1.424 matthew 5784: next if ($v eq 'version' || $symb eq 'keys');
5785: next if (exists($returnhash{$symb}) &&
5786: exists($returnhash{$symb}->{$param}) &&
5787: $returnhash{$symb}->{'v.'.$param} > $v);
5788: $returnhash{$symb}->{$param}=$value;
5789: $returnhash{$symb}->{'v.'.$param}=$v;
5790: }
5791: #
5792: # Remove all of the keys in the hashes which keep track of
5793: # the version of the parameter.
5794: while (my ($symb,$param_hash) = each(%returnhash)) {
5795: # use a foreach because we are going to delete from the hash.
5796: foreach my $key (keys(%$param_hash)) {
5797: delete($param_hash->{$key}) if ($key =~ /^v\./);
5798: }
5799: }
5800: return \%returnhash;
1.12 www 5801: }
5802:
1.627 albertel 5803: # ------------------------------------------------------ critical inc interface
5804:
5805: sub cinc {
5806: return &inc(@_,'critical');
5807: }
5808:
1.449 matthew 5809: # --------------------------------------------------------------- inc interface
5810:
5811: sub inc {
1.627 albertel 5812: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5813: if (!$udomain) { $udomain=$env{'user.domain'}; }
5814: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5815: my $uhome=&homeserver($uname,$udomain);
5816: my $items='';
5817: if (! ref($store)) {
5818: # got a single value, so use that instead
5819: $items = &escape($store).'=&';
5820: } elsif (ref($store) eq 'SCALAR') {
5821: $items = &escape($$store).'=&';
5822: } elsif (ref($store) eq 'ARRAY') {
5823: $items = join('=&',map {&escape($_);} @{$store});
5824: } elsif (ref($store) eq 'HASH') {
5825: while (my($key,$value) = each(%{$store})) {
5826: $items.= &escape($key).'='.&escape($value).'&';
5827: }
5828: }
5829: $items=~s/\&$//;
1.627 albertel 5830: if ($critical) {
5831: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5832: } else {
5833: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5834: }
1.449 matthew 5835: }
5836:
1.12 www 5837: # --------------------------------------------------------------- put interface
5838:
5839: sub put {
1.134 albertel 5840: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5841: if (!$udomain) { $udomain=$env{'user.domain'}; }
5842: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5843: my $uhome=&homeserver($uname,$udomain);
1.12 www 5844: my $items='';
1.800 albertel 5845: foreach my $item (keys(%$storehash)) {
5846: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5847: }
1.12 www 5848: $items=~s/\&$//;
1.134 albertel 5849: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5850: }
5851:
1.631 albertel 5852: # ------------------------------------------------------------ newput interface
5853:
5854: sub newput {
5855: my ($namespace,$storehash,$udomain,$uname)=@_;
5856: if (!$udomain) { $udomain=$env{'user.domain'}; }
5857: if (!$uname) { $uname=$env{'user.name'}; }
5858: my $uhome=&homeserver($uname,$udomain);
5859: my $items='';
5860: foreach my $key (keys(%$storehash)) {
5861: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5862: }
5863: $items=~s/\&$//;
5864: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5865: }
5866:
5867: # --------------------------------------------------------- putstore interface
5868:
1.524 raeburn 5869: sub putstore {
1.715 albertel 5870: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5871: if (!$udomain) { $udomain=$env{'user.domain'}; }
5872: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5873: my $uhome=&homeserver($uname,$udomain);
5874: my $items='';
1.715 albertel 5875: foreach my $key (keys(%$storehash)) {
5876: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5877: }
1.715 albertel 5878: $items=~s/\&$//;
1.716 albertel 5879: my $esc_symb=&escape($symb);
5880: my $esc_v=&escape($version);
1.715 albertel 5881: my $reply =
1.716 albertel 5882: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5883: $uhome);
5884: if ($reply eq 'unknown_cmd') {
1.716 albertel 5885: # gfall back to way things use to be done
1.715 albertel 5886: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5887: $uname);
1.524 raeburn 5888: }
1.715 albertel 5889: return $reply;
5890: }
5891:
5892: sub old_putstore {
1.716 albertel 5893: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5894: if (!$udomain) { $udomain=$env{'user.domain'}; }
5895: if (!$uname) { $uname=$env{'user.name'}; }
5896: my $uhome=&homeserver($uname,$udomain);
5897: my %newstorehash;
1.800 albertel 5898: foreach my $item (keys(%$storehash)) {
5899: my $key = $version.':'.&escape($symb).':'.$item;
5900: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5901: }
5902: my $items='';
5903: my %allitems = ();
1.800 albertel 5904: foreach my $item (keys(%newstorehash)) {
5905: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5906: my $key = $1.':keys:'.$2;
5907: $allitems{$key} .= $3.':';
5908: }
1.800 albertel 5909: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5910: }
1.800 albertel 5911: foreach my $item (keys(%allitems)) {
5912: $allitems{$item} =~ s/\:$//;
5913: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5914: }
5915: $items=~s/\&$//;
5916: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5917: }
5918:
1.47 www 5919: # ------------------------------------------------------ critical put interface
5920:
5921: sub cput {
1.134 albertel 5922: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5923: if (!$udomain) { $udomain=$env{'user.domain'}; }
5924: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5925: my $uhome=&homeserver($uname,$udomain);
1.47 www 5926: my $items='';
1.800 albertel 5927: foreach my $item (keys(%$storehash)) {
5928: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5929: }
1.47 www 5930: $items=~s/\&$//;
1.134 albertel 5931: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5932: }
5933:
5934: # -------------------------------------------------------------- eget interface
5935:
5936: sub eget {
1.133 albertel 5937: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5938: my $items='';
1.800 albertel 5939: foreach my $item (@$storearr) {
5940: $items.=&escape($item).'&';
1.191 harris41 5941: }
1.12 www 5942: $items=~s/\&$//;
1.620 albertel 5943: if (!$udomain) { $udomain=$env{'user.domain'}; }
5944: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5945: my $uhome=&homeserver($uname,$udomain);
5946: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5947: my @pairs=split(/\&/,$rep);
5948: my %returnhash=();
1.42 www 5949: my $i=0;
1.800 albertel 5950: foreach my $item (@$storearr) {
5951: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5952: $i++;
1.191 harris41 5953: }
1.12 www 5954: return %returnhash;
5955: }
5956:
1.667 albertel 5957: # ------------------------------------------------------------ tmpput interface
5958: sub tmpput {
1.802 raeburn 5959: my ($storehash,$server,$context)=@_;
1.667 albertel 5960: my $items='';
1.800 albertel 5961: foreach my $item (keys(%$storehash)) {
5962: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5963: }
5964: $items=~s/\&$//;
1.802 raeburn 5965: if (defined($context)) {
5966: $items .= ':'.&escape($context);
5967: }
1.667 albertel 5968: return &reply("tmpput:$items",$server);
5969: }
5970:
5971: # ------------------------------------------------------------ tmpget interface
5972: sub tmpget {
1.688 albertel 5973: my ($token,$server)=@_;
5974: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5975: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5976: my %returnhash;
5977: foreach my $item (split(/\&/,$rep)) {
5978: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5979: next if ($key =~ /^error: 2 /);
1.667 albertel 5980: $returnhash{&unescape($key)}=&thaw_unescape($value);
5981: }
5982: return %returnhash;
5983: }
5984:
1.1113 raeburn 5985: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5986: sub tmpdel {
5987: my ($token,$server)=@_;
5988: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5989: return &reply("tmpdel:$token",$server);
5990: }
5991:
1.1172.2.13 raeburn 5992: # ------------------------------------------------------------ get_timebased_id
5993:
5994: sub get_timebased_id {
5995: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5996: $maxtries) = @_;
5997: my ($newid,$error,$dellock);
5998: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5999: return ('','ok','invalid call to get suffix');
6000: }
6001:
6002: # set defaults for any optional args for which values were not supplied
6003: if ($who eq '') {
6004: $who = $env{'user.name'}.':'.$env{'user.domain'};
6005: }
6006: if (!$locktries) {
6007: $locktries = 3;
6008: }
6009: if (!$maxtries) {
6010: $maxtries = 10;
6011: }
6012:
6013: if (($cdom eq '') || ($cnum eq '')) {
6014: if ($env{'request.course.id'}) {
6015: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6016: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6017: }
6018: if (($cdom eq '') || ($cnum eq '')) {
6019: return ('','ok','call to get suffix not in course context');
6020: }
6021: }
6022:
6023: # construct locking item
6024: my $lockhash = {
6025: $prefix."\0".'locked_'.$keyid => $who,
6026: };
6027: my $tries = 0;
6028:
6029: # attempt to get lock on nohist_$namespace file
6030: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6031: while (($gotlock ne 'ok') && $tries <$locktries) {
6032: $tries ++;
6033: sleep 1;
6034: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6035: }
6036:
6037: # attempt to get unique identifier, based on current timestamp
6038: if ($gotlock eq 'ok') {
6039: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6040: my $id = time;
6041: $newid = $id;
6042: my $idtries = 0;
6043: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6044: if ($idtype eq 'concat') {
6045: $newid = $id.$idtries;
6046: } else {
6047: $newid ++;
6048: }
6049: $idtries ++;
6050: }
6051: if (!exists($inuse{$prefix."\0".$newid})) {
6052: my %new_item = (
6053: $prefix."\0".$newid => $who,
6054: );
6055: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6056: $cdom,$cnum);
6057: if ($putresult ne 'ok') {
6058: undef($newid);
6059: $error = 'error saving new item: '.$putresult;
6060: }
6061: } else {
6062: $error = ('error: no unique suffix available for the new item ');
6063: }
6064: # remove lock
6065: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6066: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6067: } else {
6068: $error = "error: could not obtain lockfile\n";
6069: $dellock = 'ok';
6070: }
6071: return ($newid,$dellock,$error);
6072: }
6073:
1.765 albertel 6074: # -------------------------------------------------- portfolio access checking
6075:
6076: sub portfolio_access {
1.766 albertel 6077: my ($requrl) = @_;
1.765 albertel 6078: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6079: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6080: if ($result) {
6081: my %setters;
6082: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6083: my ($startblock,$endblock) =
6084: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6085: if ($startblock && $endblock) {
6086: return 'B';
6087: }
6088: } else {
6089: my ($startblock,$endblock) =
6090: &Apache::loncommon::blockcheck(\%setters,'port');
6091: if ($startblock && $endblock) {
6092: return 'B';
6093: }
6094: }
6095: }
1.765 albertel 6096: if ($result eq 'ok') {
1.766 albertel 6097: return 'F';
1.765 albertel 6098: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6099: return 'A';
1.765 albertel 6100: }
1.766 albertel 6101: return '';
1.765 albertel 6102: }
6103:
6104: sub get_portfolio_access {
1.767 albertel 6105: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6106:
6107: if (!ref($access_hash)) {
6108: my $current_perms = &get_portfile_permissions($udom,$unum);
6109: my %access_controls = &get_access_controls($current_perms,$group,
6110: $file_name);
6111: $access_hash = $access_controls{$file_name};
6112: }
6113:
1.765 albertel 6114: my ($public,$guest,@domains,@users,@courses,@groups);
6115: my $now = time;
6116: if (ref($access_hash) eq 'HASH') {
6117: foreach my $key (keys(%{$access_hash})) {
6118: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6119: if ($start > $now) {
6120: next;
6121: }
6122: if ($end && $end<$now) {
6123: next;
6124: }
6125: if ($scope eq 'public') {
6126: $public = $key;
6127: last;
6128: } elsif ($scope eq 'guest') {
6129: $guest = $key;
6130: } elsif ($scope eq 'domains') {
6131: push(@domains,$key);
6132: } elsif ($scope eq 'users') {
6133: push(@users,$key);
6134: } elsif ($scope eq 'course') {
6135: push(@courses,$key);
6136: } elsif ($scope eq 'group') {
6137: push(@groups,$key);
6138: }
6139: }
6140: if ($public) {
6141: return 'ok';
6142: }
6143: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6144: if ($guest) {
6145: return $guest;
6146: }
6147: } else {
6148: if (@domains > 0) {
6149: foreach my $domkey (@domains) {
6150: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6151: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6152: return 'ok';
6153: }
6154: }
6155: }
6156: }
6157: if (@users > 0) {
6158: foreach my $userkey (@users) {
1.865 raeburn 6159: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6160: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6161: if (ref($item) eq 'HASH') {
6162: if (($item->{'uname'} eq $env{'user.name'}) &&
6163: ($item->{'udom'} eq $env{'user.domain'})) {
6164: return 'ok';
6165: }
6166: }
6167: }
6168: }
1.765 albertel 6169: }
6170: }
6171: my %roleshash;
6172: my @courses_and_groups = @courses;
6173: push(@courses_and_groups,@groups);
6174: if (@courses_and_groups > 0) {
6175: my (%allgroups,%allroles);
6176: my ($start,$end,$role,$sec,$group);
6177: foreach my $envkey (%env) {
1.1060 raeburn 6178: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6179: my $cid = $2.'_'.$3;
6180: if ($1 eq 'gr') {
6181: $group = $4;
6182: $allgroups{$cid}{$group} = $env{$envkey};
6183: } else {
6184: if ($4 eq '') {
6185: $sec = 'none';
6186: } else {
6187: $sec = $4;
6188: }
6189: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6190: }
1.811 albertel 6191: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6192: my $cid = $2.'_'.$3;
6193: if ($4 eq '') {
6194: $sec = 'none';
6195: } else {
6196: $sec = $4;
6197: }
6198: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6199: }
6200: }
6201: if (keys(%allroles) == 0) {
6202: return;
6203: }
6204: foreach my $key (@courses_and_groups) {
6205: my %content = %{$$access_hash{$key}};
6206: my $cnum = $content{'number'};
6207: my $cdom = $content{'domain'};
6208: my $cid = $cdom.'_'.$cnum;
6209: if (!exists($allroles{$cid})) {
6210: next;
6211: }
6212: foreach my $role_id (keys(%{$content{'roles'}})) {
6213: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6214: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6215: my @status = @{$content{'roles'}{$role_id}{'access'}};
6216: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6217: foreach my $role (keys(%{$allroles{$cid}})) {
6218: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6219: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6220: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6221: if (grep/^all$/,@sections) {
6222: return 'ok';
6223: } else {
6224: if (grep/^$sec$/,@sections) {
6225: return 'ok';
6226: }
6227: }
6228: }
6229: }
6230: if (keys(%{$allgroups{$cid}}) == 0) {
6231: if (grep/^none$/,@groups) {
6232: return 'ok';
6233: }
6234: } else {
6235: if (grep/^all$/,@groups) {
6236: return 'ok';
6237: }
6238: foreach my $group (keys(%{$allgroups{$cid}})) {
6239: if (grep/^$group$/,@groups) {
6240: return 'ok';
6241: }
6242: }
6243: }
6244: }
6245: }
6246: }
6247: }
6248: }
6249: if ($guest) {
6250: return $guest;
6251: }
6252: }
6253: }
6254: return;
6255: }
6256:
6257: sub course_group_datechecker {
6258: my ($dates,$now,$status) = @_;
6259: my ($start,$end) = split(/\./,$dates);
6260: if (!$start && !$end) {
6261: return 'ok';
6262: }
6263: if (grep/^active$/,@{$status}) {
6264: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6265: return 'ok';
6266: }
6267: }
6268: if (grep/^previous$/,@{$status}) {
6269: if ($end > $now ) {
6270: return 'ok';
6271: }
6272: }
6273: if (grep/^future$/,@{$status}) {
6274: if ($start > $now) {
6275: return 'ok';
6276: }
6277: }
6278: return;
6279: }
6280:
6281: sub parse_portfolio_url {
6282: my ($url) = @_;
6283:
6284: my ($type,$udom,$unum,$group,$file_name);
6285:
1.823 albertel 6286: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6287: $type = 1;
6288: $udom = $1;
6289: $unum = $2;
6290: $file_name = $3;
1.823 albertel 6291: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6292: $type = 2;
6293: $udom = $1;
6294: $unum = $2;
6295: $group = $3;
6296: $file_name = $3.'/'.$4;
6297: }
6298: if (wantarray) {
6299: return ($type,$udom,$unum,$file_name,$group);
6300: }
6301: return $type;
6302: }
6303:
6304: sub is_portfolio_url {
6305: my ($url) = @_;
6306: return scalar(&parse_portfolio_url($url));
6307: }
6308:
1.798 raeburn 6309: sub is_portfolio_file {
6310: my ($file) = @_;
1.820 raeburn 6311: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6312: return 1;
6313: }
6314: return;
6315: }
6316:
1.976 raeburn 6317: sub usertools_access {
1.1084 raeburn 6318: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6319: my ($access,%tools);
6320: if ($context eq '') {
6321: $context = 'tools';
6322: }
6323: if ($context eq 'requestcourses') {
6324: %tools = (
6325: official => 1,
6326: unofficial => 1,
1.1006 raeburn 6327: community => 1,
1.1172.2.37 raeburn 6328: textbook => 1,
1.985 raeburn 6329: );
1.1172.2.9 raeburn 6330: } elsif ($context eq 'requestauthor') {
6331: %tools = (
6332: requestauthor => 1,
6333: );
1.985 raeburn 6334: } else {
6335: %tools = (
6336: aboutme => 1,
6337: blog => 1,
1.1172.2.6 raeburn 6338: webdav => 1,
1.985 raeburn 6339: portfolio => 1,
6340: );
6341: }
1.976 raeburn 6342: return if (!defined($tools{$tool}));
6343:
1.1172.2.35 raeburn 6344: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6345: $udom = $env{'user.domain'};
6346: $uname = $env{'user.name'};
6347: }
6348:
1.978 raeburn 6349: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6350: if ($action ne 'reload') {
1.985 raeburn 6351: if ($context eq 'requestcourses') {
6352: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6353: } elsif ($context eq 'requestauthor') {
6354: return $env{'environment.canrequest.author'};
1.985 raeburn 6355: } else {
6356: return $env{'environment.availabletools.'.$tool};
6357: }
6358: }
1.976 raeburn 6359: }
6360:
1.1172.2.9 raeburn 6361: my ($toolstatus,$inststatus,$envkey);
6362: if ($context eq 'requestauthor') {
6363: $envkey = $context;
6364: } else {
6365: $envkey = $context.'.'.$tool;
6366: }
1.976 raeburn 6367:
1.985 raeburn 6368: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6369: ($action ne 'reload')) {
1.1172.2.9 raeburn 6370: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6371: $inststatus = $env{'environment.inststatus'};
6372: } else {
1.1084 raeburn 6373: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6374: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6375: $inststatus = $userenvref->{'inststatus'};
6376: } else {
1.1172.2.9 raeburn 6377: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6378: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6379: $inststatus = $userenv{'inststatus'};
6380: }
1.976 raeburn 6381: }
6382:
6383: if ($toolstatus ne '') {
6384: if ($toolstatus) {
6385: $access = 1;
6386: } else {
6387: $access = 0;
6388: }
6389: return $access;
6390: }
6391:
1.1084 raeburn 6392: my ($is_adv,%domdef);
6393: if (ref($is_advref) eq 'HASH') {
6394: $is_adv = $is_advref->{'is_adv'};
6395: } else {
6396: $is_adv = &is_advanced_user($udom,$uname);
6397: }
6398: if (ref($domdefref) eq 'HASH') {
6399: %domdef = %{$domdefref};
6400: } else {
6401: %domdef = &get_domain_defaults($udom);
6402: }
1.976 raeburn 6403: if (ref($domdef{$tool}) eq 'HASH') {
6404: if ($is_adv) {
6405: if ($domdef{$tool}{'_LC_adv'} ne '') {
6406: if ($domdef{$tool}{'_LC_adv'}) {
6407: $access = 1;
6408: } else {
6409: $access = 0;
6410: }
6411: return $access;
6412: }
6413: }
6414: if ($inststatus ne '') {
6415: my ($hasaccess,$hasnoaccess);
6416: foreach my $affiliation (split(/:/,$inststatus)) {
6417: if ($domdef{$tool}{$affiliation} ne '') {
6418: if ($domdef{$tool}{$affiliation}) {
6419: $hasaccess = 1;
6420: } else {
6421: $hasnoaccess = 1;
6422: }
6423: }
6424: }
6425: if ($hasaccess || $hasnoaccess) {
6426: if ($hasaccess) {
6427: $access = 1;
6428: } elsif ($hasnoaccess) {
6429: $access = 0;
6430: }
6431: return $access;
6432: }
6433: } else {
6434: if ($domdef{$tool}{'default'} ne '') {
6435: if ($domdef{$tool}{'default'}) {
6436: $access = 1;
6437: } elsif ($domdef{$tool}{'default'} == 0) {
6438: $access = 0;
6439: }
6440: return $access;
6441: }
6442: }
6443: } else {
1.1172.2.6 raeburn 6444: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6445: $access = 1;
6446: } else {
6447: $access = 0;
6448: }
1.976 raeburn 6449: return $access;
6450: }
6451: }
6452:
1.1050 raeburn 6453: sub is_course_owner {
6454: my ($cdom,$cnum,$udom,$uname) = @_;
6455: if (($udom eq '') || ($uname eq '')) {
6456: $udom = $env{'user.domain'};
6457: $uname = $env{'user.name'};
6458: }
6459: unless (($udom eq '') || ($uname eq '')) {
6460: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6461: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6462: return 1;
6463: } else {
6464: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6465: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6466: return 1;
6467: }
6468: }
6469: }
6470: }
6471: return;
6472: }
6473:
1.976 raeburn 6474: sub is_advanced_user {
6475: my ($udom,$uname) = @_;
1.1085 raeburn 6476: if ($udom ne '' && $uname ne '') {
6477: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6478: if (wantarray) {
6479: return ($env{'user.adv'},$env{'user.author'});
6480: } else {
6481: return $env{'user.adv'};
6482: }
1.1085 raeburn 6483: }
6484: }
1.976 raeburn 6485: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6486: my %allroles;
1.1128 raeburn 6487: my ($is_adv,$is_author);
1.976 raeburn 6488: foreach my $role (keys(%roleshash)) {
6489: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6490: my $area = '/'.$tdomain.'/'.$trest;
6491: if ($sec ne '') {
6492: $area .= '/'.$sec;
6493: }
6494: if (($area ne '') && ($trole ne '')) {
6495: my $spec=$trole.'.'.$area;
6496: if ($trole =~ /^cr\//) {
6497: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6498: } elsif ($trole ne 'gr') {
6499: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6500: }
1.1128 raeburn 6501: if ($trole eq 'au') {
6502: $is_author = 1;
6503: }
1.976 raeburn 6504: }
6505: }
6506: foreach my $role (keys(%allroles)) {
6507: last if ($is_adv);
6508: foreach my $item (split(/:/,$allroles{$role})) {
6509: if ($item ne '') {
6510: my ($privilege,$restrictions)=split(/&/,$item);
6511: if ($privilege eq 'adv') {
6512: $is_adv = 1;
6513: last;
6514: }
6515: }
6516: }
6517: }
1.1128 raeburn 6518: if (wantarray) {
6519: return ($is_adv,$is_author);
6520: }
1.976 raeburn 6521: return $is_adv;
6522: }
1.798 raeburn 6523:
1.1035 raeburn 6524: sub check_can_request {
1.1036 raeburn 6525: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6526: my $canreq = 0;
6527: my ($types,$typename) = &Apache::loncommon::course_types();
6528: my @options = ('approval','validate','autolimit');
6529: my $optregex = join('|',@options);
6530: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6531: foreach my $type (@{$types}) {
6532: if (&usertools_access($env{'user.name'},
6533: $env{'user.domain'},
6534: $type,undef,'requestcourses')) {
6535: $canreq ++;
1.1036 raeburn 6536: if (ref($request_domains) eq 'HASH') {
6537: push(@{$request_domains->{$type}},$env{'user.domain'});
6538: }
1.1035 raeburn 6539: if ($dom eq $env{'user.domain'}) {
6540: $can_request->{$type} = 1;
6541: }
6542: }
6543: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6544: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6545: if (@curr > 0) {
1.1036 raeburn 6546: foreach my $item (@curr) {
6547: if (ref($request_domains) eq 'HASH') {
6548: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6549: if ($otherdom ne '') {
6550: if (ref($request_domains->{$type}) eq 'ARRAY') {
6551: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6552: push(@{$request_domains->{$type}},$otherdom);
6553: }
6554: } else {
6555: push(@{$request_domains->{$type}},$otherdom);
6556: }
6557: }
6558: }
6559: }
6560: unless($dom eq $env{'user.domain'}) {
6561: $canreq ++;
1.1035 raeburn 6562: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6563: $can_request->{$type} = 1;
6564: }
6565: }
6566: }
6567: }
6568: }
6569: }
6570: return $canreq;
6571: }
6572:
1.341 www 6573: # ---------------------------------------------- Custom access rule evaluation
6574:
6575: sub customaccess {
6576: my ($priv,$uri)=@_;
1.807 albertel 6577: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6578: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6579: $udom = &LONCAPA::clean_domain($udom);
6580: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6581: my $access=0;
1.800 albertel 6582: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6583: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6584: if ($type eq 'user') {
6585: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6586: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6587: if ($tdom) {
6588: if ($tdom ne $env{'user.domain'}) { next; }
6589: }
1.896 albertel 6590: if ($tuname) {
6591: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6592: }
6593: $access=($effect eq 'allow');
6594: last;
6595: }
6596: } else {
6597: if ($role) {
6598: if ($role ne $urole) { next; }
6599: }
6600: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6601: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6602: if ($tdom) {
6603: if ($tdom ne $udom) { next; }
6604: }
6605: if ($tcrs) {
6606: if ($tcrs ne $ucrs) { next; }
6607: }
6608: if ($tsec) {
6609: if ($tsec ne $usec) { next; }
6610: }
6611: $access=($effect eq 'allow');
6612: last;
6613: }
6614: if ($realm eq '' && $role eq '') {
6615: $access=($effect eq 'allow');
6616: }
1.402 bowersj2 6617: }
1.341 www 6618: }
6619: return $access;
6620: }
6621:
1.103 harris41 6622: # ------------------------------------------------- Check for a user privilege
1.12 www 6623:
6624: sub allowed {
1.810 raeburn 6625: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6626: my $ver_orguri=$uri;
1.439 www 6627: $uri=&deversion($uri);
1.152 www 6628: my $orguri=$uri;
1.52 www 6629: $uri=&declutter($uri);
1.809 raeburn 6630:
1.810 raeburn 6631: if ($priv eq 'evb') {
6632: # Evade communication block restrictions for specified role in a course
6633: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6634: return $1;
6635: } else {
6636: return;
6637: }
6638: }
6639:
1.620 albertel 6640: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6641: # Free bre access to adm and meta resources
1.775 albertel 6642: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6643: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6644: && ($priv eq 'bre')) {
1.14 www 6645: return 'F';
1.159 www 6646: }
6647:
1.545 banghart 6648: # Free bre access to user's own portfolio contents
1.714 raeburn 6649: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6650: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6651: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6652: my %setters;
6653: my ($startblock,$endblock) =
6654: &Apache::loncommon::blockcheck(\%setters,'port');
6655: if ($startblock && $endblock) {
6656: return 'B';
6657: } else {
6658: return 'F';
6659: }
1.545 banghart 6660: }
6661:
1.762 raeburn 6662: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6663: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6664: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6665: if (exists($env{'request.course.id'})) {
6666: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6667: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6668: if (($domain eq $cdom) && ($name eq $cnum)) {
6669: my $courseprivid=$env{'request.course.id'};
6670: $courseprivid=~s/\_/\//;
6671: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6672: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6673: return $1;
1.762 raeburn 6674: } else {
6675: if ($env{'request.course.sec'}) {
6676: $courseprivid.='/'.$env{'request.course.sec'};
6677: }
6678: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6679: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6680: return $2;
6681: }
1.714 raeburn 6682: }
6683: }
6684: }
6685: }
6686:
1.159 www 6687: # Free bre to public access
6688:
6689: if ($priv eq 'bre') {
1.238 www 6690: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6691: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6692: return 'F';
6693: }
1.238 www 6694: if ($copyright eq 'priv') {
6695: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6696: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6697: return '';
6698: }
6699: }
6700: if ($copyright eq 'domain') {
6701: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6702: unless (($env{'user.domain'} eq $1) ||
6703: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6704: return '';
6705: }
1.262 matthew 6706: }
1.620 albertel 6707: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6708: # Library role, so allow browsing of resources in this domain.
6709: return 'F';
1.238 www 6710: }
1.341 www 6711: if ($copyright eq 'custom') {
6712: unless (&customaccess($priv,$uri)) { return ''; }
6713: }
1.14 www 6714: }
1.264 matthew 6715: # Domain coordinator is trying to create a course
1.620 albertel 6716: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6717: # uri is the requested domain in this case.
6718: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6719: # a role of dc for the domain in question.
1.620 albertel 6720: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6721: }
1.29 www 6722:
1.52 www 6723: my $thisallowed='';
6724: my $statecond=0;
6725: my $courseprivid='';
6726:
1.1039 raeburn 6727: my $ownaccess;
1.1043 raeburn 6728: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6729: if (($priv eq 'bro') && ($env{'user.author'})) {
6730: if ($uri eq '') {
6731: $ownaccess = 1;
6732: } else {
6733: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6734: my $udom = $env{'user.domain'};
6735: my $uname = $env{'user.name'};
6736: if ($uri =~ m{^\Q$udom\E/?$}) {
6737: $ownaccess = 1;
1.1040 raeburn 6738: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6739: unless ($uri =~ m{\.\./}) {
6740: $ownaccess = 1;
6741: }
6742: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6743: my $now = time;
6744: if ($uri =~ m{^([^/]+)/?$}) {
6745: my $adom = $1;
6746: foreach my $key (keys(%env)) {
1.1042 raeburn 6747: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6748: my ($start,$end) = split('.',$env{$key});
6749: if (($now >= $start) && (!$end || $end < $now)) {
6750: $ownaccess = 1;
6751: last;
6752: }
6753: }
6754: }
6755: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6756: my $adom = $1;
6757: my $aname = $2;
1.1042 raeburn 6758: foreach my $role ('ca','aa') {
6759: if ($env{"user.role.$role./$adom/$aname"}) {
6760: my ($start,$end) =
6761: split('.',$env{"user.role.$role./$adom/$aname"});
6762: if (($now >= $start) && (!$end || $end < $now)) {
6763: $ownaccess = 1;
6764: last;
6765: }
1.1039 raeburn 6766: }
6767: }
6768: }
6769: }
6770: }
6771: }
6772: }
6773:
1.52 www 6774: # Course
6775:
1.620 albertel 6776: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6777: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6778: $thisallowed.=$1;
6779: }
1.52 www 6780: }
1.29 www 6781:
1.52 www 6782: # Domain
6783:
1.620 albertel 6784: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6785: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6786: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6787: $thisallowed.=$1;
6788: }
1.12 www 6789: }
1.52 www 6790:
1.1141 raeburn 6791: # User who is not author or co-author might still be able to edit
6792: # resource of an author in the domain (e.g., if Domain Coordinator).
6793: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6794: (&allowed('mdc',$env{'request.course.id'}))) {
6795: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6796: $thisallowed.=$1;
6797: }
6798: }
6799:
1.52 www 6800: # Course: uri itself is a course
1.66 www 6801: my $courseuri=$uri;
6802: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6803: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6804:
1.620 albertel 6805: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6806: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6807: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6808: $thisallowed.=$1;
6809: }
1.12 www 6810: }
1.29 www 6811:
1.665 albertel 6812: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6813: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6814: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6815: $thisallowed='';
1.671 raeburn 6816: my ($match)=&is_on_map($uri);
6817: if ($match) {
6818: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6819: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6820: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6821: if (@blockers > 0) {
6822: $thisallowed = 'B';
6823: } else {
6824: $thisallowed.=$1;
6825: }
1.671 raeburn 6826: }
6827: } else {
1.705 albertel 6828: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6829: if ($refuri) {
6830: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6831: $thisallowed='F';
1.671 raeburn 6832: } else {
6833: $refuri=&declutter($refuri);
6834: my ($match) = &is_on_map($refuri);
6835: if ($match) {
1.1162 raeburn 6836: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6837: if (@blockers > 0) {
6838: $thisallowed = 'B';
6839: } else {
6840: $thisallowed='F';
6841: }
1.671 raeburn 6842: }
1.669 raeburn 6843: }
1.671 raeburn 6844: }
6845: }
1.314 www 6846: }
1.492 albertel 6847:
1.766 albertel 6848: if ($priv eq 'bre'
6849: && $thisallowed ne 'F'
6850: && $thisallowed ne '2'
6851: && &is_portfolio_url($uri)) {
6852: $thisallowed = &portfolio_access($uri);
6853: }
6854:
1.52 www 6855: # Full access at system, domain or course-wide level? Exit.
1.29 www 6856: if ($thisallowed=~/F/) {
6857: return 'F';
6858: }
6859:
1.52 www 6860: # If this is generating or modifying users, exit with special codes
1.29 www 6861:
1.643 www 6862: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6863: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6864: my ($audom,$auname)=split('/',$uri);
1.643 www 6865: # no author name given, so this just checks on the general right to make a co-author in this domain
6866: unless ($auname) { return $thisallowed; }
6867: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6868: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6869: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6870: ($audom ne $env{'request.role.domain'}))) { return ''; }
6871: }
1.52 www 6872: return $thisallowed;
6873: }
6874: #
1.103 harris41 6875: # Gathered so far: system, domain and course wide privileges
1.52 www 6876: #
6877: # Course: See if uri or referer is an individual resource that is part of
6878: # the course
6879:
1.620 albertel 6880: if ($env{'request.course.id'}) {
1.232 www 6881:
1.620 albertel 6882: $courseprivid=$env{'request.course.id'};
6883: if ($env{'request.course.sec'}) {
6884: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6885: }
6886: $courseprivid=~s/\_/\//;
6887: my $checkreferer=1;
1.232 www 6888: my ($match,$cond)=&is_on_map($uri);
6889: if ($match) {
6890: $statecond=$cond;
1.620 albertel 6891: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6892: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6893: my $value = $1;
6894: if ($priv eq 'bre') {
6895: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6896: if (@blockers > 0) {
6897: $thisallowed = 'B';
6898: } else {
6899: $thisallowed.=$value;
6900: }
6901: } else {
6902: $thisallowed.=$value;
6903: }
1.52 www 6904: $checkreferer=0;
6905: }
1.29 www 6906: }
1.83 www 6907:
1.148 www 6908: if ($checkreferer) {
1.620 albertel 6909: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6910: unless ($refuri) {
1.800 albertel 6911: foreach my $key (keys(%env)) {
6912: if ($key=~/^httpref\..*\*/) {
6913: my $pattern=$key;
1.156 www 6914: $pattern=~s/^httpref\.\/res\///;
1.148 www 6915: $pattern=~s/\*/\[\^\/\]\+/g;
6916: $pattern=~s/\//\\\//g;
1.152 www 6917: if ($orguri=~/$pattern/) {
1.800 albertel 6918: $refuri=$env{$key};
1.148 www 6919: }
6920: }
1.191 harris41 6921: }
1.148 www 6922: }
1.232 www 6923:
1.148 www 6924: if ($refuri) {
1.152 www 6925: $refuri=&declutter($refuri);
1.232 www 6926: my ($match,$cond)=&is_on_map($refuri);
6927: if ($match) {
6928: my $refstatecond=$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') {
6933: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6934: if (@blockers > 0) {
6935: $thisallowed = 'B';
6936: } else {
6937: $thisallowed.=$value;
6938: }
6939: } else {
6940: $thisallowed.=$value;
6941: }
1.53 www 6942: $uri=$refuri;
6943: $statecond=$refstatecond;
1.52 www 6944: }
6945: }
1.148 www 6946: }
1.29 www 6947: }
1.52 www 6948: }
1.29 www 6949:
1.52 www 6950: #
1.103 harris41 6951: # Gathered now: all privileges that could apply, and condition number
1.52 www 6952: #
6953: #
6954: # Full or no access?
6955: #
1.29 www 6956:
1.52 www 6957: if ($thisallowed=~/F/) {
6958: return 'F';
6959: }
1.29 www 6960:
1.52 www 6961: unless ($thisallowed) {
6962: return '';
6963: }
1.29 www 6964:
1.52 www 6965: # Restrictions exist, deal with them
6966: #
6967: # C:according to course preferences
6968: # R:according to resource settings
6969: # L:unless locked
6970: # X:according to user session state
6971: #
6972:
6973: # Possibly locked functionality, check all courses
1.54 www 6974: # Locks might take effect only after 10 minutes cache expiration for other
6975: # courses, and 2 minutes for current course
1.52 www 6976:
6977: my $envkey;
6978: if ($thisallowed=~/L/) {
1.1000 raeburn 6979: foreach $envkey (keys(%env)) {
1.54 www 6980: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6981: my $courseid=$2;
6982: my $roleid=$1.'.'.$2;
1.92 www 6983: $courseid=~s/^\///;
1.54 www 6984: my $expiretime=600;
1.620 albertel 6985: if ($env{'request.role'} eq $roleid) {
1.54 www 6986: $expiretime=120;
6987: }
6988: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6989: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6990: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6991: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6992: }
1.620 albertel 6993: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6994: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6995: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6996: &log($env{'user.domain'},$env{'user.name'},
6997: $env{'user.home'},
1.57 www 6998: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6999: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7000: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7001: return '';
7002: }
7003: }
1.620 albertel 7004: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7005: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7006: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7007: &log($env{'user.domain'},$env{'user.name'},
7008: $env{'user.home'},
1.57 www 7009: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7010: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7011: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7012: return '';
7013: }
7014: }
7015: }
1.29 www 7016: }
1.52 www 7017: }
7018:
7019: #
7020: # Rest of the restrictions depend on selected course
7021: #
7022:
1.620 albertel 7023: unless ($env{'request.course.id'}) {
1.766 albertel 7024: if ($thisallowed eq 'A') {
7025: return 'A';
1.814 raeburn 7026: } elsif ($thisallowed eq 'B') {
7027: return 'B';
1.766 albertel 7028: } else {
7029: return '1';
7030: }
1.52 www 7031: }
1.29 www 7032:
1.52 www 7033: #
7034: # Now user is definitely in a course
7035: #
1.53 www 7036:
7037:
7038: # Course preferences
7039:
7040: if ($thisallowed=~/C/) {
1.620 albertel 7041: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7042: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7043: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7044: =~/\Q$rolecode\E/) {
1.1103 raeburn 7045: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7046: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7047: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7048: $env{'request.course.id'});
7049: }
1.237 www 7050: return '';
7051: }
7052:
1.620 albertel 7053: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7054: =~/\Q$unamedom\E/) {
1.1103 raeburn 7055: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7056: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7057: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7058: $env{'request.course.id'});
7059: }
1.54 www 7060: return '';
7061: }
1.53 www 7062: }
7063:
7064: # Resource preferences
7065:
7066: if ($thisallowed=~/R/) {
1.620 albertel 7067: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7068: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7069: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7070: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7071: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7072: }
7073: return '';
1.54 www 7074: }
1.53 www 7075: }
1.30 www 7076:
1.246 www 7077: # Restricted by state or randomout?
1.30 www 7078:
1.52 www 7079: if ($thisallowed=~/X/) {
1.620 albertel 7080: if ($env{'acc.randomout'}) {
1.579 albertel 7081: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7082: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7083: return '';
7084: }
1.247 www 7085: }
7086: if (&condval($statecond)) {
1.52 www 7087: return '2';
7088: } else {
7089: return '';
7090: }
7091: }
1.30 www 7092:
1.766 albertel 7093: if ($thisallowed eq 'A') {
7094: return 'A';
1.814 raeburn 7095: } elsif ($thisallowed eq 'B') {
7096: return 'B';
1.766 albertel 7097: }
1.52 www 7098: return 'F';
1.232 www 7099: }
1.1162 raeburn 7100:
1.1172.2.13 raeburn 7101: # ------------------------------------------- Check construction space access
7102:
7103: sub constructaccess {
7104: my ($url,$setpriv)=@_;
7105:
7106: # We do not allow editing of previous versions of files
7107: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7108:
7109: # Get username and domain from URL
7110: my ($ownername,$ownerdomain,$ownerhome);
7111:
7112: ($ownerdomain,$ownername) =
7113: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7114:
7115: # The URL does not really point to any authorspace, forget it
7116: unless (($ownername) && ($ownerdomain)) { return ''; }
7117:
7118: # Now we need to see if the user has access to the authorspace of
7119: # $ownername at $ownerdomain
7120:
7121: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7122: # Real author for this?
7123: $ownerhome = $env{'user.home'};
7124: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7125: return ($ownername,$ownerdomain,$ownerhome);
7126: }
7127: } else {
7128: # Co-author for this?
7129: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7130: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7131: $ownerhome = &homeserver($ownername,$ownerdomain);
7132: return ($ownername,$ownerdomain,$ownerhome);
7133: }
7134: }
7135:
7136: # We don't have any access right now. If we are not possibly going to do anything about this,
7137: # we might as well leave
7138: unless ($setpriv) { return ''; }
7139:
7140: # Backdoor access?
7141: my $allowed=&allowed('eco',$ownerdomain);
7142: # Nope
7143: unless ($allowed) { return ''; }
7144: # Looks like we may have access, but could be locked by the owner of the construction space
7145: if ($allowed eq 'U') {
7146: my %blocked=&get('environment',['domcoord.author'],
7147: $ownerdomain,$ownername);
7148: # Is blocked by owner
7149: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7150: }
7151: if (($allowed eq 'F') || ($allowed eq 'U')) {
7152: # Grant temporary access
7153: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7154: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7155: if (!$update) { $update = $then; }
7156: my $refresh=$env{'user.refresh.time'};
7157: if (!$refresh) { $refresh = $update; }
7158: my $now = time;
7159: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7160: $now,'ca','constructaccess');
7161: $ownerhome = &homeserver($ownername,$ownerdomain);
7162: return($ownername,$ownerdomain,$ownerhome);
7163: }
7164: # No business here
7165: return '';
7166: }
7167:
1.1162 raeburn 7168: sub get_comm_blocks {
7169: my ($cdom,$cnum) = @_;
7170: if ($cdom eq '' || $cnum eq '') {
7171: return unless ($env{'request.course.id'});
7172: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7173: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7174: }
7175: my %commblocks;
7176: my $hashid=$cdom.'_'.$cnum;
7177: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7178: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7179: %commblocks = %{$blocksref};
7180: } else {
7181: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7182: my $cachetime = 600;
7183: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7184: }
7185: return %commblocks;
7186: }
7187:
7188: sub has_comm_blocking {
7189: my ($priv,$symb,$uri,$blocks) = @_;
7190: return unless ($env{'request.course.id'});
7191: return unless ($priv eq 'bre');
7192: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7193: my %commblocks;
7194: if (ref($blocks) eq 'HASH') {
7195: %commblocks = %{$blocks};
7196: } else {
7197: %commblocks = &get_comm_blocks();
7198: }
7199: return unless (keys(%commblocks) > 0);
7200: if (!$symb) { $symb=&symbread($uri,1); }
7201: my ($map,$resid,undef)=&decode_symb($symb);
7202: my %tocheck = (
7203: maps => $map,
7204: resources => $symb,
7205: );
7206: my @blockers;
7207: my $now = time;
1.1163 raeburn 7208: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7209: foreach my $block (keys(%commblocks)) {
7210: if ($block =~ /^(\d+)____(\d+)$/) {
7211: my ($start,$end) = ($1,$2);
7212: if ($start <= $now && $end >= $now) {
7213: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7214: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7215: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7216: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7217: unless (grep(/^\Q$block\E$/,@blockers)) {
7218: push(@blockers,$block);
7219: }
7220: }
7221: }
7222: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7223: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7224: unless (grep(/^\Q$block\E$/,@blockers)) {
7225: push(@blockers,$block);
7226: }
7227: }
7228: }
7229: }
7230: }
7231: }
7232: } elsif ($block =~ /^firstaccess____(.+)$/) {
7233: my $item = $1;
1.1163 raeburn 7234: my @to_test;
1.1162 raeburn 7235: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7236: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7237: my $check_interval;
7238: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7239: my @interval;
7240: my $type = 'map';
7241: if ($item eq 'course') {
7242: $type = 'course';
7243: @interval=&EXT("resource.0.interval");
7244: } else {
7245: if ($item =~ /___\d+___/) {
7246: $type = 'resource';
7247: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7248: if (ref($navmap)) {
7249: my $res = $navmap->getBySymb($item);
7250: push(@to_test,$res);
7251: }
1.1162 raeburn 7252: } else {
7253: my $mapsymb = &symbread($item,1);
7254: if ($mapsymb) {
7255: if (ref($navmap)) {
7256: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7257: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7258: foreach my $res (@to_test) {
1.1162 raeburn 7259: my $symb = $res->symb();
7260: next if ($symb eq $mapsymb);
7261: if ($symb ne '') {
7262: @interval=&EXT("resource.0.interval",$symb);
7263: last;
7264: }
7265: }
7266: }
7267: }
7268: }
7269: }
7270: if ($interval[0] =~ /\d+/) {
7271: my $first_access;
7272: if ($type eq 'resource') {
7273: $first_access=&get_first_access($interval[1],$item);
7274: } elsif ($type eq 'map') {
7275: $first_access=&get_first_access($interval[1],undef,$item);
7276: } else {
7277: $first_access=&get_first_access($interval[1]);
7278: }
7279: if ($first_access) {
7280: my $timesup = $first_access+$interval[0];
7281: if ($timesup > $now) {
1.1163 raeburn 7282: foreach my $res (@to_test) {
7283: if ($res->is_problem()) {
7284: if ($res->completable()) {
7285: unless (grep(/^\Q$block\E$/,@blockers)) {
7286: push(@blockers,$block);
7287: }
7288: last;
7289: }
7290: }
1.1162 raeburn 7291: }
7292: }
7293: }
7294: }
7295: }
7296: }
7297: }
7298: }
7299: }
7300: return @blockers;
7301: }
7302:
7303: sub check_docs_block {
7304: my ($docsblock,$tocheck) =@_;
7305: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7306: return;
7307: }
7308: if (ref($docsblock->{'maps'}) eq 'HASH') {
7309: if ($tocheck->{'maps'}) {
7310: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7311: return 1;
7312: }
7313: }
7314: }
7315: if (ref($docsblock->{'resources'}) eq 'HASH') {
7316: if ($tocheck->{'resources'}) {
7317: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7318: return 1;
7319: }
7320: }
7321: }
7322: return;
7323: }
7324:
1.1133 foxr 7325: #
7326: # Removes the versino from a URI and
7327: # splits it in to its filename and path to the filename.
7328: # Seems like File::Basename could have done this more clearly.
7329: # Parameters:
7330: # $uri - input URI
7331: # Returns:
7332: # Two element list consisting of
7333: # $pathname - the URI up to and excluding the trailing /
7334: # $filename - The part of the URI following the last /
7335: # NOTE:
7336: # Another realization of this is simply:
7337: # use File::Basename;
7338: # ...
7339: # $uri = shift;
7340: # $filename = basename($uri);
7341: # $path = dirname($uri);
7342: # return ($filename, $path);
7343: #
7344: # The implementation below is probably faster however.
7345: #
1.710 albertel 7346: sub split_uri_for_cond {
7347: my $uri=&deversion(&declutter(shift));
7348: my @uriparts=split(/\//,$uri);
7349: my $filename=pop(@uriparts);
7350: my $pathname=join('/',@uriparts);
7351: return ($pathname,$filename);
7352: }
1.232 www 7353: # --------------------------------------------------- Is a resource on the map?
7354:
7355: sub is_on_map {
1.710 albertel 7356: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7357: #Trying to find the conditional for the file
1.620 albertel 7358: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7359: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7360: if ($match) {
1.289 bowersj2 7361: return (1,$1);
7362: } else {
1.434 www 7363: return (0,0);
1.289 bowersj2 7364: }
1.12 www 7365: }
7366:
1.427 www 7367: # --------------------------------------------------------- Get symb from alias
7368:
7369: sub get_symb_from_alias {
7370: my $symb=shift;
7371: my ($map,$resid,$url)=&decode_symb($symb);
7372: # Already is a symb
7373: if ($url) { return $symb; }
7374: # Must be an alias
7375: my $aliassymb='';
7376: my %bighash;
1.620 albertel 7377: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7378: &GDBM_READER(),0640)) {
7379: my $rid=$bighash{'mapalias_'.$symb};
7380: if ($rid) {
7381: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7382: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7383: $resid,$bighash{'src_'.$rid});
1.427 www 7384: }
7385: untie %bighash;
7386: }
7387: return $aliassymb;
7388: }
7389:
1.12 www 7390: # ----------------------------------------------------------------- Define Role
7391:
7392: sub definerole {
7393: if (allowed('mcr','/')) {
7394: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7395: foreach my $role (split(':',$sysrole)) {
7396: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7397: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7398: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7399: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7400: return "refused:s:$crole&$cqual";
7401: }
7402: }
1.191 harris41 7403: }
1.800 albertel 7404: foreach my $role (split(':',$domrole)) {
7405: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7406: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7407: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7408: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7409: return "refused:d:$crole&$cqual";
7410: }
7411: }
1.191 harris41 7412: }
1.800 albertel 7413: foreach my $role (split(':',$courole)) {
7414: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7415: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7416: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7417: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7418: return "refused:c:$crole&$cqual";
7419: }
7420: }
1.191 harris41 7421: }
1.620 albertel 7422: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7423: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7424: "rolesdef_$rolename=".
7425: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7426: return reply($command,$env{'user.home'});
1.12 www 7427: } else {
7428: return 'refused';
7429: }
1.105 harris41 7430: }
7431:
7432: # ---------------- Make a metadata query against the network of library servers
7433:
7434: sub metadata_query {
1.1172.2.33 raeburn 7435: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7436: my %rhash;
1.845 albertel 7437: my %libserv = &all_library();
1.244 matthew 7438: my @server_list = (defined($server_array) ? @$server_array
7439: : keys(%libserv) );
7440: for my $server (@server_list) {
1.1172.2.33 raeburn 7441: my $domains = '';
7442: if (ref($domains_hash) eq 'HASH') {
7443: $domains = $domains_hash->{$server};
7444: }
1.118 harris41 7445: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7446: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7447: $rhash{$server}=$reply;
7448: }
7449: else {
7450: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7451: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7452: $server);
7453: $rhash{$server}=$reply;
7454: }
1.112 harris41 7455: }
1.118 harris41 7456: return \%rhash;
1.240 www 7457: }
7458:
7459: # ----------------------------------------- Send log queries and wait for reply
7460:
7461: sub log_query {
7462: my ($uname,$udom,$query,%filters)=@_;
7463: my $uhome=&homeserver($uname,$udom);
7464: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7465: my $uhost=&hostname($uhome);
1.800 albertel 7466: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7467: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7468: $uhome);
1.479 albertel 7469: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7470: return get_query_reply($queryid);
7471: }
7472:
1.818 raeburn 7473: # -------------------------- Update MySQL table for portfolio file
7474:
7475: sub update_portfolio_table {
1.821 raeburn 7476: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7477: if ($group ne '') {
7478: $file_name =~s /^\Q$group\E//;
7479: }
1.818 raeburn 7480: my $homeserver = &homeserver($uname,$udom);
7481: my $queryid=
1.821 raeburn 7482: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7483: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7484: my $reply = &get_query_reply($queryid);
7485: return $reply;
7486: }
7487:
1.899 raeburn 7488: # -------------------------- Update MySQL allusers table
7489:
7490: sub update_allusers_table {
7491: my ($uname,$udom,$names) = @_;
7492: my $homeserver = &homeserver($uname,$udom);
7493: my $queryid=
7494: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7495: 'lastname='.&escape($names->{'lastname'}).'%%'.
7496: 'firstname='.&escape($names->{'firstname'}).'%%'.
7497: 'middlename='.&escape($names->{'middlename'}).'%%'.
7498: 'generation='.&escape($names->{'generation'}).'%%'.
7499: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7500: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7501: return;
1.899 raeburn 7502: }
7503:
1.508 raeburn 7504: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7505:
7506: sub fetch_enrollment_query {
1.511 raeburn 7507: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7508: my $homeserver;
1.547 raeburn 7509: my $maxtries = 1;
1.508 raeburn 7510: if ($context eq 'automated') {
7511: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7512: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7513: } else {
7514: $homeserver = &homeserver($cnum,$dom);
7515: }
1.838 albertel 7516: my $host=&hostname($homeserver);
1.506 raeburn 7517: my $cmd = '';
1.1000 raeburn 7518: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7519: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7520: }
7521: $cmd =~ s/%%$//;
7522: $cmd = &escape($cmd);
7523: my $query = 'fetchenrollment';
1.620 albertel 7524: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7525: unless ($queryid=~/^\Q$host\E\_/) {
7526: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7527: return 'error: '.$queryid;
7528: }
1.506 raeburn 7529: my $reply = &get_query_reply($queryid);
1.547 raeburn 7530: my $tries = 1;
7531: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7532: $reply = &get_query_reply($queryid);
7533: $tries ++;
7534: }
1.526 raeburn 7535: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7536: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7537: } else {
1.901 albertel 7538: my @responses = split(/:/,$reply);
1.515 raeburn 7539: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7540: foreach my $line (@responses) {
7541: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7542: $$replyref{$key} = $value;
7543: }
7544: } else {
1.1117 foxr 7545: my $pathname = LONCAPA::tempdir();
1.800 albertel 7546: foreach my $line (@responses) {
7547: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7548: $$replyref{$key} = $value;
7549: if ($value > 0) {
1.800 albertel 7550: foreach my $item (@{$$affiliatesref{$key}}) {
7551: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7552: my $destname = $pathname.'/'.$filename;
7553: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7554: if ($xml_classlist =~ /^error/) {
7555: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7556: } else {
1.506 raeburn 7557: if ( open(FILE,">$destname") ) {
7558: print FILE &unescape($xml_classlist);
7559: close(FILE);
1.526 raeburn 7560: } else {
7561: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7562: }
7563: }
7564: }
7565: }
7566: }
7567: }
7568: return 'ok';
7569: }
7570: return 'error';
7571: }
7572:
1.242 www 7573: sub get_query_reply {
7574: my $queryid=shift;
1.1117 foxr 7575: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7576: my $reply='';
7577: for (1..100) {
7578: sleep 2;
7579: if (-e $replyfile.'.end') {
1.448 albertel 7580: if (open(my $fh,$replyfile)) {
1.904 albertel 7581: $reply = join('',<$fh>);
7582: close($fh);
1.240 www 7583: } else { return 'error: reply_file_error'; }
1.242 www 7584: return &unescape($reply);
7585: }
1.240 www 7586: }
1.242 www 7587: return 'timeout:'.$queryid;
1.240 www 7588: }
7589:
7590: sub courselog_query {
1.241 www 7591: #
7592: # possible filters:
7593: # url: url or symb
7594: # username
7595: # domain
7596: # action: view, submit, grade
7597: # start: timestamp
7598: # end: timestamp
7599: #
1.240 www 7600: my (%filters)=@_;
1.620 albertel 7601: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7602: if ($filters{'url'}) {
7603: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7604: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7605: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7606: }
1.620 albertel 7607: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7608: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7609: return &log_query($cname,$cdom,'courselog',%filters);
7610: }
7611:
7612: sub userlog_query {
1.858 raeburn 7613: #
7614: # possible filters:
7615: # action: log check role
7616: # start: timestamp
7617: # end: timestamp
7618: #
1.240 www 7619: my ($uname,$udom,%filters)=@_;
7620: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7621: }
7622:
1.506 raeburn 7623: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7624:
7625: sub auto_run {
1.508 raeburn 7626: my ($cnum,$cdom) = @_;
1.876 raeburn 7627: my $response = 0;
7628: my $settings;
7629: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7630: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7631: $settings = $domconfig{'autoenroll'};
7632: if ($settings->{'run'} eq '1') {
7633: $response = 1;
7634: }
7635: } else {
1.934 raeburn 7636: my $homeserver;
7637: if (&is_course($cdom,$cnum)) {
7638: $homeserver = &homeserver($cnum,$cdom);
7639: } else {
7640: $homeserver = &domain($cdom,'primary');
7641: }
7642: if ($homeserver ne 'no_host') {
7643: $response = &reply('autorun:'.$cdom,$homeserver);
7644: }
1.876 raeburn 7645: }
1.506 raeburn 7646: return $response;
7647: }
1.776 albertel 7648:
1.506 raeburn 7649: sub auto_get_sections {
1.508 raeburn 7650: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7651: my $homeserver;
7652: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7653: $homeserver = &homeserver($cnum,$cdom);
7654: }
7655: if (!defined($homeserver)) {
7656: if ($cdom =~ /^$match_domain$/) {
7657: $homeserver = &domain($cdom,'primary');
7658: }
7659: }
7660: my @secs;
7661: if (defined($homeserver)) {
7662: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7663: unless ($response eq 'refused') {
7664: @secs = split(/:/,$response);
7665: }
1.506 raeburn 7666: }
7667: return @secs;
7668: }
1.776 albertel 7669:
1.506 raeburn 7670: sub auto_new_course {
1.1099 raeburn 7671: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7672: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7673: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7674: return $response;
7675: }
1.776 albertel 7676:
1.506 raeburn 7677: sub auto_validate_courseID {
1.508 raeburn 7678: my ($cnum,$cdom,$inst_course_id) = @_;
7679: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7680: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7681: return $response;
7682: }
1.776 albertel 7683:
1.1007 raeburn 7684: sub auto_validate_instcode {
1.1020 raeburn 7685: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7686: my ($homeserver,$response);
7687: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7688: $homeserver = &homeserver($cnum,$cdom);
7689: }
7690: if (!defined($homeserver)) {
7691: if ($cdom =~ /^$match_domain$/) {
7692: $homeserver = &domain($cdom,'primary');
7693: }
7694: }
1.1065 raeburn 7695: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7696: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7697: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7698: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7699: }
7700:
1.506 raeburn 7701: sub auto_create_password {
1.873 raeburn 7702: my ($cnum,$cdom,$authparam,$udom) = @_;
7703: my ($homeserver,$response);
1.506 raeburn 7704: my $create_passwd = 0;
7705: my $authchk = '';
1.873 raeburn 7706: if ($udom =~ /^$match_domain$/) {
7707: $homeserver = &domain($udom,'primary');
7708: }
7709: if ($homeserver eq '') {
7710: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7711: $homeserver = &homeserver($cnum,$cdom);
7712: }
7713: }
7714: if ($homeserver eq '') {
7715: $authchk = 'nodomain';
1.506 raeburn 7716: } else {
1.873 raeburn 7717: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7718: if ($response eq 'refused') {
7719: $authchk = 'refused';
7720: } else {
1.901 albertel 7721: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7722: }
1.506 raeburn 7723: }
7724: return ($authparam,$create_passwd,$authchk);
7725: }
7726:
1.706 raeburn 7727: sub auto_photo_permission {
7728: my ($cnum,$cdom,$students) = @_;
7729: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7730: my ($outcome,$perm_reqd,$conditions) =
7731: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7732: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7733: return (undef,undef);
7734: }
1.706 raeburn 7735: return ($outcome,$perm_reqd,$conditions);
7736: }
7737:
7738: sub auto_checkphotos {
7739: my ($uname,$udom,$pid) = @_;
7740: my $homeserver = &homeserver($uname,$udom);
7741: my ($result,$resulttype);
7742: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7743: &escape($uname).':'.&escape($pid),
7744: $homeserver));
1.709 albertel 7745: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7746: return (undef,undef);
7747: }
1.706 raeburn 7748: if ($outcome) {
7749: ($result,$resulttype) = split(/:/,$outcome);
7750: }
7751: return ($result,$resulttype);
7752: }
7753:
7754: sub auto_photochoice {
7755: my ($cnum,$cdom) = @_;
7756: my $homeserver = &homeserver($cnum,$cdom);
7757: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7758: &escape($cdom),
7759: $homeserver)));
1.709 albertel 7760: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7761: return (undef,undef);
7762: }
1.706 raeburn 7763: return ($update,$comment);
7764: }
7765:
7766: sub auto_photoupdate {
7767: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7768: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7769: my $host=&hostname($homeserver);
1.706 raeburn 7770: my $cmd = '';
7771: my $maxtries = 1;
1.800 albertel 7772: foreach my $affiliate (keys(%{$affiliatesref})) {
7773: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7774: }
7775: $cmd =~ s/%%$//;
7776: $cmd = &escape($cmd);
7777: my $query = 'institutionalphotos';
7778: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7779: unless ($queryid=~/^\Q$host\E\_/) {
7780: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7781: return 'error: '.$queryid;
7782: }
7783: my $reply = &get_query_reply($queryid);
7784: my $tries = 1;
7785: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7786: $reply = &get_query_reply($queryid);
7787: $tries ++;
7788: }
7789: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7790: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7791: } else {
7792: my @responses = split(/:/,$reply);
7793: my $outcome = shift(@responses);
7794: foreach my $item (@responses) {
7795: my ($key,$value) = split(/=/,$item);
7796: $$photo{$key} = $value;
7797: }
7798: return $outcome;
7799: }
7800: return 'error';
7801: }
7802:
1.521 raeburn 7803: sub auto_instcode_format {
1.793 albertel 7804: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7805: $cat_order) = @_;
1.521 raeburn 7806: my $courses = '';
1.772 raeburn 7807: my @homeservers;
1.521 raeburn 7808: if ($caller eq 'global') {
1.841 albertel 7809: my %servers = &get_servers($codedom,'library');
7810: foreach my $tryserver (keys(%servers)) {
7811: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7812: push(@homeservers,$tryserver);
7813: }
1.584 raeburn 7814: }
1.1022 raeburn 7815: } elsif ($caller eq 'requests') {
7816: if ($codedom =~ /^$match_domain$/) {
7817: my $chome = &domain($codedom,'primary');
7818: unless ($chome eq 'no_host') {
7819: push(@homeservers,$chome);
7820: }
7821: }
1.521 raeburn 7822: } else {
1.772 raeburn 7823: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7824: }
1.793 albertel 7825: foreach my $code (keys(%{$instcodes})) {
7826: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7827: }
7828: chop($courses);
1.772 raeburn 7829: my $ok_response = 0;
7830: my $response;
7831: while (@homeservers > 0 && $ok_response == 0) {
7832: my $server = shift(@homeservers);
7833: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7834: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7835: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7836: split(/:/,$response);
1.772 raeburn 7837: %{$codes} = (%{$codes},&str2hash($codes_str));
7838: push(@{$codetitles},&str2array($codetitles_str));
7839: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7840: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7841: $ok_response = 1;
7842: }
7843: }
7844: if ($ok_response) {
1.521 raeburn 7845: return 'ok';
1.772 raeburn 7846: } else {
7847: return $response;
1.521 raeburn 7848: }
7849: }
7850:
1.792 raeburn 7851: sub auto_instcode_defaults {
7852: my ($domain,$returnhash,$code_order) = @_;
7853: my @homeservers;
1.841 albertel 7854:
7855: my %servers = &get_servers($domain,'library');
7856: foreach my $tryserver (keys(%servers)) {
7857: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7858: push(@homeservers,$tryserver);
7859: }
1.792 raeburn 7860: }
1.841 albertel 7861:
1.792 raeburn 7862: my $response;
1.841 albertel 7863: foreach my $server (@homeservers) {
1.792 raeburn 7864: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7865: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7866:
7867: foreach my $pair (split(/\&/,$response)) {
7868: my ($name,$value)=split(/\=/,$pair);
7869: if ($name eq 'code_order') {
7870: @{$code_order} = split(/\&/,&unescape($value));
7871: } else {
7872: $returnhash->{&unescape($name)}=&unescape($value);
7873: }
7874: }
7875: return 'ok';
1.792 raeburn 7876: }
1.841 albertel 7877:
7878: return $response;
1.1003 raeburn 7879: }
7880:
7881: sub auto_possible_instcodes {
1.1007 raeburn 7882: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7883: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7884: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7885: return;
7886: }
1.1003 raeburn 7887: my (@homeservers,$uhome);
7888: if (defined(&domain($domain,'primary'))) {
7889: $uhome=&domain($domain,'primary');
7890: push(@homeservers,&domain($domain,'primary'));
7891: } else {
7892: my %servers = &get_servers($domain,'library');
7893: foreach my $tryserver (keys(%servers)) {
7894: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7895: push(@homeservers,$tryserver);
7896: }
7897: }
7898: }
7899: my $response;
7900: foreach my $server (@homeservers) {
7901: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7902: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7903: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7904: split(':',$response);
7905: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7906: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7907: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7908: my ($name,$value)=split('=',$item);
7909: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7910: }
7911: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7912: my ($name,$value)=split('=',$item);
7913: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7914: }
7915: return 'ok';
7916: }
7917: return $response;
7918: }
1.792 raeburn 7919:
1.1010 raeburn 7920: sub auto_courserequest_checks {
7921: my ($dom) = @_;
1.1020 raeburn 7922: my ($homeserver,%validations);
7923: if ($dom =~ /^$match_domain$/) {
7924: $homeserver = &domain($dom,'primary');
7925: }
7926: unless ($homeserver eq 'no_host') {
7927: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7928: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7929: my @items = split(/&/,$response);
7930: foreach my $item (@items) {
7931: my ($key,$value) = split('=',$item);
7932: $validations{&unescape($key)} = &thaw_unescape($value);
7933: }
7934: }
7935: }
1.1010 raeburn 7936: return %validations;
7937: }
7938:
1.1020 raeburn 7939: sub auto_courserequest_validation {
1.1172.2.43 raeburn 7940: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7941: my ($homeserver,$response);
7942: if ($dom =~ /^$match_domain$/) {
7943: $homeserver = &domain($dom,'primary');
7944: }
1.1172.2.43 raeburn 7945: unless ($homeserver eq 'no_host') {
7946: my $customdata;
7947: if (ref($custominfo) eq 'HASH') {
7948: $customdata = &freeze_escape($custominfo);
7949: }
1.1020 raeburn 7950: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7951: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 7952: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7953: $customdata,$homeserver));
1.1020 raeburn 7954: }
7955: return $response;
7956: }
7957:
1.777 albertel 7958: sub auto_validate_class_sec {
1.918 raeburn 7959: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7960: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7961: my $ownerlist;
7962: if (ref($owners) eq 'ARRAY') {
7963: $ownerlist = join(',',@{$owners});
7964: } else {
7965: $ownerlist = $owners;
7966: }
1.773 raeburn 7967: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7968: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7969: return $response;
7970: }
7971:
1.1172.2.38 raeburn 7972: sub auto_crsreq_update {
7973: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 7974: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 7975: my ($homeserver,%crsreqresponse);
7976: if ($cdom =~ /^$match_domain$/) {
7977: $homeserver = &domain($cdom,'primary');
7978: }
7979: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7980: my $info;
7981: if (ref($inbound) eq 'HASH') {
7982: $info = &freeze_escape($inbound);
7983: }
7984: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7985: ':'.&escape($action).':'.&escape($ownername).':'.
7986: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 7987: &escape($title).':'.&escape($code).':'.
7988: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 7989: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7990: my @items = split(/&/,$response);
7991: foreach my $item (@items) {
7992: my ($key,$value) = split('=',$item);
7993: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7994: }
7995: }
7996: }
7997: return \%crsreqresponse;
7998: }
7999:
1.679 raeburn 8000: # ------------------------------------------------------- Course Group routines
8001:
8002: sub get_coursegroups {
1.809 raeburn 8003: my ($cdom,$cnum,$group,$namespace) = @_;
8004: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8005: }
8006:
1.679 raeburn 8007: sub modify_coursegroup {
8008: my ($cdom,$cnum,$groupsettings) = @_;
8009: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8010: }
8011:
1.809 raeburn 8012: sub toggle_coursegroup_status {
8013: my ($cdom,$cnum,$group,$action) = @_;
8014: my ($from_namespace,$to_namespace);
8015: if ($action eq 'delete') {
8016: $from_namespace = 'coursegroups';
8017: $to_namespace = 'deleted_groups';
8018: } else {
8019: $from_namespace = 'deleted_groups';
8020: $to_namespace = 'coursegroups';
8021: }
8022: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8023: if (my $tmp = &error(%curr_group)) {
8024: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8025: return ('read error',$tmp);
8026: } else {
8027: my %savedsettings = %curr_group;
1.809 raeburn 8028: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8029: my $deloutcome;
8030: if ($result eq 'ok') {
1.809 raeburn 8031: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8032: } else {
8033: return ('write error',$result);
8034: }
8035: if ($deloutcome eq 'ok') {
8036: return 'ok';
8037: } else {
8038: return ('delete error',$deloutcome);
8039: }
8040: }
8041: }
8042:
1.679 raeburn 8043: sub modify_group_roles {
1.957 raeburn 8044: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8045: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8046: my $role = 'gr/'.&escape($userprivs);
8047: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8048: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8049: if ($result eq 'ok') {
8050: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8051: }
1.679 raeburn 8052: return $result;
8053: }
8054:
8055: sub modify_coursegroup_membership {
8056: my ($cdom,$cnum,$membership) = @_;
8057: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8058: return $result;
8059: }
8060:
1.682 raeburn 8061: sub get_active_groups {
8062: my ($udom,$uname,$cdom,$cnum) = @_;
8063: my $now = time;
8064: my %groups = ();
8065: foreach my $key (keys(%env)) {
1.811 albertel 8066: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8067: my ($start,$end) = split(/\./,$env{$key});
8068: if (($end!=0) && ($end<$now)) { next; }
8069: if (($start!=0) && ($start>$now)) { next; }
8070: if ($1 eq $cdom && $2 eq $cnum) {
8071: $groups{$3} = $env{$key} ;
8072: }
8073: }
8074: }
8075: return %groups;
8076: }
8077:
1.683 raeburn 8078: sub get_group_membership {
8079: my ($cdom,$cnum,$group) = @_;
8080: return(&dump('groupmembership',$cdom,$cnum,$group));
8081: }
8082:
8083: sub get_users_groups {
8084: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8085: my @usersgroups;
1.683 raeburn 8086: my $cachetime=1800;
8087:
8088: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8089: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8090: if (defined($cached)) {
1.734 albertel 8091: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8092: } else {
8093: $grouplist = '';
1.816 raeburn 8094: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8095: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8096: my $access_end = $env{'course.'.$courseid.
8097: '.default_enrollment_end_date'};
8098: my $now = time;
8099: foreach my $key (keys(%roleshash)) {
8100: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8101: my $group = $1;
8102: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8103: my $start = $2;
8104: my $end = $1;
8105: if ($start == -1) { next; } # deleted from group
8106: if (($start!=0) && ($start>$now)) { next; }
8107: if (($end!=0) && ($end<$now)) {
8108: if ($access_end && $access_end < $now) {
8109: if ($access_end - $end < 86400) {
8110: push(@usersgroups,$group);
1.733 raeburn 8111: }
8112: }
1.817 raeburn 8113: next;
1.733 raeburn 8114: }
1.817 raeburn 8115: push(@usersgroups,$group);
1.683 raeburn 8116: }
8117: }
8118: }
1.817 raeburn 8119: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8120: $grouplist = join(':',@usersgroups);
8121: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8122: }
1.733 raeburn 8123: return @usersgroups;
1.683 raeburn 8124: }
8125:
8126: sub devalidate_getgroups_cache {
8127: my ($udom,$uname,$cdom,$cnum)=@_;
8128: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8129:
1.683 raeburn 8130: my $hashid="$udom:$uname:$courseid";
8131: &devalidate_cache_new('getgroups',$hashid);
8132: }
8133:
1.12 www 8134: # ------------------------------------------------------------------ Plain Text
8135:
8136: sub plaintext {
1.988 raeburn 8137: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8138: if ($short =~ m{^cr/}) {
1.758 albertel 8139: return (split('/',$short))[-1];
8140: }
1.742 raeburn 8141: if (!defined($cid)) {
8142: $cid = $env{'request.course.id'};
8143: }
8144: my %rolenames = (
1.1008 raeburn 8145: Course => 'std',
8146: Community => 'alt1',
1.742 raeburn 8147: );
1.1037 raeburn 8148: if ($cid ne '') {
8149: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8150: unless ($forcedefault) {
8151: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8152: &Apache::lonlocal::mt_escape(\$roletext);
8153: return &Apache::lonlocal::mt($roletext);
8154: }
8155: }
8156: }
8157: if ((defined($type)) && (defined($rolenames{$type})) &&
8158: (defined($rolenames{$type})) &&
8159: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8160: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8161: } elsif ($cid ne '') {
8162: my $crstype = $env{'course.'.$cid.'.type'};
8163: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8164: (defined($prp{$short}{$rolenames{$crstype}}))) {
8165: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8166: }
1.742 raeburn 8167: }
1.1037 raeburn 8168: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8169: }
8170:
8171: # ----------------------------------------------------------------- Assign Role
8172:
8173: sub assignrole {
1.957 raeburn 8174: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8175: $context)=@_;
1.21 www 8176: my $mrole;
8177: if ($role =~ /^cr\//) {
1.393 www 8178: my $cwosec=$url;
1.811 albertel 8179: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8180: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8181: my $refused = 1;
8182: if ($context eq 'requestcourses') {
8183: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8184: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8185: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8186: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8187: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8188: if ($crsenv{'internal.courseowner'} eq
8189: $env{'user.name'}.':'.$env{'user.domain'}) {
8190: $refused = '';
8191: }
8192: }
8193: }
8194: }
8195: }
8196: if ($refused) {
8197: &logthis('Refused custom assignrole: '.
8198: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8199: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8200: return 'refused';
8201: }
1.104 www 8202: }
1.21 www 8203: $mrole='cr';
1.678 raeburn 8204: } elsif ($role =~ /^gr\//) {
8205: my $cwogrp=$url;
1.811 albertel 8206: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8207: unless (&allowed('mdg',$cwogrp)) {
8208: &logthis('Refused group assignrole: '.
8209: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8210: $env{'user.name'}.' at '.$env{'user.domain'});
8211: return 'refused';
8212: }
8213: $mrole='gr';
1.21 www 8214: } else {
1.82 www 8215: my $cwosec=$url;
1.811 albertel 8216: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8217: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8218: my $refused;
8219: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8220: if (!(&allowed('c'.$role,$url))) {
8221: $refused = 1;
8222: }
8223: } else {
8224: $refused = 1;
8225: }
1.947 raeburn 8226: if ($refused) {
1.1045 raeburn 8227: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8228: if (!$selfenroll && $context eq 'course') {
8229: my %crsenv;
8230: if ($role eq 'cc' || $role eq 'co') {
8231: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8232: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8233: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8234: if ($crsenv{'internal.courseowner'} eq
8235: $env{'user.name'}.':'.$env{'user.domain'}) {
8236: $refused = '';
8237: }
8238: }
8239: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8240: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8241: if ($crsenv{'internal.courseowner'} eq
8242: $env{'user.name'}.':'.$env{'user.domain'}) {
8243: $refused = '';
8244: }
8245: }
8246: }
8247: }
8248: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8249: $refused = '';
1.1017 raeburn 8250: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8251: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8252: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8253: my $wrongcc;
8254: if ($cnum =~ /^$match_community$/) {
8255: $wrongcc = 1 if ($role eq 'cc');
8256: } else {
8257: $wrongcc = 1 if ($role eq 'co');
8258: }
8259: unless ($wrongcc) {
8260: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8261: if ($crsenv{'internal.courseowner'} eq
8262: $env{'user.name'}.':'.$env{'user.domain'}) {
8263: $refused = '';
8264: }
1.1017 raeburn 8265: }
8266: }
1.1172.2.9 raeburn 8267: } elsif ($context eq 'requestauthor') {
8268: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8269: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8270: if ($env{'environment.requestauthor'} eq 'automatic') {
8271: $refused = '';
8272: } else {
8273: my %domdefaults = &get_domain_defaults($udom);
8274: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8275: my $checkbystatus;
8276: if ($env{'user.adv'}) {
8277: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8278: if ($disposition eq 'automatic') {
8279: $refused = '';
8280: } elsif ($disposition eq '') {
8281: $checkbystatus = 1;
8282: }
8283: } else {
8284: $checkbystatus = 1;
8285: }
8286: if ($checkbystatus) {
8287: if ($env{'environment.inststatus'}) {
8288: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8289: foreach my $type (@inststatuses) {
8290: if (($type ne '') &&
8291: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8292: $refused = '';
8293: }
8294: }
8295: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8296: $refused = '';
8297: }
8298: }
8299: }
8300: }
8301: }
1.1017 raeburn 8302: }
8303: if ($refused) {
1.947 raeburn 8304: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8305: ' '.$role.' '.$end.' '.$start.' by '.
8306: $env{'user.name'}.' at '.$env{'user.domain'});
8307: return 'refused';
8308: }
1.932 raeburn 8309: }
1.1131 raeburn 8310: } elsif ($role eq 'au') {
8311: if ($url ne '/'.$udom.'/') {
8312: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8313: ' to assign author role for '.$uname.':'.$udom.
8314: ' in domain: '.$url.' refused (wrong domain).');
8315: return 'refused';
8316: }
1.104 www 8317: }
1.21 www 8318: $mrole=$role;
8319: }
1.620 albertel 8320: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8321: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8322: if ($end) { $command.='_'.$end; }
1.21 www 8323: if ($start) {
8324: if ($end) {
1.81 www 8325: $command.='_'.$start;
1.21 www 8326: } else {
1.81 www 8327: $command.='_0_'.$start;
1.21 www 8328: }
8329: }
1.739 raeburn 8330: my $origstart = $start;
8331: my $origend = $end;
1.957 raeburn 8332: my $delflag;
1.357 www 8333: # actually delete
8334: if ($deleteflag) {
1.373 www 8335: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8336: # modify command to delete the role
1.620 albertel 8337: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8338: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8339: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8340: # set start and finish to negative values for userrolelog
8341: $start=-1;
8342: $end=-1;
1.957 raeburn 8343: $delflag = 1;
1.357 www 8344: }
8345: }
8346: # send command
1.349 www 8347: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8348: # log new user role if status is ok
1.349 www 8349: if ($answer eq 'ok') {
1.663 raeburn 8350: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8351: if (($role eq 'cc') || ($role eq 'in') ||
8352: ($role eq 'ep') || ($role eq 'ad') ||
8353: ($role eq 'ta') || ($role eq 'st') ||
8354: ($role=~/^cr/) || ($role eq 'gr') ||
8355: ($role eq 'co')) {
1.1172.2.13 raeburn 8356: # for course roles, perform group memberships changes triggered by role change.
8357: unless ($role =~ /^gr/) {
8358: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8359: $origstart,$selfenroll,$context);
8360: }
1.1172.2.9 raeburn 8361: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8362: $selfenroll,$context);
8363: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8364: ($role eq 'au') || ($role eq 'dc')) {
8365: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8366: $context);
8367: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8368: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8369: $context);
8370: }
1.1053 raeburn 8371: if ($role eq 'cc') {
8372: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8373: }
1.349 www 8374: }
8375: return $answer;
1.169 harris41 8376: }
8377:
1.1053 raeburn 8378: sub autoupdate_coowners {
8379: my ($url,$end,$start,$uname,$udom) = @_;
8380: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8381: if (($cdom ne '') && ($cnum ne '')) {
8382: my $now = time;
8383: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8384: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8385: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8386: my $instcode = $coursehash{'internal.coursecode'};
8387: if ($instcode ne '') {
1.1056 raeburn 8388: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8389: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8390: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8391: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8392: if ($result eq 'valid') {
8393: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8394: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8395: push(@newcoowners,$coowner);
8396: }
8397: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8398: push(@newcoowners,$uname.':'.$udom);
8399: }
8400: @newcoowners = sort(@newcoowners);
8401: } else {
8402: push(@newcoowners,$uname.':'.$udom);
8403: }
8404: } else {
8405: if ($coursehash{'internal.co-owners'}) {
8406: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8407: unless ($coowner eq $uname.':'.$udom) {
8408: push(@newcoowners,$coowner);
8409: }
8410: }
8411: unless (@newcoowners > 0) {
8412: $delcoowners = 1;
8413: $coowners = '';
8414: }
8415: }
8416: }
8417: if (@newcoowners || $delcoowners) {
8418: &store_coowners($cdom,$cnum,$coursehash{'home'},
8419: $delcoowners,@newcoowners);
8420: }
8421: }
8422: }
8423: }
8424: }
8425: }
8426: }
8427:
8428: sub store_coowners {
8429: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8430: my $cid = $cdom.'_'.$cnum;
8431: my ($coowners,$delresult,$putresult);
8432: if (@newcoowners) {
8433: $coowners = join(',',@newcoowners);
8434: my %coownershash = (
8435: 'internal.co-owners' => $coowners,
8436: );
8437: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8438: if ($putresult eq 'ok') {
8439: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8440: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8441: }
8442: }
8443: }
8444: if ($delcoowners) {
8445: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8446: if ($delresult eq 'ok') {
8447: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8448: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8449: }
8450: }
8451: }
8452: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8453: my %crsinfo =
8454: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8455: if (ref($crsinfo{$cid}) eq 'HASH') {
8456: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8457: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8458: }
8459: }
8460: }
8461:
1.169 harris41 8462: # -------------------------------------------------- Modify user authentication
1.197 www 8463: # Overrides without validation
8464:
1.169 harris41 8465: sub modifyuserauth {
8466: my ($udom,$uname,$umode,$upass)=@_;
8467: my $uhome=&homeserver($uname,$udom);
1.197 www 8468: unless (&allowed('mau',$udom)) { return 'refused'; }
8469: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8470: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8471: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8472: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8473: &escape($upass),$uhome);
1.620 albertel 8474: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8475: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8476: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8477: &log($udom,,$uname,$uhome,
1.620 albertel 8478: 'Authentication changed by '.$env{'user.domain'}.', '.
8479: $env{'user.name'}.', '.$umode.
1.197 www 8480: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8481: unless ($reply eq 'ok') {
1.197 www 8482: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8483: return 'error: '.$reply;
8484: }
1.170 harris41 8485: return 'ok';
1.80 www 8486: }
8487:
1.81 www 8488: # --------------------------------------------------------------- Modify a user
1.80 www 8489:
1.81 www 8490: sub modifyuser {
1.206 matthew 8491: my ($udom, $uname, $uid,
8492: $umode, $upass, $first,
8493: $middle, $last, $gene,
1.1058 raeburn 8494: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8495: $udom= &LONCAPA::clean_domain($udom);
8496: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8497: my $showcandelete = 'none';
8498: if (ref($candelete) eq 'ARRAY') {
8499: if (@{$candelete} > 0) {
8500: $showcandelete = join(', ',@{$candelete});
8501: }
8502: }
1.81 www 8503: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8504: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8505: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8506: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8507: ' desiredhome not specified').
1.620 albertel 8508: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8509: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8510: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8511: my $newuser;
8512: if ($uhome eq 'no_host') {
8513: $newuser = 1;
8514: }
1.80 www 8515: # ----------------------------------------------------------------- Create User
1.406 albertel 8516: if (($uhome eq 'no_host') &&
8517: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8518: my $unhome='';
1.844 albertel 8519: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8520: $unhome = $desiredhome;
1.620 albertel 8521: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8522: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8523: } else { # load balancing routine for determining $unhome
1.81 www 8524: my $loadm=10000000;
1.841 albertel 8525: my %servers = &get_servers($udom,'library');
8526: foreach my $tryserver (keys(%servers)) {
8527: my $answer=reply('load',$tryserver);
8528: if (($answer=~/\d+/) && ($answer<$loadm)) {
8529: $loadm=$answer;
8530: $unhome=$tryserver;
8531: }
1.80 www 8532: }
8533: }
8534: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8535: return 'error: unable to find a home server for '.$uname.
8536: ' in domain '.$udom;
1.80 www 8537: }
8538: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8539: &escape($upass),$unhome);
8540: unless ($reply eq 'ok') {
8541: return 'error: '.$reply;
8542: }
1.230 stredwic 8543: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8544: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8545: return 'error: unable verify users home machine.';
1.80 www 8546: }
1.209 matthew 8547: } # End of creation of new user
1.80 www 8548: # ---------------------------------------------------------------------- Add ID
8549: if ($uid) {
8550: $uid=~tr/A-Z/a-z/;
8551: my %uidhash=&idrget($udom,$uname);
1.196 www 8552: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8553: && (!$forceid)) {
1.80 www 8554: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8555: return 'error: user id "'.$uid.'" does not match '.
8556: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8557: }
8558: } else {
8559: &idput($udom,($uname => $uid));
8560: }
8561: }
8562: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8563: my @tmp=&get('environment',
1.899 raeburn 8564: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8565: 'permanentemail','inststatus'],
1.134 albertel 8566: $udom,$uname);
1.1075 raeburn 8567: my (%names,%oldnames);
1.313 matthew 8568: if ($tmp[0] =~ m/^error:.*/) {
8569: %names=();
8570: } else {
8571: %names = @tmp;
1.1075 raeburn 8572: %oldnames = %names;
1.313 matthew 8573: }
1.388 www 8574: #
1.1058 raeburn 8575: # If name, email and/or uid are blank (e.g., because an uploaded file
8576: # of users did not contain them), do not overwrite existing values
8577: # unless field is in $candelete array ref.
8578: #
8579:
8580: my @fields = ('firstname','middlename','lastname','generation',
8581: 'permanentemail','id');
8582: my %newvalues;
8583: if (ref($candelete) eq 'ARRAY') {
8584: foreach my $field (@fields) {
8585: if (grep(/^\Q$field\E$/,@{$candelete})) {
8586: if ($field eq 'firstname') {
8587: $names{$field} = $first;
8588: } elsif ($field eq 'middlename') {
8589: $names{$field} = $middle;
8590: } elsif ($field eq 'lastname') {
8591: $names{$field} = $last;
8592: } elsif ($field eq 'generation') {
8593: $names{$field} = $gene;
8594: } elsif ($field eq 'permanentemail') {
8595: $names{$field} = $email;
8596: } elsif ($field eq 'id') {
8597: $names{$field} = $uid;
8598: }
8599: }
8600: }
8601: }
1.388 www 8602: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8603: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8604: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8605: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8606: if ($email) {
8607: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8608: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8609: }
1.899 raeburn 8610: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8611: if (defined($inststatus)) {
8612: $names{'inststatus'} = '';
8613: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8614: if (ref($usertypes) eq 'HASH') {
8615: my @okstatuses;
8616: foreach my $item (split(/:/,$inststatus)) {
8617: if (defined($usertypes->{$item})) {
8618: push(@okstatuses,$item);
8619: }
8620: }
8621: if (@okstatuses) {
8622: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8623: }
8624: }
8625: }
1.1075 raeburn 8626: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8627: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8628: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8629: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8630: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8631: } else {
8632: $logmsg .= ' during self creation';
8633: }
1.1075 raeburn 8634: my $changed;
8635: if ($newuser) {
8636: $changed = 1;
8637: } else {
8638: foreach my $field (@fields) {
8639: if ($names{$field} ne $oldnames{$field}) {
8640: $changed = 1;
8641: last;
8642: }
8643: }
8644: }
8645: unless ($changed) {
8646: $logmsg = 'No changes in user information needed for: '.$logmsg;
8647: &logthis($logmsg);
8648: return 'ok';
8649: }
8650: my $reply = &put('environment', \%names, $udom,$uname);
8651: if ($reply ne 'ok') {
8652: return 'error: '.$reply;
8653: }
1.1087 raeburn 8654: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8655: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8656: }
1.1075 raeburn 8657: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8658: &devalidate_cache_new('namescache',$uname.':'.$udom);
8659: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8660: &logthis($logmsg);
1.134 albertel 8661: return 'ok';
1.80 www 8662: }
8663:
1.81 www 8664: # -------------------------------------------------------------- Modify student
1.80 www 8665:
1.81 www 8666: sub modifystudent {
8667: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8668: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8669: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8670: if (!$cid) {
1.620 albertel 8671: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8672: return 'not_in_class';
8673: }
1.80 www 8674: }
8675: # --------------------------------------------------------------- Make the user
1.81 www 8676: my $reply=&modifyuser
1.209 matthew 8677: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8678: $desiredhome,$email,$inststatus);
1.80 www 8679: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8680: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8681: # student's environment
1.297 matthew 8682: $uid = undef if (!$forceid);
1.455 albertel 8683: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8684: $gene,$usec,$end,$start,$type,$locktype,
8685: $cid,$selfenroll,$context,$credits);
1.297 matthew 8686: return $reply;
8687: }
8688:
8689: sub modify_student_enrollment {
1.1172.2.23 raeburn 8690: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8691: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8692: my ($cdom,$cnum,$chome);
8693: if (!$cid) {
1.620 albertel 8694: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8695: return 'not_in_class';
8696: }
1.620 albertel 8697: $cdom=$env{'course.'.$cid.'.domain'};
8698: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8699: } else {
8700: ($cdom,$cnum)=split(/_/,$cid);
8701: }
1.620 albertel 8702: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8703: if (!$chome) {
1.457 raeburn 8704: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8705: }
1.455 albertel 8706: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8707: # Make sure the user exists
1.81 www 8708: my $uhome=&homeserver($uname,$udom);
8709: if (($uhome eq '') || ($uhome eq 'no_host')) {
8710: return 'error: no such user';
8711: }
1.297 matthew 8712: # Get student data if we were not given enough information
8713: if (!defined($first) || $first eq '' ||
8714: !defined($last) || $last eq '' ||
8715: !defined($uid) || $uid eq '' ||
8716: !defined($middle) || $middle eq '' ||
8717: !defined($gene) || $gene eq '') {
1.294 matthew 8718: # They did not supply us with enough data to enroll the student, so
8719: # we need to pick up more information.
1.297 matthew 8720: my %tmp = &get('environment',
1.294 matthew 8721: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8722: ,$udom,$uname);
8723:
1.800 albertel 8724: #foreach my $key (keys(%tmp)) {
8725: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8726: #}
1.294 matthew 8727: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8728: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8729: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8730: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8731: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8732: }
1.556 albertel 8733: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8734: my $user = "$uname:$udom";
8735: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8736: my $reply=cput('classlist',
1.1148 raeburn 8737: {$user =>
1.1172.2.19 raeburn 8738: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8739: $cdom,$cnum);
1.1148 raeburn 8740: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8741: &devalidate_getsection_cache($udom,$uname,$cid);
8742: } else {
1.81 www 8743: return 'error: '.$reply;
8744: }
1.297 matthew 8745: # Add student role to user
1.83 www 8746: my $uurl='/'.$cid;
1.81 www 8747: $uurl=~s/\_/\//g;
8748: if ($usec) {
8749: $uurl.='/'.$usec;
8750: }
1.1148 raeburn 8751: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8752: $selfenroll,$context);
8753: if ($result ne 'ok') {
8754: if ($old_entry{$user} ne '') {
8755: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8756: } else {
8757: $reply = &del('classlist',[$user],$cdom,$cnum);
8758: }
8759: }
8760: return $result;
1.21 www 8761: }
8762:
1.556 albertel 8763: sub format_name {
8764: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8765: my $name;
8766: if ($first ne 'lastname') {
8767: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8768: } else {
8769: if ($lastname=~/\S/) {
8770: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8771: $name=~s/\s+,/,/;
8772: } else {
8773: $name.= $firstname.' '.$middlename.' '.$generation;
8774: }
8775: }
8776: $name=~s/^\s+//;
8777: $name=~s/\s+$//;
8778: $name=~s/\s+/ /g;
8779: return $name;
8780: }
8781:
1.84 www 8782: # ------------------------------------------------- Write to course preferences
8783:
8784: sub writecoursepref {
8785: my ($courseid,%prefs)=@_;
8786: $courseid=~s/^\///;
8787: $courseid=~s/\_/\//g;
8788: my ($cdomain,$cnum)=split(/\//,$courseid);
8789: my $chome=homeserver($cnum,$cdomain);
8790: if (($chome eq '') || ($chome eq 'no_host')) {
8791: return 'error: no such course';
8792: }
8793: my $cstring='';
1.800 albertel 8794: foreach my $pref (keys(%prefs)) {
8795: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8796: }
1.84 www 8797: $cstring=~s/\&$//;
8798: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8799: }
8800:
8801: # ---------------------------------------------------------- Make/modify course
8802:
8803: sub createcourse {
1.741 raeburn 8804: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8805: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8806: $url=&declutter($url);
8807: my $cid='';
1.1028 raeburn 8808: if ($context eq 'requestcourses') {
8809: my $can_create = 0;
8810: my ($ownername,$ownerdom) = split(':',$course_owner);
8811: if ($udom eq $ownerdom) {
8812: if (&usertools_access($ownername,$ownerdom,$category,undef,
8813: $context)) {
8814: $can_create = 1;
8815: }
8816: } else {
8817: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8818: $category);
8819: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8820: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8821: if (@curr > 0) {
8822: my @options = qw(approval validate autolimit);
8823: my $optregex = join('|',@options);
8824: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8825: $can_create = 1;
8826: }
8827: }
8828: }
8829: }
8830: if ($can_create) {
8831: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8832: unless (&allowed('ccc',$udom)) {
8833: return 'refused';
8834: }
1.1017 raeburn 8835: }
8836: } else {
8837: return 'refused';
8838: }
1.1028 raeburn 8839: } elsif (!&allowed('ccc',$udom)) {
8840: return 'refused';
1.84 www 8841: }
1.1011 raeburn 8842: # --------------------------------------------------------------- Get Unique ID
8843: my $uname;
8844: if ($cnum =~ /^$match_courseid$/) {
8845: my $chome=&homeserver($cnum,$udom,'true');
8846: if (($chome eq '') || ($chome eq 'no_host')) {
8847: $uname = $cnum;
8848: } else {
1.1038 raeburn 8849: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8850: }
8851: } else {
1.1038 raeburn 8852: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8853: }
8854: return $uname if ($uname =~ /^error/);
8855: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8856: if (!defined($course_server)) {
8857: if (defined(&domain($udom,'primary'))) {
8858: $course_server = &domain($udom,'primary');
8859: } else {
8860: $course_server = $env{'user.home'};
8861: }
8862: }
8863: my %host_servers =
8864: &Apache::lonnet::get_servers($udom,'library');
8865: unless ($host_servers{$course_server}) {
8866: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8867: }
1.84 www 8868: # ------------------------------------------------------------- Make the course
8869: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8870: $course_server);
1.84 www 8871: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8872: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8873: if (($uhome eq '') || ($uhome eq 'no_host')) {
8874: return 'error: no such course';
8875: }
1.271 www 8876: # ----------------------------------------------------------------- Course made
1.516 raeburn 8877: # log existence
1.1029 raeburn 8878: my $now = time;
1.918 raeburn 8879: my $newcourse = {
8880: $udom.'_'.$uname => {
1.921 raeburn 8881: description => $description,
8882: inst_code => $inst_code,
8883: owner => $course_owner,
8884: type => $crstype,
1.1029 raeburn 8885: creator => $env{'user.name'}.':'.
8886: $env{'user.domain'},
8887: created => $now,
8888: context => $context,
1.918 raeburn 8889: },
8890: };
1.921 raeburn 8891: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8892: # set toplevel url
1.271 www 8893: my $topurl=$url;
8894: unless ($nonstandard) {
8895: # ------------------------------------------ For standard courses, make top url
8896: my $mapurl=&clutter($url);
1.278 www 8897: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8898: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8899: <map>
8900: <resource id="1" type="start"></resource>
8901: <resource id="2" src="$mapurl"></resource>
8902: <resource id="3" type="finish"></resource>
8903: <link index="1" from="1" to="2"></link>
8904: <link index="2" from="2" to="3"></link>
8905: </map>
8906: ENDINITMAP
8907: $topurl=&declutter(
1.638 albertel 8908: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8909: );
8910: }
8911: # ----------------------------------------------------------- Write preferences
1.84 www 8912: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8913: ('description' => $description,
8914: 'url' => $topurl,
8915: 'internal.creator' => $env{'user.name'}.':'.
8916: $env{'user.domain'},
8917: 'internal.created' => $now,
8918: 'internal.creationcontext' => $context)
8919: );
1.84 www 8920: return '/'.$udom.'/'.$uname;
8921: }
8922:
1.1011 raeburn 8923: # ------------------------------------------------------------------- Create ID
8924: sub generate_coursenum {
1.1038 raeburn 8925: my ($udom,$crstype) = @_;
1.1011 raeburn 8926: my $domdesc = &domain($udom);
8927: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8928: my $first;
8929: if ($crstype eq 'Community') {
8930: $first = '0';
8931: } else {
8932: $first = int(1+rand(9));
8933: }
8934: my $uname=$first.
1.1011 raeburn 8935: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8936: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8937: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8938: # ----------------------------------------------- Make sure that does not exist
8939: my $uhome=&homeserver($uname,$udom,'true');
8940: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8941: if ($crstype eq 'Community') {
8942: $first = '0';
8943: } else {
8944: $first = int(1+rand(9));
8945: }
8946: $uname=$first.
1.1011 raeburn 8947: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8948: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8949: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8950: $uhome=&homeserver($uname,$udom,'true');
8951: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8952: return 'error: unable to generate unique course-ID';
8953: }
8954: }
8955: return $uname;
8956: }
8957:
1.813 albertel 8958: sub is_course {
1.1167 droeschl 8959: my ($cdom, $cnum) = scalar(@_) == 1 ?
8960: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8961:
8962: return unless $cdom and $cnum;
8963:
8964: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8965: '.');
8966:
1.1172.2.23 raeburn 8967: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8968: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8969: }
8970:
1.1015 raeburn 8971: sub store_userdata {
8972: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8973: my $result;
1.1016 raeburn 8974: if ($datakey ne '') {
1.1013 raeburn 8975: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8976: if ($udom eq '' || $uname eq '') {
8977: $udom = $env{'user.domain'};
8978: $uname = $env{'user.name'};
8979: }
8980: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8981: if (($uhome eq '') || ($uhome eq 'no_host')) {
8982: $result = 'error: no_host';
8983: } else {
8984: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8985: $storehash->{'host'} = $perlvar{'lonHostID'};
8986:
8987: my $namevalue='';
8988: foreach my $key (keys(%{$storehash})) {
8989: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8990: }
8991: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8992: unless ($namespace eq 'courserequests') {
8993: $datakey = &escape($datakey);
8994: }
1.1105 raeburn 8995: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8996: $namevalue,$uhome);
1.1013 raeburn 8997: }
8998: } else {
8999: $result = 'error: data to store was not a hash reference';
9000: }
9001: } else {
9002: $result= 'error: invalid requestkey';
9003: }
9004: return $result;
9005: }
9006:
1.21 www 9007: # ---------------------------------------------------------- Assign Custom Role
9008:
9009: sub assigncustomrole {
1.957 raeburn 9010: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9011: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9012: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9013: }
9014:
9015: # ----------------------------------------------------------------- Revoke Role
9016:
9017: sub revokerole {
1.957 raeburn 9018: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9019: my $now=time;
1.965 raeburn 9020: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9021: }
9022:
9023: # ---------------------------------------------------------- Revoke Custom Role
9024:
9025: sub revokecustomrole {
1.957 raeburn 9026: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9027: my $now=time;
1.357 www 9028: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9029: $deleteflag,$selfenroll,$context);
1.17 www 9030: }
9031:
1.533 banghart 9032: # ------------------------------------------------------------ Disk usage
1.535 albertel 9033: sub diskusage {
1.955 raeburn 9034: my ($udom,$uname,$directorypath,$getpropath)=@_;
9035: $directorypath =~ s/\/$//;
9036: my $listing=&reply('du2:'.&escape($directorypath).':'
9037: .&escape($getpropath).':'.&escape($uname).':'
9038: .&escape($udom),homeserver($uname,$udom));
9039: if ($listing eq 'unknown_cmd') {
9040: if ($getpropath) {
9041: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9042: }
9043: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9044: }
1.514 albertel 9045: return $listing;
1.512 banghart 9046: }
9047:
1.566 banghart 9048: sub is_locked {
1.1096 raeburn 9049: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9050: my @check;
9051: my $is_locked;
1.1093 raeburn 9052: push (@check,$file_name);
1.613 albertel 9053: my %locked = &get('file_permissions',\@check,
1.620 albertel 9054: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9055: my ($tmp)=keys(%locked);
9056: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9057:
1.566 banghart 9058: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9059: $is_locked = 'false';
9060: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9061: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9062: $is_locked = 'true';
1.1096 raeburn 9063: if (ref($which) eq 'ARRAY') {
9064: push(@{$which},$entry);
9065: } else {
9066: last;
9067: }
1.745 raeburn 9068: }
9069: }
1.566 banghart 9070: } else {
9071: $is_locked = 'false';
9072: }
1.1093 raeburn 9073: return $is_locked;
1.566 banghart 9074: }
9075:
1.759 albertel 9076: sub declutter_portfile {
9077: my ($file) = @_;
1.833 albertel 9078: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9079: return $file;
9080: }
9081:
1.559 banghart 9082: # ------------------------------------------------------------- Mark as Read Only
9083:
9084: sub mark_as_readonly {
9085: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9086: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9087: my ($tmp)=keys(%current_permissions);
9088: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9089: foreach my $file (@{$files}) {
1.759 albertel 9090: $file = &declutter_portfile($file);
1.561 banghart 9091: push(@{$current_permissions{$file}},$what);
1.559 banghart 9092: }
1.613 albertel 9093: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9094: return;
9095: }
9096:
1.572 banghart 9097: # ------------------------------------------------------------Save Selected Files
9098:
9099: sub save_selected_files {
9100: my ($user, $path, @files) = @_;
9101: my $filename = $user."savedfiles";
1.573 banghart 9102: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9103: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9104: foreach my $file (@files) {
1.620 albertel 9105: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9106: }
9107: foreach my $file (@other_files) {
1.574 banghart 9108: print (OUT $file."\n");
1.572 banghart 9109: }
1.574 banghart 9110: close (OUT);
1.572 banghart 9111: return 'ok';
9112: }
9113:
1.574 banghart 9114: sub clear_selected_files {
9115: my ($user) = @_;
9116: my $filename = $user."savedfiles";
1.1117 foxr 9117: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9118: print (OUT undef);
9119: close (OUT);
9120: return ("ok");
9121: }
9122:
1.572 banghart 9123: sub files_in_path {
9124: my ($user, $path) = @_;
9125: my $filename = $user."savedfiles";
9126: my %return_files;
1.1117 foxr 9127: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9128: while (my $line_in = <IN>) {
1.574 banghart 9129: chomp ($line_in);
9130: my @paths_and_file = split (m!/!, $line_in);
9131: my $file_part = pop (@paths_and_file);
9132: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9133: $path_part.='/';
9134: my $path_and_file = $path_part.$file_part;
9135: if ($path_part eq $path) {
9136: $return_files{$file_part}= 'selected';
9137: }
9138: }
1.574 banghart 9139: close (IN);
9140: return (\%return_files);
1.572 banghart 9141: }
9142:
9143: # called in portfolio select mode, to show files selected NOT in current directory
9144: sub files_not_in_path {
9145: my ($user, $path) = @_;
9146: my $filename = $user."savedfiles";
9147: my @return_files;
9148: my $path_part;
1.1117 foxr 9149: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9150: while (my $line = <IN>) {
1.572 banghart 9151: #ok, I know it's clunky, but I want it to work
1.800 albertel 9152: my @paths_and_file = split(m|/|, $line);
9153: my $file_part = pop(@paths_and_file);
9154: chomp($file_part);
9155: my $path_part = join('/', @paths_and_file);
1.572 banghart 9156: $path_part .= '/';
9157: my $path_and_file = $path_part.$file_part;
9158: if ($path_part ne $path) {
1.800 albertel 9159: push(@return_files, ($path_and_file));
1.572 banghart 9160: }
9161: }
1.800 albertel 9162: close(OUT);
1.574 banghart 9163: return (@return_files);
1.572 banghart 9164: }
9165:
1.745 raeburn 9166: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9167:
1.745 raeburn 9168: sub get_portfile_permissions {
9169: my ($domain,$user) = @_;
1.613 albertel 9170: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9171: my ($tmp)=keys(%current_permissions);
9172: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9173: return \%current_permissions;
9174: }
9175:
9176: #---------------------------------------------Get portfolio file access controls
9177:
1.749 raeburn 9178: sub get_access_controls {
1.745 raeburn 9179: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9180: my %access;
9181: my $real_file = $file;
9182: $file =~ s/\.meta$//;
1.745 raeburn 9183: if (defined($file)) {
1.749 raeburn 9184: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9185: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9186: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9187: }
9188: }
1.745 raeburn 9189: } else {
1.749 raeburn 9190: foreach my $key (keys(%{$current_permissions})) {
9191: if ($key =~ /\0accesscontrol$/) {
9192: if (defined($group)) {
9193: if ($key !~ m-^\Q$group\E/-) {
9194: next;
9195: }
9196: }
9197: my ($fullpath) = split(/\0/,$key);
9198: if (ref($$current_permissions{$key}) eq 'HASH') {
9199: foreach my $control (keys(%{$$current_permissions{$key}})) {
9200: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9201: }
9202: }
9203: }
9204: }
9205: }
9206: return %access;
9207: }
9208:
9209: sub modify_access_controls {
9210: my ($file_name,$changes,$domain,$user)=@_;
9211: my ($outcome,$deloutcome);
9212: my %store_permissions;
9213: my %new_values;
9214: my %new_control;
9215: my %translation;
9216: my @deletions = ();
9217: my $now = time;
9218: if (exists($$changes{'activate'})) {
9219: if (ref($$changes{'activate'}) eq 'HASH') {
9220: my @newitems = sort(keys(%{$$changes{'activate'}}));
9221: my $numnew = scalar(@newitems);
9222: for (my $i=0; $i<$numnew; $i++) {
9223: my $newkey = $newitems[$i];
9224: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9225: if ($newkey =~ /^\d+:/) {
9226: $newkey =~ s/^(\d+)/$newid/;
9227: $translation{$1} = $newid;
9228: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9229: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9230: $translation{$1} = $newid;
9231: }
1.749 raeburn 9232: $new_values{$file_name."\0".$newkey} =
9233: $$changes{'activate'}{$newitems[$i]};
9234: $new_control{$newkey} = $now;
9235: }
9236: }
9237: }
9238: my %todelete;
9239: my %changed_items;
9240: foreach my $action ('delete','update') {
9241: if (exists($$changes{$action})) {
9242: if (ref($$changes{$action}) eq 'HASH') {
9243: foreach my $key (keys(%{$$changes{$action}})) {
9244: my ($itemnum) = ($key =~ /^([^:]+):/);
9245: if ($action eq 'delete') {
9246: $todelete{$itemnum} = 1;
9247: } else {
9248: $changed_items{$itemnum} = $key;
9249: }
9250: }
1.745 raeburn 9251: }
9252: }
1.749 raeburn 9253: }
9254: # get lock on access controls for file.
9255: my $lockhash = {
9256: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9257: ':'.$env{'user.domain'},
9258: };
9259: my $tries = 0;
9260: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9261:
9262: while (($gotlock ne 'ok') && $tries <3) {
9263: $tries ++;
9264: sleep 1;
9265: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9266: }
9267: if ($gotlock eq 'ok') {
9268: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9269: my ($tmp)=keys(%curr_permissions);
9270: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9271: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9272: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9273: if (ref($curr_controls) eq 'HASH') {
9274: foreach my $control_item (keys(%{$curr_controls})) {
9275: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9276: if (defined($todelete{$itemnum})) {
9277: push(@deletions,$file_name."\0".$control_item);
9278: } else {
9279: if (defined($changed_items{$itemnum})) {
9280: $new_control{$changed_items{$itemnum}} = $now;
9281: push(@deletions,$file_name."\0".$control_item);
9282: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9283: } else {
9284: $new_control{$control_item} = $$curr_controls{$control_item};
9285: }
9286: }
1.745 raeburn 9287: }
9288: }
9289: }
1.970 raeburn 9290: my ($group);
9291: if (&is_course($domain,$user)) {
9292: ($group,my $file) = split(/\//,$file_name,2);
9293: }
1.749 raeburn 9294: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9295: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9296: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9297: # remove lock
9298: my @del_lock = ($file_name."\0".'locked_access_records');
9299: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9300: my $sqlresult =
1.970 raeburn 9301: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9302: $group);
1.749 raeburn 9303: } else {
9304: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9305: }
1.749 raeburn 9306: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9307: }
9308:
1.827 raeburn 9309: sub make_public_indefinitely {
9310: my ($requrl) = @_;
9311: my $now = time;
9312: my $action = 'activate';
9313: my $aclnum = 0;
9314: if (&is_portfolio_url($requrl)) {
9315: my (undef,$udom,$unum,$file_name,$group) =
9316: &parse_portfolio_url($requrl);
9317: my $current_perms = &get_portfile_permissions($udom,$unum);
9318: my %access_controls = &get_access_controls($current_perms,
9319: $group,$file_name);
9320: foreach my $key (keys(%{$access_controls{$file_name}})) {
9321: my ($num,$scope,$end,$start) =
9322: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9323: if ($scope eq 'public') {
9324: if ($start <= $now && $end == 0) {
9325: $action = 'none';
9326: } else {
9327: $action = 'update';
9328: $aclnum = $num;
9329: }
9330: last;
9331: }
9332: }
9333: if ($action eq 'none') {
9334: return 'ok';
9335: } else {
9336: my %changes;
9337: my $newend = 0;
9338: my $newstart = $now;
9339: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9340: $changes{$action}{$newkey} = {
9341: type => 'public',
9342: time => {
9343: start => $newstart,
9344: end => $newend,
9345: },
9346: };
9347: my ($outcome,$deloutcome,$new_values,$translation) =
9348: &modify_access_controls($file_name,\%changes,$udom,$unum);
9349: return $outcome;
9350: }
9351: } else {
9352: return 'invalid';
9353: }
9354: }
9355:
1.745 raeburn 9356: #------------------------------------------------------Get Marked as Read Only
9357:
9358: sub get_marked_as_readonly {
9359: my ($domain,$user,$what,$group) = @_;
9360: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9361: my @readonly_files;
1.629 banghart 9362: my $cmp1=$what;
9363: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9364: while (my ($file_name,$value) = each(%{$current_permissions})) {
9365: if (defined($group)) {
9366: if ($file_name !~ m-^\Q$group\E/-) {
9367: next;
9368: }
9369: }
1.561 banghart 9370: if (ref($value) eq "ARRAY"){
9371: foreach my $stored_what (@{$value}) {
1.629 banghart 9372: my $cmp2=$stored_what;
1.759 albertel 9373: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9374: $cmp2=join('',@{$stored_what});
1.745 raeburn 9375: }
1.629 banghart 9376: if ($cmp1 eq $cmp2) {
1.561 banghart 9377: push(@readonly_files, $file_name);
1.745 raeburn 9378: last;
1.563 banghart 9379: } elsif (!defined($what)) {
9380: push(@readonly_files, $file_name);
1.745 raeburn 9381: last;
1.561 banghart 9382: }
9383: }
1.745 raeburn 9384: }
1.561 banghart 9385: }
9386: return @readonly_files;
9387: }
1.577 banghart 9388: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9389:
1.577 banghart 9390: sub get_marked_as_readonly_hash {
1.745 raeburn 9391: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9392: my %readonly_files;
1.745 raeburn 9393: while (my ($file_name,$value) = each(%{$current_permissions})) {
9394: if (defined($group)) {
9395: if ($file_name !~ m-^\Q$group\E/-) {
9396: next;
9397: }
9398: }
1.577 banghart 9399: if (ref($value) eq "ARRAY"){
9400: foreach my $stored_what (@{$value}) {
1.745 raeburn 9401: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9402: foreach my $lock_descriptor(@{$stored_what}) {
9403: if ($lock_descriptor eq 'graded') {
9404: $readonly_files{$file_name} = 'graded';
9405: } elsif ($lock_descriptor eq 'handback') {
9406: $readonly_files{$file_name} = 'handback';
9407: } else {
9408: if (!exists($readonly_files{$file_name})) {
9409: $readonly_files{$file_name} = 'locked';
9410: }
9411: }
1.745 raeburn 9412: }
1.750 banghart 9413: }
1.577 banghart 9414: }
9415: }
9416: }
9417: return %readonly_files;
9418: }
1.559 banghart 9419: # ------------------------------------------------------------ Unmark as Read Only
9420:
9421: sub unmark_as_readonly {
1.629 banghart 9422: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9423: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9424: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9425: $file_name = &declutter_portfile($file_name);
1.634 albertel 9426: my $symb_crs = $what;
9427: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9428: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9429: my ($tmp)=keys(%current_permissions);
9430: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9431: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9432: foreach my $file (@readonly_files) {
1.759 albertel 9433: my $clean_file = &declutter_portfile($file);
9434: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9435: my $current_locks = $current_permissions{$file};
1.563 banghart 9436: my @new_locks;
9437: my @del_keys;
9438: if (ref($current_locks) eq "ARRAY"){
9439: foreach my $locker (@{$current_locks}) {
1.632 albertel 9440: my $compare=$locker;
1.749 raeburn 9441: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9442: $compare=join('',@{$locker});
1.746 raeburn 9443: if ($compare ne $symb_crs) {
9444: push(@new_locks, $locker);
9445: }
1.563 banghart 9446: }
9447: }
1.650 albertel 9448: if (scalar(@new_locks) > 0) {
1.563 banghart 9449: $current_permissions{$file} = \@new_locks;
9450: } else {
9451: push(@del_keys, $file);
1.613 albertel 9452: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9453: delete($current_permissions{$file});
1.563 banghart 9454: }
9455: }
1.561 banghart 9456: }
1.613 albertel 9457: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9458: return;
9459: }
1.512 banghart 9460:
1.17 www 9461: # ------------------------------------------------------------ Directory lister
9462:
9463: sub dirlist {
1.955 raeburn 9464: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9465: $uri=~s/^\///;
9466: $uri=~s/\/$//;
1.253 stredwic 9467: my ($udom, $uname);
1.955 raeburn 9468: if ($getuserdir) {
1.253 stredwic 9469: $udom = $userdomain;
9470: $uname = $username;
1.955 raeburn 9471: } else {
9472: (undef,$udom,$uname)=split(/\//,$uri);
9473: if(defined($userdomain)) {
9474: $udom = $userdomain;
9475: }
9476: if(defined($username)) {
9477: $uname = $username;
9478: }
1.253 stredwic 9479: }
1.955 raeburn 9480: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9481:
1.955 raeburn 9482: $dirRoot = $perlvar{'lonDocRoot'};
9483: if (defined($getpropath)) {
9484: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9485: $dirRoot =~ s/\/$//;
1.955 raeburn 9486: } elsif (defined($getuserdir)) {
9487: my $subdir=$uname.'__';
9488: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9489: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9490: ."/$udom/$subdir/$uname";
9491: } elsif (defined($alternateRoot)) {
9492: $dirRoot = $alternateRoot;
1.751 banghart 9493: }
1.253 stredwic 9494:
9495: if($udom) {
9496: if($uname) {
1.1135 raeburn 9497: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9498: if ($uhome eq 'no_host') {
9499: return ([],'no_host');
9500: }
1.955 raeburn 9501: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9502: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9503: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9504: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9505: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9506: } else {
9507: @listing_results = map { &unescape($_); } split(/:/,$listing);
9508: }
1.605 matthew 9509: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9510: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9511: @listing_results = split(/:/,$listing);
9512: } else {
9513: @listing_results = map { &unescape($_); } split(/:/,$listing);
9514: }
1.1135 raeburn 9515: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9516: ($listing eq 'rejected') || ($listing eq 'refused') ||
9517: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9518: return ([],$listing);
9519: } else {
9520: return (\@listing_results);
1.1135 raeburn 9521: }
1.955 raeburn 9522: } elsif(!$alternateRoot) {
1.1136 raeburn 9523: my (%allusers,%listerror);
1.841 albertel 9524: my %servers = &get_servers($udom,'library');
1.955 raeburn 9525: foreach my $tryserver (keys(%servers)) {
9526: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9527: &escape($udom),$tryserver);
9528: if ($listing eq 'unknown_cmd') {
9529: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9530: $udom, $tryserver);
9531: } else {
9532: @listing_results = map { &unescape($_); } split(/:/,$listing);
9533: }
1.841 albertel 9534: if ($listing eq 'unknown_cmd') {
9535: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9536: $udom, $tryserver);
9537: @listing_results = split(/:/,$listing);
9538: } else {
9539: @listing_results =
9540: map { &unescape($_); } split(/:/,$listing);
9541: }
1.1136 raeburn 9542: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9543: ($listing eq 'rejected') || ($listing eq 'refused') ||
9544: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9545: $listerror{$tryserver} = $listing;
9546: } else {
1.841 albertel 9547: foreach my $line (@listing_results) {
9548: my ($entry) = split(/&/,$line,2);
9549: $allusers{$entry} = 1;
9550: }
9551: }
1.253 stredwic 9552: }
1.1136 raeburn 9553: my @alluserslist=();
1.800 albertel 9554: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9555: push(@alluserslist,$user.'&user');
1.253 stredwic 9556: }
1.1136 raeburn 9557: return (\@alluserslist);
1.253 stredwic 9558: } else {
1.1136 raeburn 9559: return ([],'missing username');
1.253 stredwic 9560: }
1.955 raeburn 9561: } elsif(!defined($getpropath)) {
1.1136 raeburn 9562: my $path = $perlvar{'lonDocRoot'}.'/res/';
9563: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9564: return (\@all_domains);
1.955 raeburn 9565: } else {
1.1136 raeburn 9566: return ([],'missing domain');
1.275 stredwic 9567: }
9568: }
9569:
9570: # --------------------------------------------- GetFileTimestamp
9571: # This function utilizes dirlist and returns the date stamp for
9572: # when it was last modified. It will also return an error of -1
9573: # if an error occurs
9574:
9575: sub GetFileTimestamp {
1.955 raeburn 9576: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9577: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9578: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9579: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9580: undef,$getuserdir);
9581: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9582: return -1;
9583: }
9584: if (ref($fileref) eq 'ARRAY') {
9585: my @stats = split('&',$fileref->[0]);
1.375 matthew 9586: # @stats contains first the filename, then the stat output
9587: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9588: } else {
9589: return -1;
1.253 stredwic 9590: }
1.26 www 9591: }
9592:
1.712 albertel 9593: sub stat_file {
9594: my ($uri) = @_;
1.787 albertel 9595: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9596:
1.955 raeburn 9597: my ($udom,$uname,$file);
1.712 albertel 9598: if ($uri =~ m-^/(uploaded|editupload)/-) {
9599: ($udom,$uname,$file) =
1.811 albertel 9600: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9601: $file = 'userfiles/'.$file;
9602: }
9603: if ($uri =~ m-^/res/-) {
9604: ($udom,$uname) =
1.807 albertel 9605: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9606: $file = $uri;
9607: }
9608:
9609: if (!$udom || !$uname || !$file) {
9610: # unable to handle the uri
9611: return ();
9612: }
1.956 raeburn 9613: my $getpropath;
9614: if ($file =~ /^userfiles\//) {
9615: $getpropath = 1;
9616: }
1.1136 raeburn 9617: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9618: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9619: return ();
9620: } else {
9621: if (ref($listref) eq 'ARRAY') {
9622: my @stats = split('&',$listref->[0]);
9623: shift(@stats); #filename is first
9624: return @stats;
9625: }
1.712 albertel 9626: }
9627: return ();
9628: }
9629:
1.26 www 9630: # -------------------------------------------------------- Value of a Condition
9631:
1.713 albertel 9632: # gets the value of a specific preevaluated condition
9633: # stored in the string $env{user.state.<cid>}
9634: # or looks up a condition reference in the bighash and if if hasn't
9635: # already been evaluated recurses into docondval to get the value of
9636: # the condition, then memoizing it to
9637: # $env{user.state.<cid>.<condition>}
1.40 www 9638: sub directcondval {
9639: my $number=shift;
1.620 albertel 9640: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9641: &Apache::lonuserstate::evalstate();
9642: }
1.713 albertel 9643: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9644: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9645: } elsif ($number =~ /^_/) {
9646: my $sub_condition;
9647: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9648: &GDBM_READER(),0640)) {
9649: $sub_condition=$bighash{'conditions'.$number};
9650: untie(%bighash);
9651: }
9652: my $value = &docondval($sub_condition);
1.949 raeburn 9653: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9654: return $value;
9655: }
1.620 albertel 9656: if ($env{'user.state.'.$env{'request.course.id'}}) {
9657: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9658: } else {
9659: return 2;
9660: }
9661: }
9662:
1.713 albertel 9663: # get the collection of conditions for this resource
1.26 www 9664: sub condval {
9665: my $condidx=shift;
1.54 www 9666: my $allpathcond='';
1.713 albertel 9667: foreach my $cond (split(/\|/,$condidx)) {
9668: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9669: $allpathcond.=
9670: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9671: }
1.191 harris41 9672: }
1.54 www 9673: $allpathcond=~s/\|$//;
1.713 albertel 9674: return &docondval($allpathcond);
9675: }
9676:
9677: #evaluates an expression of conditions
9678: sub docondval {
9679: my ($allpathcond) = @_;
9680: my $result=0;
9681: if ($env{'request.course.id'}
9682: && defined($allpathcond)) {
9683: my $operand='|';
9684: my @stack;
9685: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9686: if ($chunk eq '(') {
9687: push @stack,($operand,$result);
9688: } elsif ($chunk eq ')') {
9689: my $before=pop @stack;
9690: if (pop @stack eq '&') {
9691: $result=$result>$before?$before:$result;
9692: } else {
9693: $result=$result>$before?$result:$before;
9694: }
9695: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9696: $operand=$chunk;
9697: } else {
9698: my $new=directcondval($chunk);
9699: if ($operand eq '&') {
9700: $result=$result>$new?$new:$result;
9701: } else {
9702: $result=$result>$new?$result:$new;
9703: }
9704: }
9705: }
1.26 www 9706: }
9707: return $result;
1.421 albertel 9708: }
9709:
9710: # ---------------------------------------------------- Devalidate courseresdata
9711:
9712: sub devalidatecourseresdata {
9713: my ($coursenum,$coursedomain)=@_;
9714: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9715: &devalidate_cache_new('courseres',$hashid);
1.28 www 9716: }
9717:
1.763 www 9718:
1.200 www 9719: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9720: #
9721: # Parameters:
9722: # $coursenum - Number of the course.
9723: # $coursedomain - Domain at which the course was created.
9724: # Returns:
9725: # A hash of the course parameters along (I think) with timestamps
9726: # and version info.
1.877 foxr 9727:
1.624 albertel 9728: sub get_courseresdata {
9729: my ($coursenum,$coursedomain)=@_;
1.200 www 9730: my $coursehom=&homeserver($coursenum,$coursedomain);
9731: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9732: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9733: my %dumpreply;
1.417 albertel 9734: unless (defined($cached)) {
1.624 albertel 9735: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9736: $result=\%dumpreply;
1.251 albertel 9737: my ($tmp) = keys(%dumpreply);
9738: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9739: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9740: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9741: return $tmp;
1.416 albertel 9742: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9743: $result=undef;
1.599 albertel 9744: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9745: }
9746: }
1.624 albertel 9747: return $result;
9748: }
9749:
1.633 albertel 9750: sub devalidateuserresdata {
9751: my ($uname,$udom)=@_;
9752: my $hashid="$udom:$uname";
9753: &devalidate_cache_new('userres',$hashid);
9754: }
9755:
1.624 albertel 9756: sub get_userresdata {
9757: my ($uname,$udom)=@_;
9758: #most student don\'t have any data set, check if there is some data
9759: if (&EXT_cache_status($udom,$uname)) { return undef; }
9760:
9761: my $hashid="$udom:$uname";
9762: my ($result,$cached)=&is_cached_new('userres',$hashid);
9763: if (!defined($cached)) {
9764: my %resourcedata=&dump('resourcedata',$udom,$uname);
9765: $result=\%resourcedata;
9766: &do_cache_new('userres',$hashid,$result,600);
9767: }
9768: my ($tmp)=keys(%$result);
9769: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9770: return $result;
9771: }
9772: #error 2 occurs when the .db doesn't exist
9773: if ($tmp!~/error: 2 /) {
1.672 albertel 9774: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9775: " Trying to get resource data for ".
9776: $uname." at ".$udom.": ".
9777: $tmp."</font>");
9778: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9779: #&EXT_cache_set($udom,$uname);
9780: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9781: undef($tmp); # not really an error so don't send it back
1.624 albertel 9782: }
9783: return $tmp;
9784: }
1.879 foxr 9785: #----------------------------------------------- resdata - return resource data
9786: # Purpose:
9787: # Return resource data for either users or for a course.
9788: # Parameters:
9789: # $name - Course/user name.
9790: # $domain - Name of the domain the user/course is registered on.
9791: # $type - Type of thing $name is (must be 'course' or 'user'
9792: # @which - Array of names of resources desired.
9793: # Returns:
9794: # The value of the first reasource in @which that is found in the
9795: # resource hash.
9796: # Exceptional Conditions:
9797: # If the $type passed in is not valid (not the string 'course' or
9798: # 'user', an undefined reference is returned.
9799: # If none of the resources are found, an undef is returned
1.624 albertel 9800: sub resdata {
9801: my ($name,$domain,$type,@which)=@_;
9802: my $result;
9803: if ($type eq 'course') {
9804: $result=&get_courseresdata($name,$domain);
9805: } elsif ($type eq 'user') {
9806: $result=&get_userresdata($name,$domain);
9807: }
9808: if (!ref($result)) { return $result; }
1.251 albertel 9809: foreach my $item (@which) {
1.927 albertel 9810: if (defined($result->{$item->[0]})) {
9811: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9812: }
1.250 albertel 9813: }
1.291 albertel 9814: return undef;
1.200 www 9815: }
9816:
1.1172.2.31 raeburn 9817: sub get_numsuppfiles {
9818: my ($cnum,$cdom,$ignorecache)=@_;
9819: my $hashid=$cnum.':'.$cdom;
9820: my ($suppcount,$cached);
9821: unless ($ignorecache) {
9822: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9823: }
9824: unless (defined($cached)) {
9825: my $chome=&homeserver($cnum,$cdom);
9826: unless ($chome eq 'no_host') {
9827: ($suppcount,my $errors) = (0,0);
9828: my $suppmap = 'supplemental.sequence';
9829: ($suppcount,$errors) =
9830: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9831: }
9832: &do_cache_new('suppcount',$hashid,$suppcount,600);
9833: }
9834: return $suppcount;
9835: }
9836:
1.379 matthew 9837: #
9838: # EXT resource caching routines
9839: #
9840:
9841: sub clear_EXT_cache_status {
1.383 albertel 9842: &delenv('cache.EXT.');
1.379 matthew 9843: }
9844:
9845: sub EXT_cache_status {
9846: my ($target_domain,$target_user) = @_;
1.383 albertel 9847: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9848: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9849: # We know already the user has no data
9850: return 1;
9851: } else {
9852: return 0;
9853: }
9854: }
9855:
9856: sub EXT_cache_set {
9857: my ($target_domain,$target_user) = @_;
1.383 albertel 9858: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9859: #&appenv({$cachename => time});
1.379 matthew 9860: }
9861:
1.28 www 9862: # --------------------------------------------------------- Value of a Variable
1.58 www 9863: sub EXT {
1.715 albertel 9864:
1.1172.2.28 raeburn 9865: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9866: unless ($varname) { return ''; }
1.218 albertel 9867: #get real user name/domain, courseid and symb
9868: my $courseid;
1.359 albertel 9869: my $publicuser;
1.427 www 9870: if ($symbparm) {
9871: $symbparm=&get_symb_from_alias($symbparm);
9872: }
1.218 albertel 9873: if (!($uname && $udom)) {
1.790 albertel 9874: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9875: if (!$symbparm) { $symbparm=$cursymb; }
9876: } else {
1.620 albertel 9877: $courseid=$env{'request.course.id'};
1.218 albertel 9878: }
1.48 www 9879: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9880: my $rest;
1.320 albertel 9881: if (defined($therest[0])) {
1.48 www 9882: $rest=join('.',@therest);
9883: } else {
9884: $rest='';
9885: }
1.320 albertel 9886:
1.57 www 9887: my $qualifierrest=$qualifier;
9888: if ($rest) { $qualifierrest.='.'.$rest; }
9889: my $spacequalifierrest=$space;
9890: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9891: if ($realm eq 'user') {
1.48 www 9892: # --------------------------------------------------------------- user.resource
9893: if ($space eq 'resource') {
1.651 albertel 9894: if ( (defined($Apache::lonhomework::parsing_a_problem)
9895: || defined($Apache::lonhomework::parsing_a_task))
9896: &&
1.744 albertel 9897: ($symbparm eq &symbread()) ) {
9898: # if we are in the middle of processing the resource the
9899: # get the value we are planning on committing
9900: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9901: return $Apache::lonhomework::results{$qualifierrest};
9902: } else {
9903: return $Apache::lonhomework::history{$qualifierrest};
9904: }
1.335 albertel 9905: } else {
1.359 albertel 9906: my %restored;
1.620 albertel 9907: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9908: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9909: } else {
9910: %restored=&restore($symbparm,$courseid,$udom,$uname);
9911: }
1.335 albertel 9912: return $restored{$qualifierrest};
9913: }
1.48 www 9914: # ----------------------------------------------------------------- user.access
9915: } elsif ($space eq 'access') {
1.218 albertel 9916: # FIXME - not supporting calls for a specific user
1.48 www 9917: return &allowed($qualifier,$rest);
9918: # ------------------------------------------ user.preferences, user.environment
9919: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9920: if (($uname eq $env{'user.name'}) &&
9921: ($udom eq $env{'user.domain'})) {
9922: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9923: } else {
1.359 albertel 9924: my %returnhash;
9925: if (!$publicuser) {
9926: %returnhash=&userenvironment($udom,$uname,
9927: $qualifierrest);
9928: }
1.218 albertel 9929: return $returnhash{$qualifierrest};
9930: }
1.48 www 9931: # ----------------------------------------------------------------- user.course
9932: } elsif ($space eq 'course') {
1.218 albertel 9933: # FIXME - not supporting calls for a specific user
1.620 albertel 9934: return $env{join('.',('request.course',$qualifier))};
1.48 www 9935: # ------------------------------------------------------------------- user.role
9936: } elsif ($space eq 'role') {
1.218 albertel 9937: # FIXME - not supporting calls for a specific user
1.620 albertel 9938: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9939: if ($qualifier eq 'value') {
9940: return $role;
9941: } elsif ($qualifier eq 'extent') {
9942: return $where;
9943: }
9944: # ----------------------------------------------------------------- user.domain
9945: } elsif ($space eq 'domain') {
1.218 albertel 9946: return $udom;
1.48 www 9947: # ------------------------------------------------------------------- user.name
9948: } elsif ($space eq 'name') {
1.218 albertel 9949: return $uname;
1.48 www 9950: # ---------------------------------------------------- Any other user namespace
1.29 www 9951: } else {
1.359 albertel 9952: my %reply;
9953: if (!$publicuser) {
9954: %reply=&get($space,[$qualifierrest],$udom,$uname);
9955: }
9956: return $reply{$qualifierrest};
1.48 www 9957: }
1.236 www 9958: } elsif ($realm eq 'query') {
9959: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9960: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9961: [$spacequalifierrest]);
1.620 albertel 9962: return $env{'form.'.$spacequalifierrest};
1.236 www 9963: } elsif ($realm eq 'request') {
1.48 www 9964: # ------------------------------------------------------------- request.browser
9965: if ($space eq 'browser') {
1.1145 bisitz 9966: return $env{'browser.'.$qualifier};
1.57 www 9967: # ------------------------------------------------------------ request.filename
9968: } else {
1.620 albertel 9969: return $env{'request.'.$spacequalifierrest};
1.29 www 9970: }
1.28 www 9971: } elsif ($realm eq 'course') {
1.48 www 9972: # ---------------------------------------------------------- course.description
1.620 albertel 9973: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9974: } elsif ($realm eq 'resource') {
1.165 www 9975:
1.620 albertel 9976: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9977: if (!$symbparm) { $symbparm=&symbread(); }
9978: }
1.693 albertel 9979:
1.1172.2.30 raeburn 9980: if ($qualifier eq '') {
9981: if ($space eq 'title') {
9982: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9983: return &gettitle($symbparm);
9984: }
1.693 albertel 9985:
1.1172.2.30 raeburn 9986: if ($space eq 'map') {
9987: my ($map) = &decode_symb($symbparm);
9988: return &symbread($map);
9989: }
9990: if ($space eq 'maptitle') {
9991: my ($map) = &decode_symb($symbparm);
9992: return &gettitle($map);
9993: }
9994: if ($space eq 'filename') {
9995: if ($symbparm) {
9996: return &clutter((&decode_symb($symbparm))[2]);
9997: }
9998: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9999: }
1.1172.2.30 raeburn 10000:
10001: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10002: if ($space eq 'visibleparts') {
10003: my $navmap = Apache::lonnavmaps::navmap->new();
10004: my $item;
10005: if (ref($navmap)) {
10006: my $res = $navmap->getBySymb($symbparm);
10007: my $parts = $res->parts();
10008: if (ref($parts) eq 'ARRAY') {
10009: $item = join(',',@{$parts});
10010: }
10011: undef($navmap);
10012: }
10013: return $item;
10014: }
10015: }
10016: }
1.693 albertel 10017:
10018: my ($section, $group, @groups);
1.593 albertel 10019: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10020: if (($courseid eq '') && ($cid)) {
10021: $courseid = $cid;
10022: }
10023: if (($symbparm && $courseid) &&
10024: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10025:
1.218 albertel 10026: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10027:
1.60 www 10028: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10029: my $symbp=$symbparm;
1.735 albertel 10030: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10031:
10032: my $symbparm=$symbp.'.'.$spacequalifierrest;
10033: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10034:
1.620 albertel 10035: if (($env{'user.name'} eq $uname) &&
10036: ($env{'user.domain'} eq $udom)) {
10037: $section=$env{'request.course.sec'};
1.733 raeburn 10038: @groups = split(/:/,$env{'request.course.groups'});
10039: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10040: } else {
1.539 albertel 10041: if (! defined($usection)) {
1.551 albertel 10042: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10043: } else {
10044: $section = $usection;
10045: }
1.733 raeburn 10046: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10047: }
10048:
10049: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10050: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10051: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10052:
1.593 albertel 10053: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10054: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10055: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10056:
1.60 www 10057: # ----------------------------------------------------------- first, check user
1.624 albertel 10058:
10059: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10060: ([$courselevelr,'resource'],
10061: [$courselevelm,'map' ],
10062: [$courselevel, 'course' ]));
1.931 albertel 10063: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10064:
1.594 albertel 10065: # ------------------------------------------------ second, check some of course
1.684 raeburn 10066: my $coursereply;
1.691 raeburn 10067: if (@groups > 0) {
10068: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10069: $mapparm,$spacequalifierrest);
1.927 albertel 10070: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10071: }
1.96 www 10072:
1.684 raeburn 10073: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10074: $env{'course.'.$courseid.'.domain'},
10075: 'course',
10076: ([$seclevelr, 'resource'],
10077: [$seclevelm, 'map' ],
10078: [$seclevel, 'course' ],
10079: [$courselevelr,'resource']));
10080: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10081:
1.60 www 10082: # ------------------------------------------------------ third, check map parms
1.218 albertel 10083: my %parmhash=();
10084: my $thisparm='';
10085: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10086: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10087: &GDBM_READER(),0640)) {
1.218 albertel 10088: $thisparm=$parmhash{$symbparm};
10089: untie(%parmhash);
10090: }
1.927 albertel 10091: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10092: }
1.594 albertel 10093: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10094:
1.218 albertel 10095: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10096: my $filename;
10097: if (!$symbparm) { $symbparm=&symbread(); }
10098: if ($symbparm) {
1.409 www 10099: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10100: } else {
1.620 albertel 10101: $filename=$env{'request.filename'};
1.282 albertel 10102: }
10103: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10104: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10105: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10106: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10107:
1.927 albertel 10108: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10109: if ($symbparm && defined($courseid) &&
1.620 albertel 10110: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10111: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10112: $env{'course.'.$courseid.'.domain'},
10113: 'course',
1.927 albertel 10114: ([$courselevelm,'map' ],
10115: [$courselevel, 'course']));
10116: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10117: }
1.145 www 10118: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10119: unless ($space eq '0') {
1.336 albertel 10120: my @parts=split(/_/,$space);
10121: my $id=pop(@parts);
10122: my $part=join('_',@parts);
10123: if ($part eq '') { $part='0'; }
1.927 albertel 10124: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10125: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10126: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10127: }
1.395 albertel 10128: if ($recurse) { return undef; }
10129: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10130: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10131: # ---------------------------------------------------- Any other user namespace
10132: } elsif ($realm eq 'environment') {
10133: # ----------------------------------------------------------------- environment
1.620 albertel 10134: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10135: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10136: } else {
1.770 albertel 10137: if ($uname eq 'anonymous' && $udom eq '') {
10138: return '';
10139: }
1.219 albertel 10140: my %returnhash=&userenvironment($udom,$uname,
10141: $spacequalifierrest);
10142: return $returnhash{$spacequalifierrest};
10143: }
1.28 www 10144: } elsif ($realm eq 'system') {
1.48 www 10145: # ----------------------------------------------------------------- system.time
10146: if ($space eq 'time') {
10147: return time;
10148: }
1.696 albertel 10149: } elsif ($realm eq 'server') {
10150: # ----------------------------------------------------------------- system.time
10151: if ($space eq 'name') {
10152: return $ENV{'SERVER_NAME'};
10153: }
1.28 www 10154: }
1.48 www 10155: return '';
1.61 www 10156: }
10157:
1.927 albertel 10158: sub get_reply {
10159: my ($reply_value) = @_;
1.940 raeburn 10160: if (ref($reply_value) eq 'ARRAY') {
10161: if (wantarray) {
10162: return @$reply_value;
10163: }
10164: return $reply_value->[0];
10165: } else {
10166: return $reply_value;
1.927 albertel 10167: }
10168: }
10169:
1.691 raeburn 10170: sub check_group_parms {
10171: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10172: my @groupitems = ();
10173: my $resultitem;
1.927 albertel 10174: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10175: foreach my $group (@{$groups}) {
10176: foreach my $level (@levels) {
1.927 albertel 10177: my $item = $courseid.'.['.$group.'].'.$level->[0];
10178: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10179: }
10180: }
10181: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10182: $env{'course.'.$courseid.'.domain'},
10183: 'course',@groupitems);
10184: return $coursereply;
10185: }
10186:
10187: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10188: my ($courseid,@groups) = @_;
10189: @groups = sort(@groups);
1.691 raeburn 10190: return @groups;
10191: }
10192:
1.395 albertel 10193: sub packages_tab_default {
10194: my ($uri,$varname)=@_;
10195: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10196:
10197: my (@extension,@specifics,$do_default);
10198: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10199: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10200: if ($pack_type eq 'default') {
10201: $do_default=1;
10202: } elsif ($pack_type eq 'extension') {
10203: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10204: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10205: # only look at packages defaults for packages that this id is
1.738 albertel 10206: push(@specifics,[$package,$pack_type,$pack_part]);
10207: }
10208: }
10209: # first look for a package that matches the requested part id
10210: foreach my $package (@specifics) {
10211: my (undef,$pack_type,$pack_part)=@{$package};
10212: next if ($pack_part ne $part);
10213: if (defined($packagetab{"$pack_type&$name&default"})) {
10214: return $packagetab{"$pack_type&$name&default"};
10215: }
10216: }
10217: # look for any possible matching non extension_ package
10218: foreach my $package (@specifics) {
10219: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10220: if (defined($packagetab{"$pack_type&$name&default"})) {
10221: return $packagetab{"$pack_type&$name&default"};
10222: }
1.585 albertel 10223: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10224: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10225: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10226: }
10227: }
1.738 albertel 10228: # look for any posible extension_ match
10229: foreach my $package (@extension) {
10230: my ($package,$pack_type)=@{$package};
10231: if (defined($packagetab{"$pack_type&$name&default"})) {
10232: return $packagetab{"$pack_type&$name&default"};
10233: }
10234: if (defined($packagetab{$package."&$name&default"})) {
10235: return $packagetab{$package."&$name&default"};
10236: }
10237: }
10238: # look for a global default setting
10239: if ($do_default && defined($packagetab{"default&$name&default"})) {
10240: return $packagetab{"default&$name&default"};
10241: }
1.395 albertel 10242: return undef;
10243: }
10244:
1.334 albertel 10245: sub add_prefix_and_part {
10246: my ($prefix,$part)=@_;
10247: my $keyroot;
10248: if (defined($prefix) && $prefix !~ /^__/) {
10249: # prefix that has a part already
10250: $keyroot=$prefix;
10251: } elsif (defined($prefix)) {
10252: # prefix that is missing a part
10253: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10254: } else {
10255: # no prefix at all
10256: if (defined($part)) { $keyroot='_'.$part; }
10257: }
10258: return $keyroot;
10259: }
10260:
1.71 www 10261: # ---------------------------------------------------------------- Get metadata
10262:
1.599 albertel 10263: my %metaentry;
1.1070 www 10264: my %importedpartids;
1.71 www 10265: sub metadata {
1.176 www 10266: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10267: $uri=&declutter($uri);
1.288 albertel 10268: # if it is a non metadata possible uri return quickly
1.529 albertel 10269: if (($uri eq '') ||
10270: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10271: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10272: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10273: return undef;
10274: }
1.1140 www 10275: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10276: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10277: return undef;
1.288 albertel 10278: }
1.73 www 10279: my $filename=$uri;
10280: $uri=~s/\.meta$//;
1.172 www 10281: #
10282: # Is the metadata already cached?
1.177 www 10283: # Look at timestamp of caching
1.172 www 10284: # Everything is cached by the main uri, libraries are never directly cached
10285: #
1.428 albertel 10286: if (!defined($liburi)) {
1.599 albertel 10287: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10288: if (defined($cached)) { return $result->{':'.$what}; }
10289: }
10290: {
1.1069 www 10291: # Imported parts would go here
1.1070 www 10292: my %importedids=();
10293: my @origfileimportpartids=();
1.1069 www 10294: my $importedparts=0;
1.172 www 10295: #
10296: # Is this a recursive call for a library?
10297: #
1.599 albertel 10298: # if (! exists($metacache{$uri})) {
10299: # $metacache{$uri}={};
10300: # }
1.924 albertel 10301: my $cachetime = 60*60;
1.171 www 10302: if ($liburi) {
10303: $liburi=&declutter($liburi);
10304: $filename=$liburi;
1.401 bowersj2 10305: } else {
1.599 albertel 10306: &devalidate_cache_new('meta',$uri);
10307: undef(%metaentry);
1.401 bowersj2 10308: }
1.140 www 10309: my %metathesekeys=();
1.73 www 10310: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10311: my $metastring;
1.1140 www 10312: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10313: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10314: $metastring =
1.929 albertel 10315: &Apache::lonnet::ssi_body($which,
1.924 albertel 10316: ('grade_target' => 'meta'));
10317: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10318: } elsif (($uri !~ m -^(editupload)/-) &&
10319: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10320: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10321: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10322: $metastring=&getfile($file);
1.489 albertel 10323: }
1.208 albertel 10324: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10325: my $token;
1.140 www 10326: undef %metathesekeys;
1.71 www 10327: while ($token=$parser->get_token) {
1.339 albertel 10328: if ($token->[0] eq 'S') {
10329: if (defined($token->[2]->{'package'})) {
1.172 www 10330: #
10331: # This is a package - get package info
10332: #
1.339 albertel 10333: my $package=$token->[2]->{'package'};
10334: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10335: if (defined($token->[2]->{'id'})) {
10336: $keyroot.='_'.$token->[2]->{'id'};
10337: }
1.599 albertel 10338: if ($metaentry{':packages'}) {
10339: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10340: } else {
1.599 albertel 10341: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10342: }
1.736 albertel 10343: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10344: my $part=$keyroot;
10345: $part=~s/^\_//;
1.736 albertel 10346: if ($pack_entry=~/^\Q$package\E\&/ ||
10347: $pack_entry=~/^\Q$package\E_0\&/) {
10348: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10349: # ignore package.tab specified default values
10350: # here &package_tab_default() will fetch those
10351: if ($subp eq 'default') { next; }
1.736 albertel 10352: my $value=$packagetab{$pack_entry};
1.432 albertel 10353: my $unikey;
10354: if ($pack =~ /_0$/) {
10355: $unikey='parameter_0_'.$name;
10356: $part=0;
10357: } else {
10358: $unikey='parameter'.$keyroot.'_'.$name;
10359: }
1.339 albertel 10360: if ($subp eq 'display') {
10361: $value.=' [Part: '.$part.']';
10362: }
1.599 albertel 10363: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10364: $metathesekeys{$unikey}=1;
1.599 albertel 10365: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10366: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10367: }
1.599 albertel 10368: if (defined($metaentry{':'.$unikey.'.default'})) {
10369: $metaentry{':'.$unikey}=
10370: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10371: }
1.339 albertel 10372: }
10373: }
10374: } else {
1.172 www 10375: #
10376: # This is not a package - some other kind of start tag
1.339 albertel 10377: #
10378: my $entry=$token->[1];
1.1068 www 10379: my $unikey='';
1.175 www 10380:
1.339 albertel 10381: if ($entry eq 'import') {
1.175 www 10382: #
10383: # Importing a library here
1.339 albertel 10384: #
1.1067 www 10385: my $location=$parser->get_text('/import');
10386: my $dir=$filename;
10387: $dir=~s|[^/]*$||;
10388: $location=&filelocation($dir,$location);
1.1069 www 10389:
1.1068 www 10390: my $importmode=$token->[2]->{'importmode'};
10391: if ($importmode eq 'problem') {
1.1069 www 10392: # Import as problem/response
1.1068 www 10393: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10394: } elsif ($importmode eq 'part') {
10395: # Import as part(s)
1.1069 www 10396: $importedparts=1;
10397: # We need to get the original file and the imported file to get the part order correct
10398: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10399: # Load and inspect original file
1.1070 www 10400: if ($#origfileimportpartids<0) {
10401: undef(%importedpartids);
10402: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10403: my $origfile=&getfile($origfilelocation);
10404: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10405: }
10406:
1.1069 www 10407: # Load and inspect imported file
10408: my $impfile=&getfile($location);
10409: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10410: if ($#impfilepartids>=0) {
10411: # This problem had parts
1.1070 www 10412: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10413: } else {
10414: # Importing by turning a single problem into a problem part
10415: # It gets the import-tags ID as part-ID
10416: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10417: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10418: }
1.1068 www 10419: } else {
10420: # Normal import
10421: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10422: if (defined($token->[2]->{'id'})) {
10423: $unikey.='_'.$token->[2]->{'id'};
10424: }
1.1067 www 10425: }
10426:
1.339 albertel 10427: if ($depthcount<20) {
1.736 albertel 10428: my $metadata =
10429: &metadata($uri,'keys', $location,$unikey,
10430: $depthcount+1);
10431: foreach my $meta (split(',',$metadata)) {
10432: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10433: $metathesekeys{$meta}=1;
1.339 albertel 10434: }
1.1068 www 10435:
10436: }
1.1067 www 10437: } else {
10438: #
10439: # Not importing, some other kind of non-package, non-library start tag
10440: #
10441: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10442: if (defined($token->[2]->{'id'})) {
10443: $unikey.='_'.$token->[2]->{'id'};
10444: }
1.339 albertel 10445: if (defined($token->[2]->{'name'})) {
10446: $unikey.='_'.$token->[2]->{'name'};
10447: }
10448: $metathesekeys{$unikey}=1;
1.736 albertel 10449: foreach my $param (@{$token->[3]}) {
10450: $metaentry{':'.$unikey.'.'.$param} =
10451: $token->[2]->{$param};
1.339 albertel 10452: }
10453: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10454: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10455: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10456: # only ws inside the tag, and not in default, so use default
10457: # as value
1.599 albertel 10458: $metaentry{':'.$unikey}=$default;
1.908 albertel 10459: } elsif ( $internaltext =~ /\S/ ) {
10460: # something interesting inside the tag
10461: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10462: } else {
1.908 albertel 10463: # no interesting values, don't set a default
1.339 albertel 10464: }
1.172 www 10465: # end of not-a-package not-a-library import
1.339 albertel 10466: }
1.172 www 10467: # end of not-a-package start tag
1.339 albertel 10468: }
1.172 www 10469: # the next is the end of "start tag"
1.339 albertel 10470: }
10471: }
1.483 albertel 10472: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10473: $extension = lc($extension);
10474: if ($extension eq 'htm') { $extension='html'; }
10475:
1.737 albertel 10476: foreach my $key (keys(%packagetab)) {
1.483 albertel 10477: #no specific packages #how's our extension
10478: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10479: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10480: \%metathesekeys);
10481: }
1.883 albertel 10482:
10483: if (!exists($metaentry{':packages'})
10484: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10485: foreach my $key (keys(%packagetab)) {
1.483 albertel 10486: #no specific packages well let's get default then
10487: if ($key!~/^default&/) { next; }
1.488 albertel 10488: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10489: \%metathesekeys);
10490: }
10491: }
1.338 www 10492: # are there custom rights to evaluate
1.599 albertel 10493: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10494:
1.338 www 10495: #
10496: # Importing a rights file here
1.339 albertel 10497: #
10498: unless ($depthcount) {
1.599 albertel 10499: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10500: my $dir=$filename;
10501: $dir=~s|[^/]*$||;
10502: $location=&filelocation($dir,$location);
1.736 albertel 10503: my $rights_metadata =
10504: &metadata($uri,'keys',$location,'_rights',
10505: $depthcount+1);
10506: foreach my $rights (split(',',$rights_metadata)) {
10507: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10508: $metathesekeys{$rights}=1;
1.339 albertel 10509: }
10510: }
10511: }
1.737 albertel 10512: # uniqifiy package listing
10513: my %seen;
10514: my @uniq_packages =
10515: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10516: $metaentry{':packages'} = join(',',@uniq_packages);
10517:
1.1070 www 10518: if ($importedparts) {
10519: # We had imported parts and need to rebuild partorder
10520: $metaentry{':partorder'}='';
10521: $metathesekeys{'partorder'}=1;
10522: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10523: if ($origfileimportpartids[$index] eq 'part') {
10524: # original part, part of the problem
10525: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10526: } else {
10527: # we have imported parts at this position
10528: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10529: }
10530: }
10531: $metaentry{':partorder'}=~s/^\,//;
10532: }
10533:
1.737 albertel 10534: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10535: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10536: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10537: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10538: # this is the end of "was not already recently cached
1.71 www 10539: }
1.599 albertel 10540: return $metaentry{':'.$what};
1.261 albertel 10541: }
10542:
1.488 albertel 10543: sub metadata_create_package_def {
1.483 albertel 10544: my ($uri,$key,$package,$metathesekeys)=@_;
10545: my ($pack,$name,$subp)=split(/\&/,$key);
10546: if ($subp eq 'default') { next; }
10547:
1.599 albertel 10548: if (defined($metaentry{':packages'})) {
10549: $metaentry{':packages'}.=','.$package;
1.483 albertel 10550: } else {
1.599 albertel 10551: $metaentry{':packages'}=$package;
1.483 albertel 10552: }
10553: my $value=$packagetab{$key};
10554: my $unikey;
10555: $unikey='parameter_0_'.$name;
1.599 albertel 10556: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10557: $$metathesekeys{$unikey}=1;
1.599 albertel 10558: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10559: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10560: }
1.599 albertel 10561: if (defined($metaentry{':'.$unikey.'.default'})) {
10562: $metaentry{':'.$unikey}=
10563: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10564: }
10565: }
10566:
1.261 albertel 10567: sub metadata_generate_part0 {
10568: my ($metadata,$metacache,$uri) = @_;
10569: my %allnames;
1.737 albertel 10570: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10571: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10572: my $part=$$metacache{':'.$metakey.'.part'};
10573: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10574: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10575: $allnames{$name}=$part;
10576: }
10577: }
10578: }
10579: foreach my $name (keys(%allnames)) {
10580: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10581: my $key=":parameter_0_$name";
1.261 albertel 10582: $$metacache{"$key.part"}='0';
10583: $$metacache{"$key.name"}=$name;
1.428 albertel 10584: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10585: $allnames{$name}.'_'.$name.
10586: '.type'};
1.428 albertel 10587: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10588: '.display'};
1.644 www 10589: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10590: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10591: $$metacache{"$key.display"}=$olddis;
10592: }
1.71 www 10593: }
10594:
1.764 albertel 10595: # ------------------------------------------------------ Devalidate title cache
10596:
10597: sub devalidate_title_cache {
10598: my ($url)=@_;
10599: if (!$env{'request.course.id'}) { return; }
10600: my $symb=&symbread($url);
10601: if (!$symb) { return; }
10602: my $key=$env{'request.course.id'}."\0".$symb;
10603: &devalidate_cache_new('title',$key);
10604: }
10605:
1.1014 droeschl 10606: # ------------------------------------------------- Get the title of a course
10607:
10608: sub current_course_title {
10609: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10610: }
1.301 www 10611: # ------------------------------------------------- Get the title of a resource
10612:
10613: sub gettitle {
10614: my $urlsymb=shift;
10615: my $symb=&symbread($urlsymb);
1.534 albertel 10616: if ($symb) {
1.620 albertel 10617: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10618: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10619: if (defined($cached)) {
10620: return $result;
10621: }
1.534 albertel 10622: my ($map,$resid,$url)=&decode_symb($symb);
10623: my $title='';
1.907 albertel 10624: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10625: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10626: } else {
10627: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10628: &GDBM_READER(),0640)) {
10629: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10630: $title=$bighash{'title_'.$mapid.'.'.$resid};
10631: untie(%bighash);
10632: }
1.534 albertel 10633: }
10634: $title=~s/\&colon\;/\:/gs;
10635: if ($title) {
1.1159 www 10636: # Remember both $symb and $title for dynamic metadata
10637: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10638: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10639: # Cache this title and then return it
1.599 albertel 10640: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10641: }
10642: $urlsymb=$url;
10643: }
10644: my $title=&metadata($urlsymb,'title');
10645: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10646: return $title;
1.301 www 10647: }
1.613 albertel 10648:
1.614 albertel 10649: sub get_slot {
10650: my ($which,$cnum,$cdom)=@_;
10651: if (!$cnum || !$cdom) {
1.790 albertel 10652: (undef,my $courseid)=&whichuser();
1.620 albertel 10653: $cdom=$env{'course.'.$courseid.'.domain'};
10654: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10655: }
1.703 albertel 10656: my $key=join("\0",'slots',$cdom,$cnum,$which);
10657: my %slotinfo;
10658: if (exists($remembered{$key})) {
10659: $slotinfo{$which} = $remembered{$key};
10660: } else {
10661: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10662: &Apache::lonhomework::showhash(%slotinfo);
10663: my ($tmp)=keys(%slotinfo);
10664: if ($tmp=~/^error:/) { return (); }
10665: $remembered{$key} = $slotinfo{$which};
10666: }
1.616 albertel 10667: if (ref($slotinfo{$which}) eq 'HASH') {
10668: return %{$slotinfo{$which}};
10669: }
10670: return $slotinfo{$which};
1.614 albertel 10671: }
1.1150 raeburn 10672:
10673: sub get_reservable_slots {
10674: my ($cnum,$cdom,$uname,$udom) = @_;
10675: my $now = time;
10676: my $reservable_info;
10677: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10678: if (exists($remembered{$key})) {
10679: $reservable_info = $remembered{$key};
10680: } else {
10681: my %resv;
10682: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10683: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10684: $reservable_info = \%resv;
10685: $remembered{$key} = $reservable_info;
10686: }
10687: return $reservable_info;
10688: }
10689:
10690: sub get_course_slots {
10691: my ($cnum,$cdom) = @_;
10692: my $hashid=$cnum.':'.$cdom;
10693: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10694: if (defined($cached)) {
10695: if (ref($result) eq 'HASH') {
10696: return %{$result};
10697: }
10698: } else {
10699: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10700: my ($tmp) = keys(%slots);
10701: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10702: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10703: return %slots;
10704: }
10705: }
10706: return;
10707: }
10708:
10709: sub devalidate_slots_cache {
10710: my ($cnum,$cdom)=@_;
10711: my $hashid=$cnum.':'.$cdom;
10712: &devalidate_cache_new('allslots',$hashid);
10713: }
10714:
1.1172.2.8 raeburn 10715: sub get_coursechange {
10716: my ($cdom,$cnum) = @_;
10717: if ($cdom eq '' || $cnum eq '') {
10718: return unless ($env{'request.course.id'});
10719: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10720: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10721: }
10722: my $hashid=$cdom.'_'.$cnum;
10723: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10724: if ((defined($cached)) && ($change ne '')) {
10725: return $change;
10726: } else {
10727: my %crshash;
10728: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10729: if ($crshash{'internal.contentchange'} eq '') {
10730: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10731: if ($change eq '') {
10732: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10733: $change = $crshash{'internal.created'};
10734: }
10735: } else {
10736: $change = $crshash{'internal.contentchange'};
10737: }
10738: my $cachetime = 600;
10739: &do_cache_new('crschange',$hashid,$change,$cachetime);
10740: }
10741: return $change;
10742: }
10743:
10744: sub devalidate_coursechange_cache {
10745: my ($cnum,$cdom)=@_;
10746: my $hashid=$cnum.':'.$cdom;
10747: &devalidate_cache_new('crschange',$hashid);
10748: }
10749:
1.31 www 10750: # ------------------------------------------------- Update symbolic store links
10751:
10752: sub symblist {
10753: my ($mapname,%newhash)=@_;
1.438 www 10754: $mapname=&deversion(&declutter($mapname));
1.31 www 10755: my %hash;
1.620 albertel 10756: if (($env{'request.course.fn'}) && (%newhash)) {
10757: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10758: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10759: foreach my $url (keys(%newhash)) {
1.711 albertel 10760: next if ($url eq 'last_known'
10761: && $env{'form.no_update_last_known'});
10762: $hash{declutter($url)}=&encode_symb($mapname,
10763: $newhash{$url}->[1],
10764: $newhash{$url}->[0]);
1.191 harris41 10765: }
1.31 www 10766: if (untie(%hash)) {
10767: return 'ok';
10768: }
10769: }
10770: }
10771: return 'error';
1.212 www 10772: }
10773:
10774: # --------------------------------------------------------------- Verify a symb
10775:
10776: sub symbverify {
1.1172.2.11 raeburn 10777: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10778: my $thisfn=$thisurl;
1.439 www 10779: $thisfn=&declutter($thisfn);
1.215 www 10780: # direct jump to resource in page or to a sequence - will construct own symbs
10781: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10782: # check URL part
1.409 www 10783: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10784:
1.431 www 10785: unless ($url eq $thisfn) { return 0; }
1.213 www 10786:
1.216 www 10787: $symb=&symbclean($symb);
1.510 www 10788: $thisurl=&deversion($thisurl);
1.439 www 10789: $thisfn=&deversion($thisfn);
1.213 www 10790:
10791: my %bighash;
10792: my $okay=0;
1.431 www 10793:
1.620 albertel 10794: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10795: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10796: my $noclutter;
1.1032 raeburn 10797: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10798: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10799: if ($map =~ m{^uploaded/.+\.page$}) {
10800: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10801: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10802: $noclutter = 1;
10803: }
10804: }
10805: my $ids;
10806: if ($noclutter) {
10807: $ids=$bighash{'ids_'.$thisurl};
10808: } else {
10809: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10810: }
1.1102 raeburn 10811: unless ($ids) {
1.1172.2.13 raeburn 10812: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10813: $ids=$bighash{$idkey};
1.216 www 10814: }
10815: if ($ids) {
10816: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10817: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10818: $symb =~ s/\?.+$//;
10819: }
1.800 albertel 10820: foreach my $id (split(/\,/,$ids)) {
10821: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10822: if (
10823: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10824: eq $symb) {
1.1172.2.11 raeburn 10825: if (ref($encstate)) {
10826: $$encstate = $bighash{'encrypted_'.$id};
10827: }
1.1172.2.13 raeburn 10828: if (($env{'request.role.adv'}) ||
10829: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10830: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10831: $okay=1;
10832: last;
10833: }
10834: }
10835: }
1.216 www 10836: }
1.213 www 10837: untie(%bighash);
10838: }
10839: return $okay;
1.31 www 10840: }
10841:
1.210 www 10842: # --------------------------------------------------------------- Clean-up symb
10843:
10844: sub symbclean {
10845: my $symb=shift;
1.568 albertel 10846: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10847: # remove version from map
10848: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10849:
1.210 www 10850: # remove version from URL
10851: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10852:
1.507 www 10853: # remove wrapper
10854:
1.510 www 10855: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10856: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10857: return $symb;
1.409 www 10858: }
10859:
10860: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10861:
10862: sub encode_symb {
10863: my ($map,$resid,$url)=@_;
10864: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10865: }
1.409 www 10866:
10867: sub decode_symb {
1.568 albertel 10868: my $symb=shift;
10869: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10870: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10871: return (&fixversion($map),$resid,&fixversion($url));
10872: }
10873:
10874: sub fixversion {
10875: my $fn=shift;
1.609 banghart 10876: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10877: my %bighash;
10878: my $uri=&clutter($fn);
1.620 albertel 10879: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10880: # is this cached?
1.599 albertel 10881: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10882: if (defined($cached)) { return $result; }
10883: # unfortunately not cached, or expired
1.620 albertel 10884: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10885: &GDBM_READER(),0640)) {
10886: if ($bighash{'version_'.$uri}) {
10887: my $version=$bighash{'version_'.$uri};
1.444 www 10888: unless (($version eq 'mostrecent') ||
10889: ($version==&getversion($uri))) {
1.440 www 10890: $uri=~s/\.(\w+)$/\.$version\.$1/;
10891: }
10892: }
10893: untie %bighash;
1.413 www 10894: }
1.599 albertel 10895: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10896: }
10897:
10898: sub deversion {
10899: my $url=shift;
10900: $url=~s/\.\d+\.(\w+)$/\.$1/;
10901: return $url;
1.210 www 10902: }
10903:
1.31 www 10904: # ------------------------------------------------------ Return symb list entry
10905:
10906: sub symbread {
1.249 www 10907: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10908: my $cache_str;
10909: if ($thisfn ne '') {
10910: $cache_str='request.symbread.cached.'.$thisfn;
10911: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10912: return $env{$cache_str};
10913: }
1.1172.2.13 raeburn 10914: } else {
1.242 www 10915: # no filename provided? try from environment
1.620 albertel 10916: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10917: return $env{$cache_str}=&symbclean($env{'request.symb'});
10918: }
10919: $thisfn=$env{'request.filename'};
1.44 www 10920: }
1.569 albertel 10921: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10922: # is that filename actually a symb? Verify, clean, and return
10923: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10924: if (&symbverify($thisfn,$1)) {
1.620 albertel 10925: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10926: }
1.242 www 10927: }
1.44 www 10928: $thisfn=declutter($thisfn);
1.31 www 10929: my %hash;
1.37 www 10930: my %bighash;
10931: my $syval='';
1.620 albertel 10932: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10933: my $targetfn = $thisfn;
1.609 banghart 10934: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10935: $targetfn = 'adm/wrapper/'.$thisfn;
10936: }
1.687 albertel 10937: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10938: $targetfn=$1;
10939: }
1.620 albertel 10940: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10941: &GDBM_READER(),0640)) {
1.481 raeburn 10942: $syval=$hash{$targetfn};
1.37 www 10943: untie(%hash);
10944: }
10945: # ---------------------------------------------------------- There was an entry
10946: if ($syval) {
1.601 albertel 10947: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10948: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10949: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10950: #return $env{$cache_str}='';
1.601 albertel 10951: #}
10952: #$syval.=$1;
10953: #}
1.37 www 10954: } else {
10955: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10956: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10957: &GDBM_READER(),0640)) {
1.37 www 10958: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10959: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10960: unless ($ids) {
10961: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10962: }
10963: unless ($ids) {
10964: # alias?
10965: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10966: }
1.37 www 10967: if ($ids) {
10968: # ------------------------------------------------------------------- Has ID(s)
10969: my @possibilities=split(/\,/,$ids);
1.39 www 10970: if ($#possibilities==0) {
10971: # ----------------------------------------------- There is only one possibility
1.37 www 10972: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10973: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10974: $resid,$thisfn);
1.249 www 10975: } elsif (!$donotrecurse) {
1.39 www 10976: # ------------------------------------------ There is more than one possibility
10977: my $realpossible=0;
1.800 albertel 10978: foreach my $id (@possibilities) {
10979: my $file=$bighash{'src_'.$id};
1.39 www 10980: if (&allowed('bre',$file)) {
1.800 albertel 10981: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10982: if ($bighash{'map_type_'.$mapid} ne 'page') {
10983: $realpossible++;
1.626 albertel 10984: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10985: $resid,$thisfn);
1.39 www 10986: }
10987: }
1.191 harris41 10988: }
1.39 www 10989: if ($realpossible!=1) { $syval=''; }
1.249 www 10990: } else {
10991: $syval='';
1.37 www 10992: }
10993: }
10994: untie(%bighash)
1.481 raeburn 10995: }
1.31 www 10996: }
1.62 www 10997: if ($syval) {
1.620 albertel 10998: return $env{$cache_str}=$syval;
1.62 www 10999: }
1.31 www 11000: }
1.949 raeburn 11001: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11002: return $env{$cache_str}='';
1.31 www 11003: }
11004:
11005: # ---------------------------------------------------------- Return random seed
11006:
1.32 www 11007: sub numval {
11008: my $txt=shift;
11009: $txt=~tr/A-J/0-9/;
11010: $txt=~tr/a-j/0-9/;
11011: $txt=~tr/K-T/0-9/;
11012: $txt=~tr/k-t/0-9/;
11013: $txt=~tr/U-Z/0-5/;
11014: $txt=~tr/u-z/0-5/;
11015: $txt=~s/\D//g;
1.564 albertel 11016: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11017: return int($txt);
1.368 albertel 11018: }
11019:
1.484 albertel 11020: sub numval2 {
11021: my $txt=shift;
11022: $txt=~tr/A-J/0-9/;
11023: $txt=~tr/a-j/0-9/;
11024: $txt=~tr/K-T/0-9/;
11025: $txt=~tr/k-t/0-9/;
11026: $txt=~tr/U-Z/0-5/;
11027: $txt=~tr/u-z/0-5/;
11028: $txt=~s/\D//g;
11029: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11030: my $total;
11031: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11032: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11033: return int($total);
11034: }
11035:
1.575 albertel 11036: sub numval3 {
11037: use integer;
11038: my $txt=shift;
11039: $txt=~tr/A-J/0-9/;
11040: $txt=~tr/a-j/0-9/;
11041: $txt=~tr/K-T/0-9/;
11042: $txt=~tr/k-t/0-9/;
11043: $txt=~tr/U-Z/0-5/;
11044: $txt=~tr/u-z/0-5/;
11045: $txt=~s/\D//g;
11046: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11047: my $total;
11048: foreach my $val (@txts) { $total+=$val; }
11049: if ($_64bit) { $total=(($total<<32)>>32); }
11050: return $total;
11051: }
11052:
1.675 albertel 11053: sub digest {
11054: my ($data)=@_;
11055: my $digest=&Digest::MD5::md5($data);
11056: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11057: my ($e,$f);
11058: {
11059: use integer;
11060: $e=($a+$b);
11061: $f=($c+$d);
11062: if ($_64bit) {
11063: $e=(($e<<32)>>32);
11064: $f=(($f<<32)>>32);
11065: }
11066: }
11067: if (wantarray) {
11068: return ($e,$f);
11069: } else {
11070: my $g;
11071: {
11072: use integer;
11073: $g=($e+$f);
11074: if ($_64bit) {
11075: $g=(($g<<32)>>32);
11076: }
11077: }
11078: return $g;
11079: }
11080: }
11081:
1.368 albertel 11082: sub latest_rnd_algorithm_id {
1.675 albertel 11083: return '64bit5';
1.366 albertel 11084: }
1.32 www 11085:
1.503 albertel 11086: sub get_rand_alg {
11087: my ($courseid)=@_;
1.790 albertel 11088: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11089: if ($courseid) {
1.620 albertel 11090: return $env{"course.$courseid.rndseed"};
1.503 albertel 11091: }
11092: return &latest_rnd_algorithm_id();
11093: }
11094:
1.562 albertel 11095: sub validCODE {
11096: my ($CODE)=@_;
11097: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11098: return 0;
11099: }
11100:
1.491 albertel 11101: sub getCODE {
1.620 albertel 11102: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11103: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11104: defined($Apache::lonhomework::parsing_a_task) ) &&
11105: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11106: return $Apache::lonhomework::history{'resource.CODE'};
11107: }
11108: return undef;
11109: }
1.1133 foxr 11110: #
11111: # Determines the random seed for a specific context:
11112: #
11113: # parameters:
11114: # symb - in course context the symb for the seed.
11115: # course_id - The course id of the form domain_coursenum.
11116: # domain - Domain for the user.
11117: # course - Course for the user.
11118: # cenv - environment of the course.
11119: #
11120: # NOTE:
11121: # All parameters are picked out of the environment if missing
11122: # or not defined.
11123: # If a symb cannot be determined the current time is used instead.
11124: #
11125: # For a given well defined symb, courside, domain, username,
11126: # and course environment, the seed is reproducible.
11127: #
1.31 www 11128: sub rndseed {
1.1133 foxr 11129: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11130: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11131: if (!defined($symb)) {
1.366 albertel 11132: unless ($symb=$wsymb) { return time; }
11133: }
1.1146 foxr 11134: if (!defined $courseid) {
11135: $courseid=$wcourseid;
11136: }
11137: if (!defined $domain) { $domain=$wdomain; }
11138: if (!defined $username) { $username=$wusername }
1.1133 foxr 11139:
11140: my $which;
11141: if (defined($cenv->{'rndseed'})) {
11142: $which = $cenv->{'rndseed'};
11143: } else {
11144: $which =&get_rand_alg($courseid);
11145: }
1.491 albertel 11146: if (defined(&getCODE())) {
1.675 albertel 11147: if ($which eq '64bit5') {
11148: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11149: } elsif ($which eq '64bit4') {
1.575 albertel 11150: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11151: } else {
11152: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11153: }
1.675 albertel 11154: } elsif ($which eq '64bit5') {
11155: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11156: } elsif ($which eq '64bit4') {
11157: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11158: } elsif ($which eq '64bit3') {
11159: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11160: } elsif ($which eq '64bit2') {
11161: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11162: } elsif ($which eq '64bit') {
11163: return &rndseed_64bit($symb,$courseid,$domain,$username);
11164: }
11165: return &rndseed_32bit($symb,$courseid,$domain,$username);
11166: }
11167:
11168: sub rndseed_32bit {
11169: my ($symb,$courseid,$domain,$username)=@_;
11170: {
11171: use integer;
11172: my $symbchck=unpack("%32C*",$symb) << 27;
11173: my $symbseed=numval($symb) << 22;
11174: my $namechck=unpack("%32C*",$username) << 17;
11175: my $nameseed=numval($username) << 12;
11176: my $domainseed=unpack("%32C*",$domain) << 7;
11177: my $courseseed=unpack("%32C*",$courseid);
11178: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11179: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11180: #&logthis("rndseed :$num:$symb");
1.564 albertel 11181: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11182: return $num;
11183: }
11184: }
11185:
11186: sub rndseed_64bit {
11187: my ($symb,$courseid,$domain,$username)=@_;
11188: {
11189: use integer;
11190: my $symbchck=unpack("%32S*",$symb) << 21;
11191: my $symbseed=numval($symb) << 10;
11192: my $namechck=unpack("%32S*",$username);
11193:
11194: my $nameseed=numval($username) << 21;
11195: my $domainseed=unpack("%32S*",$domain) << 10;
11196: my $courseseed=unpack("%32S*",$courseid);
11197:
11198: my $num1=$symbchck+$symbseed+$namechck;
11199: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11200: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11201: #&logthis("rndseed :$num:$symb");
1.564 albertel 11202: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11203: return "$num1,$num2";
1.155 albertel 11204: }
1.366 albertel 11205: }
11206:
1.443 albertel 11207: sub rndseed_64bit2 {
11208: my ($symb,$courseid,$domain,$username)=@_;
11209: {
11210: use integer;
11211: # strings need to be an even # of cahracters long, it it is odd the
11212: # last characters gets thrown away
11213: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11214: my $symbseed=numval($symb) << 10;
11215: my $namechck=unpack("%32S*",$username.' ');
11216:
11217: my $nameseed=numval($username) << 21;
1.501 albertel 11218: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11219: my $courseseed=unpack("%32S*",$courseid.' ');
11220:
11221: my $num1=$symbchck+$symbseed+$namechck;
11222: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11223: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11224: #&logthis("rndseed :$num:$symb");
1.803 albertel 11225: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11226: return "$num1,$num2";
11227: }
11228: }
11229:
11230: sub rndseed_64bit3 {
11231: my ($symb,$courseid,$domain,$username)=@_;
11232: {
11233: use integer;
11234: # strings need to be an even # of cahracters long, it it is odd the
11235: # last characters gets thrown away
11236: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11237: my $symbseed=numval2($symb) << 10;
11238: my $namechck=unpack("%32S*",$username.' ');
11239:
11240: my $nameseed=numval2($username) << 21;
1.443 albertel 11241: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11242: my $courseseed=unpack("%32S*",$courseid.' ');
11243:
11244: my $num1=$symbchck+$symbseed+$namechck;
11245: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11246: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11247: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11248: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11249:
1.503 albertel 11250: return "$num1:$num2";
1.443 albertel 11251: }
11252: }
11253:
1.575 albertel 11254: sub rndseed_64bit4 {
11255: my ($symb,$courseid,$domain,$username)=@_;
11256: {
11257: use integer;
11258: # strings need to be an even # of cahracters long, it it is odd the
11259: # last characters gets thrown away
11260: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11261: my $symbseed=numval3($symb) << 10;
11262: my $namechck=unpack("%32S*",$username.' ');
11263:
11264: my $nameseed=numval3($username) << 21;
11265: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11266: my $courseseed=unpack("%32S*",$courseid.' ');
11267:
11268: my $num1=$symbchck+$symbseed+$namechck;
11269: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11270: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11271: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11272: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11273:
1.575 albertel 11274: return "$num1:$num2";
11275: }
11276: }
11277:
1.675 albertel 11278: sub rndseed_64bit5 {
11279: my ($symb,$courseid,$domain,$username)=@_;
11280: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11281: return "$num1:$num2";
11282: }
11283:
1.366 albertel 11284: sub rndseed_CODE_64bit {
11285: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11286: {
1.366 albertel 11287: use integer;
1.443 albertel 11288: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11289: my $symbseed=numval2($symb);
1.491 albertel 11290: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11291: my $CODEseed=numval(&getCODE());
1.443 albertel 11292: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11293: my $num1=$symbseed+$CODEchck;
11294: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11295: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11296: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11297: if ($_64bit) { $num1=(($num1<<32)>>32); }
11298: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11299: return "$num1:$num2";
1.366 albertel 11300: }
11301: }
11302:
1.575 albertel 11303: sub rndseed_CODE_64bit4 {
11304: my ($symb,$courseid,$domain,$username)=@_;
11305: {
11306: use integer;
11307: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11308: my $symbseed=numval3($symb);
11309: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11310: my $CODEseed=numval3(&getCODE());
11311: my $courseseed=unpack("%32S*",$courseid.' ');
11312: my $num1=$symbseed+$CODEchck;
11313: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11314: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11315: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11316: if ($_64bit) { $num1=(($num1<<32)>>32); }
11317: if ($_64bit) { $num2=(($num2<<32)>>32); }
11318: return "$num1:$num2";
11319: }
11320: }
11321:
1.675 albertel 11322: sub rndseed_CODE_64bit5 {
11323: my ($symb,$courseid,$domain,$username)=@_;
11324: my $code = &getCODE();
11325: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11326: return "$num1:$num2";
11327: }
11328:
1.366 albertel 11329: sub setup_random_from_rndseed {
11330: my ($rndseed)=@_;
1.503 albertel 11331: if ($rndseed =~/([,:])/) {
11332: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11333: &Math::Random::random_set_seed(abs($num1),abs($num2));
11334: } else {
11335: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11336: }
1.36 albertel 11337: }
11338:
1.474 albertel 11339: sub latest_receipt_algorithm_id {
1.835 albertel 11340: return 'receipt3';
1.474 albertel 11341: }
11342:
1.480 www 11343: sub recunique {
11344: my $fucourseid=shift;
11345: my $unique;
1.835 albertel 11346: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11347: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11348: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11349: } else {
11350: $unique=$perlvar{'lonReceipt'};
11351: }
11352: return unpack("%32C*",$unique);
11353: }
11354:
11355: sub recprefix {
11356: my $fucourseid=shift;
11357: my $prefix;
1.835 albertel 11358: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11359: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11360: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11361: } else {
11362: $prefix=$perlvar{'lonHostID'};
11363: }
11364: return unpack("%32C*",$prefix);
11365: }
11366:
1.76 www 11367: sub ireceipt {
1.474 albertel 11368: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11369:
11370: my $return =&recprefix($fucourseid).'-';
11371:
11372: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11373: $env{'request.state'} eq 'construct') {
11374: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11375: return $return;
11376: }
11377:
1.76 www 11378: my $cuname=unpack("%32C*",$funame);
11379: my $cudom=unpack("%32C*",$fudom);
11380: my $cucourseid=unpack("%32C*",$fucourseid);
11381: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11382: my $cunique=&recunique($fucourseid);
1.474 albertel 11383: my $cpart=unpack("%32S*",$part);
1.835 albertel 11384: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11385:
1.790 albertel 11386: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11387:
11388: $return.= ($cunique%$cuname+
11389: $cunique%$cudom+
11390: $cusymb%$cuname+
11391: $cusymb%$cudom+
11392: $cucourseid%$cuname+
11393: $cucourseid%$cudom+
11394: $cpart%$cuname+
11395: $cpart%$cudom);
11396: } else {
11397: $return.= ($cunique%$cuname+
11398: $cunique%$cudom+
11399: $cusymb%$cuname+
11400: $cusymb%$cudom+
11401: $cucourseid%$cuname+
11402: $cucourseid%$cudom);
11403: }
11404: return $return;
1.76 www 11405: }
11406:
11407: sub receipt {
1.474 albertel 11408: my ($part)=@_;
1.790 albertel 11409: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11410: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11411: }
1.260 ng 11412:
1.790 albertel 11413: sub whichuser {
11414: my ($passedsymb)=@_;
11415: my ($symb,$courseid,$domain,$name,$publicuser);
11416: if (defined($env{'form.grade_symb'})) {
11417: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11418: my $allowed=&allowed('vgr',$tmp_courseid);
11419: if (!$allowed &&
11420: exists($env{'request.course.sec'}) &&
11421: $env{'request.course.sec'} !~ /^\s*$/) {
11422: $allowed=&allowed('vgr',$tmp_courseid.
11423: '/'.$env{'request.course.sec'});
11424: }
11425: if ($allowed) {
11426: ($symb)=&get_env_multiple('form.grade_symb');
11427: $courseid=$tmp_courseid;
11428: ($domain)=&get_env_multiple('form.grade_domain');
11429: ($name)=&get_env_multiple('form.grade_username');
11430: return ($symb,$courseid,$domain,$name,$publicuser);
11431: }
11432: }
11433: if (!$passedsymb) {
11434: $symb=&symbread();
11435: } else {
11436: $symb=$passedsymb;
11437: }
11438: $courseid=$env{'request.course.id'};
11439: $domain=$env{'user.domain'};
11440: $name=$env{'user.name'};
11441: if ($name eq 'public' && $domain eq 'public') {
11442: if (!defined($env{'form.username'})) {
11443: $env{'form.username'}.=time.rand(10000000);
11444: }
11445: $name.=$env{'form.username'};
11446: }
11447: return ($symb,$courseid,$domain,$name,$publicuser);
11448:
11449: }
11450:
1.36 albertel 11451: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11452: # returns either the contents of the file or
11453: # -1 if the file doesn't exist
1.481 raeburn 11454: #
11455: # if the target is a file that was uploaded via DOCS,
11456: # a check will be made to see if a current copy exists on the local server,
11457: # if it does this will be served, otherwise a copy will be retrieved from
11458: # the home server for the course and stored in /home/httpd/html/userfiles on
11459: # the local server.
1.472 albertel 11460:
1.36 albertel 11461: sub getfile {
1.538 albertel 11462: my ($file) = @_;
1.609 banghart 11463: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11464: &repcopy($file);
11465: return &readfile($file);
11466: }
11467:
11468: sub repcopy_userfile {
11469: my ($file)=@_;
1.1142 raeburn 11470: my $londocroot = $perlvar{'lonDocRoot'};
11471: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11472: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11473: my ($cdom,$cnum,$filename) =
1.811 albertel 11474: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11475: my $uri="/uploaded/$cdom/$cnum/$filename";
11476: if (-e "$file") {
1.828 www 11477: # we already have a local copy, check it out
1.538 albertel 11478: my @fileinfo = stat($file);
1.828 www 11479: my $rtncode;
11480: my $info;
1.538 albertel 11481: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11482: if ($lwpresp ne 'ok') {
1.828 www 11483: # there is no such file anymore, even though we had a local copy
1.482 albertel 11484: if ($rtncode eq '404') {
1.538 albertel 11485: unlink($file);
1.482 albertel 11486: }
11487: return -1;
11488: }
11489: if ($info < $fileinfo[9]) {
1.828 www 11490: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11491: return 'ok';
1.828 www 11492: } else {
11493: # the file is outdated, get rid of it
11494: unlink($file);
1.482 albertel 11495: }
1.828 www 11496: }
11497: # one way or the other, at this point, we don't have the file
11498: # construct the correct path for the file
11499: my @parts = ($cdom,$cnum);
11500: if ($filename =~ m|^(.+)/[^/]+$|) {
11501: push @parts, split(/\//,$1);
11502: }
11503: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11504: foreach my $part (@parts) {
11505: $path .= '/'.$part;
11506: if (!-e $path) {
11507: mkdir($path,0770);
1.482 albertel 11508: }
11509: }
1.828 www 11510: # now the path exists for sure
11511: # get a user agent
11512: my $ua=new LWP::UserAgent;
11513: my $transferfile=$file.'.in.transfer';
11514: # FIXME: this should flock
11515: if (-e $transferfile) { return 'ok'; }
11516: my $request;
11517: $uri=~s/^\///;
1.980 raeburn 11518: my $homeserver = &homeserver($cnum,$cdom);
11519: my $protocol = $protocol{$homeserver};
11520: $protocol = 'http' if ($protocol ne 'https');
11521: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11522: my $response=$ua->request($request,$transferfile);
11523: # did it work?
11524: if ($response->is_error()) {
11525: unlink($transferfile);
11526: &logthis("Userfile repcopy failed for $uri");
11527: return -1;
11528: }
11529: # worked, rename the transfer file
11530: rename($transferfile,$file);
1.607 raeburn 11531: return 'ok';
1.481 raeburn 11532: }
11533:
1.517 albertel 11534: sub tokenwrapper {
11535: my $uri=shift;
1.980 raeburn 11536: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11537: $uri=~s|^/||;
1.620 albertel 11538: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11539: my $token=$1;
1.552 albertel 11540: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11541: if ($udom && $uname && $file) {
11542: $file=~s|(\?\.*)*$||;
1.949 raeburn 11543: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11544: my $homeserver = &homeserver($uname,$udom);
11545: my $protocol = $protocol{$homeserver};
11546: $protocol = 'http' if ($protocol ne 'https');
11547: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11548: (($uri=~/\?/)?'&':'?').'token='.$token.
11549: '&tokenissued='.$perlvar{'lonHostID'};
11550: } else {
11551: return '/adm/notfound.html';
11552: }
11553: }
11554:
1.828 www 11555: # call with reqtype HEAD: get last modification time
11556: # call with reqtype GET: get the file contents
11557: # Do not call this with reqtype GET for large files! It loads everything into memory
11558: #
1.481 raeburn 11559: sub getuploaded {
11560: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11561: $uri=~s/^\///;
1.980 raeburn 11562: my $homeserver = &homeserver($cnum,$cdom);
11563: my $protocol = $protocol{$homeserver};
11564: $protocol = 'http' if ($protocol ne 'https');
11565: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11566: my $ua=new LWP::UserAgent;
11567: my $request=new HTTP::Request($reqtype,$uri);
11568: my $response=$ua->request($request);
11569: $$rtncode = $response->code;
1.482 albertel 11570: if (! $response->is_success()) {
11571: return 'failed';
11572: }
11573: if ($reqtype eq 'HEAD') {
1.486 www 11574: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11575: } elsif ($reqtype eq 'GET') {
11576: $$info = $response->content;
1.472 albertel 11577: }
1.482 albertel 11578: return 'ok';
1.36 albertel 11579: }
11580:
1.481 raeburn 11581: sub readfile {
11582: my $file = shift;
11583: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11584: my $fh;
11585: open($fh,"<$file");
11586: my $a='';
1.800 albertel 11587: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11588: return $a;
11589: }
11590:
1.36 albertel 11591: sub filelocation {
1.590 banghart 11592: my ($dir,$file) = @_;
11593: my $location;
11594: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11595:
11596: if ($file =~ m-^/adm/-) {
11597: $file=~s-^/adm/wrapper/-/-;
11598: $file=~s-^/adm/coursedocs/showdoc/-/-;
11599: }
1.882 albertel 11600:
1.1139 www 11601: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11602: $location = $file;
1.609 banghart 11603: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11604: my ($udom,$uname,$filename)=
1.811 albertel 11605: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11606: my $home=&homeserver($uname,$udom);
11607: my $is_me=0;
11608: my @ids=¤t_machine_ids();
11609: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11610: if ($is_me) {
1.1117 foxr 11611: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11612: } else {
11613: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11614: $udom.'/'.$uname.'/'.$filename;
11615: }
1.882 albertel 11616: } elsif ($file =~ m-^/adm/-) {
11617: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11618: } else {
11619: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11620: $file=~s:^/(res|priv)/:/:;
11621: my $space=$1;
1.590 banghart 11622: if ( !( $file =~ m:^/:) ) {
11623: $location = $dir. '/'.$file;
11624: } else {
1.1142 raeburn 11625: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11626: }
1.59 albertel 11627: }
1.590 banghart 11628: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11629: while ($location=~m{/\.\./}) {
11630: if ($location =~ m{/[^/]+/\.\./}) {
11631: $location=~ s{/[^/]+/\.\./}{/}g;
11632: } else {
11633: $location=~ s{/\.\./}{/}g;
11634: }
11635: } #remove dir/..
1.590 banghart 11636: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11637: return $location;
1.46 www 11638: }
1.36 albertel 11639:
1.46 www 11640: sub hreflocation {
11641: my ($dir,$file)=@_;
1.980 raeburn 11642: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11643: $file=filelocation($dir,$file);
1.700 albertel 11644: } elsif ($file=~m-^/adm/-) {
11645: $file=~s-^/adm/wrapper/-/-;
11646: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11647: }
11648: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11649: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11650: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11651: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11652: {/uploaded/$1/$2/}x;
1.46 www 11653: }
1.913 albertel 11654: if ($file=~ m{^/userfiles/}) {
11655: $file =~ s{^/userfiles/}{/uploaded/};
11656: }
1.462 albertel 11657: return $file;
1.465 albertel 11658: }
11659:
1.1139 www 11660:
11661:
11662:
11663:
1.465 albertel 11664: sub current_machine_domains {
1.853 albertel 11665: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11666: }
11667:
11668: sub machine_domains {
11669: my ($hostname) = @_;
1.465 albertel 11670: my @domains;
1.838 albertel 11671: my %hostname = &all_hostnames();
1.465 albertel 11672: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11673: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11674: if ($hostname eq $name) {
1.844 albertel 11675: push(@domains,&host_domain($id));
1.465 albertel 11676: }
11677: }
11678: return @domains;
11679: }
11680:
11681: sub current_machine_ids {
1.853 albertel 11682: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11683: }
11684:
11685: sub machine_ids {
11686: my ($hostname) = @_;
11687: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11688: my @ids;
1.888 albertel 11689: my %name_to_host = &all_names();
1.889 albertel 11690: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11691: return @{ $name_to_host{$hostname} };
11692: }
11693: return;
1.31 www 11694: }
11695:
1.824 raeburn 11696: sub additional_machine_domains {
11697: my @domains;
11698: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11699: while( my $line = <$fh>) {
11700: $line =~ s/\s//g;
11701: push(@domains,$line);
11702: }
11703: return @domains;
11704: }
11705:
11706: sub default_login_domain {
11707: my $domain = $perlvar{'lonDefDomain'};
11708: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11709: foreach my $posdom (¤t_machine_domains(),
11710: &additional_machine_domains()) {
11711: if (lc($posdom) eq lc($testdomain)) {
11712: $domain=$posdom;
11713: last;
11714: }
11715: }
11716: return $domain;
11717: }
11718:
1.31 www 11719: # ------------------------------------------------------------- Declutters URLs
11720:
11721: sub declutter {
11722: my $thisfn=shift;
1.569 albertel 11723: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11724: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11725: $thisfn=~s/^\///;
1.697 albertel 11726: $thisfn=~s|^adm/wrapper/||;
11727: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11728: $thisfn=~s/^res\///;
1.1172 bisitz 11729: $thisfn=~s/^priv\///;
1.1032 raeburn 11730: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11731: $thisfn=~s/\?.+$//;
11732: }
1.268 www 11733: return $thisfn;
11734: }
11735:
11736: # ------------------------------------------------------------- Clutter up URLs
11737:
11738: sub clutter {
11739: my $thisfn='/'.&declutter(shift);
1.887 albertel 11740: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11741: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11742: $thisfn='/res'.$thisfn;
11743: }
1.1031 raeburn 11744: if ($thisfn !~m|^/adm|) {
11745: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11746: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11747: } else {
11748: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11749: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11750: if ($embstyle eq 'ssi'
11751: || ($embstyle eq 'hdn')
11752: || ($embstyle eq 'rat')
11753: || ($embstyle eq 'prv')
11754: || ($embstyle eq 'ign')) {
11755: #do nothing with these
11756: } elsif (($embstyle eq 'img')
1.695 albertel 11757: || ($embstyle eq 'emb')
11758: || ($embstyle eq 'wrp')) {
11759: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11760: } elsif ($embstyle eq 'unk'
11761: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11762: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11763: } else {
1.718 www 11764: # &logthis("Got a blank emb style");
1.695 albertel 11765: }
1.694 albertel 11766: }
11767: }
1.31 www 11768: return $thisfn;
1.12 www 11769: }
11770:
1.787 albertel 11771: sub clutter_with_no_wrapper {
11772: my $uri = &clutter(shift);
11773: if ($uri =~ m-^/adm/-) {
11774: $uri =~ s-^/adm/wrapper/-/-;
11775: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11776: }
11777: return $uri;
11778: }
11779:
1.557 albertel 11780: sub freeze_escape {
11781: my ($value)=@_;
11782: if (ref($value)) {
11783: $value=&nfreeze($value);
11784: return '__FROZEN__'.&escape($value);
11785: }
11786: return &escape($value);
11787: }
11788:
1.11 www 11789:
1.557 albertel 11790: sub thaw_unescape {
11791: my ($value)=@_;
11792: if ($value =~ /^__FROZEN__/) {
11793: substr($value,0,10,undef);
11794: $value=&unescape($value);
11795: return &thaw($value);
11796: }
11797: return &unescape($value);
11798: }
11799:
1.436 albertel 11800: sub correct_line_ends {
11801: my ($result)=@_;
11802: $$result =~s/\r\n/\n/mg;
11803: $$result =~s/\r/\n/mg;
1.415 albertel 11804: }
1.1 albertel 11805: # ================================================================ Main Program
11806:
1.184 www 11807: sub goodbye {
1.204 albertel 11808: &logthis("Starting Shut down");
1.443 albertel 11809: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11810: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11811: #converted
1.599 albertel 11812: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11813: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11814: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11815: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11816: #1.1 only
1.870 albertel 11817: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11818: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11819: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11820: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11821: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11822: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11823: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11824: &flushcourselogs();
11825: &logthis("Shutting down");
11826: }
11827:
1.852 albertel 11828: sub get_dns {
1.1172.2.17 raeburn 11829: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11830: if (!$ignore_cache) {
11831: my ($content,$cached)=
11832: &Apache::lonnet::is_cached_new('dns',$url);
11833: if ($cached) {
1.1172.2.17 raeburn 11834: &$func($content,$hashref);
1.869 albertel 11835: return;
11836: }
11837: }
11838:
11839: my %alldns;
1.852 albertel 11840: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11841: foreach my $dns (<$config>) {
11842: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11843: my $line = $1;
11844: my ($host,$protocol) = split(/:/,$line);
11845: if ($protocol ne 'https') {
11846: $protocol = 'http';
11847: }
11848: $alldns{$host} = $protocol;
1.869 albertel 11849: }
11850: while (%alldns) {
11851: my ($dns) = keys(%alldns);
1.852 albertel 11852: my $ua=new LWP::UserAgent;
1.1134 raeburn 11853: $ua->timeout(30);
1.979 raeburn 11854: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11855: my $response=$ua->request($request);
1.979 raeburn 11856: delete($alldns{$dns});
1.852 albertel 11857: next if ($response->is_error());
11858: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11859: unless ($nocache) {
1.1172.2.23 raeburn 11860: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11861: }
11862: &$func(\@content,$hashref);
1.869 albertel 11863: return;
1.852 albertel 11864: }
11865: close($config);
1.871 albertel 11866: my $which = (split('/',$url))[3];
11867: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11868: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11869: my @content = <$config>;
1.1172.2.17 raeburn 11870: &$func(\@content,$hashref);
11871: return;
11872: }
11873:
11874: # ------------------------------------------------------Get DNS checksums file
11875: sub parse_dns_checksums_tab {
11876: my ($lines,$hashref) = @_;
11877: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11878: my $loncaparev = &get_server_loncaparev($machine_dom);
11879: my ($release,$timestamp) = split(/\-/,$loncaparev);
11880: my (%chksum,%revnum);
11881: if (ref($lines) eq 'ARRAY') {
11882: chomp(@{$lines});
1.1172.2.34 raeburn 11883: my $version = shift(@{$lines});
11884: if ($version eq $release) {
1.1172.2.17 raeburn 11885: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11886: my ($file,$version,$shasum) = split(/,/,$line);
11887: $chksum{$file} = $shasum;
11888: $revnum{$file} = $version;
1.1172.2.17 raeburn 11889: }
11890: if (ref($hashref) eq 'HASH') {
11891: %{$hashref} = (
11892: sums => \%chksum,
11893: versions => \%revnum,
11894: );
11895: }
11896: }
11897: }
1.869 albertel 11898: return;
1.852 albertel 11899: }
1.1172.2.17 raeburn 11900:
11901: sub fetch_dns_checksums {
11902: my %checksums;
1.1172.2.34 raeburn 11903: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11904: my $loncaparev = &get_server_loncaparev($machine_dom);
11905: my ($release,$timestamp) = split(/\-/,$loncaparev);
11906: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11907: \%checksums);
11908: return \%checksums;
11909: }
11910:
1.327 albertel 11911: # ------------------------------------------------------------ Read domain file
11912: {
1.852 albertel 11913: my $loaded;
1.846 albertel 11914: my %domain;
11915:
1.852 albertel 11916: sub parse_domain_tab {
11917: my ($lines) = @_;
11918: foreach my $line (@$lines) {
11919: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11920:
1.846 albertel 11921: chomp($line);
1.852 albertel 11922: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11923: my %this_domain;
11924: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11925: 'lang_def', 'city', 'longi', 'lati',
11926: 'primary') {
11927: $this_domain{$field} = shift(@elements);
11928: }
11929: $domain{$name} = \%this_domain;
1.852 albertel 11930: }
11931: }
1.864 albertel 11932:
11933: sub reset_domain_info {
11934: undef($loaded);
11935: undef(%domain);
11936: }
11937:
1.852 albertel 11938: sub load_domain_tab {
1.869 albertel 11939: my ($ignore_cache) = @_;
11940: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11941: my $fh;
11942: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11943: my @lines = <$fh>;
11944: &parse_domain_tab(\@lines);
1.448 albertel 11945: }
1.852 albertel 11946: close($fh);
11947: $loaded = 1;
1.327 albertel 11948: }
1.846 albertel 11949:
11950: sub domain {
1.852 albertel 11951: &load_domain_tab() if (!$loaded);
11952:
1.846 albertel 11953: my ($name,$what) = @_;
11954: return if ( !exists($domain{$name}) );
11955:
11956: if (!$what) {
11957: return $domain{$name}{'description'};
11958: }
11959: return $domain{$name}{$what};
11960: }
1.974 raeburn 11961:
11962: sub domain_info {
11963: &load_domain_tab() if (!$loaded);
11964: return %domain;
11965: }
11966:
1.327 albertel 11967: }
11968:
11969:
1.1 albertel 11970: # ------------------------------------------------------------- Read hosts file
11971: {
1.838 albertel 11972: my %hostname;
1.844 albertel 11973: my %hostdom;
1.845 albertel 11974: my %libserv;
1.852 albertel 11975: my $loaded;
1.888 albertel 11976: my %name_to_host;
1.1074 raeburn 11977: my %internetdom;
1.1107 raeburn 11978: my %LC_dns_serv;
1.852 albertel 11979:
11980: sub parse_hosts_tab {
11981: my ($file) = @_;
11982: foreach my $configline (@$file) {
11983: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11984: chomp($configline);
11985: if ($configline =~ /^\^/) {
11986: if ($configline =~ /^\^([\w.\-]+)/) {
11987: $LC_dns_serv{$1} = 1;
11988: }
11989: next;
11990: }
1.1074 raeburn 11991: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11992: $name=~s/\s//g;
11993: if ($id && $domain && $role && $name) {
11994: $hostname{$id}=$name;
1.888 albertel 11995: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11996: $hostdom{$id}=$domain;
11997: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11998: if (defined($protocol)) {
11999: if ($protocol eq 'https') {
12000: $protocol{$id} = $protocol;
12001: } else {
12002: $protocol{$id} = 'http';
12003: }
1.968 raeburn 12004: } else {
1.969 raeburn 12005: $protocol{$id} = 'http';
1.968 raeburn 12006: }
1.1074 raeburn 12007: if (defined($intdom)) {
12008: $internetdom{$id} = $intdom;
12009: }
1.852 albertel 12010: }
12011: }
12012: }
1.864 albertel 12013:
12014: sub reset_hosts_info {
1.897 albertel 12015: &purge_remembered();
1.864 albertel 12016: &reset_domain_info();
12017: &reset_hosts_ip_info();
1.892 albertel 12018: undef(%name_to_host);
1.864 albertel 12019: undef(%hostname);
12020: undef(%hostdom);
12021: undef(%libserv);
12022: undef($loaded);
12023: }
1.1 albertel 12024:
1.852 albertel 12025: sub load_hosts_tab {
1.869 albertel 12026: my ($ignore_cache) = @_;
12027: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12028: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12029: my @config = <$config>;
12030: &parse_hosts_tab(\@config);
12031: close($config);
12032: $loaded=1;
1.1 albertel 12033: }
1.852 albertel 12034:
1.838 albertel 12035: sub hostname {
1.852 albertel 12036: &load_hosts_tab() if (!$loaded);
12037:
1.838 albertel 12038: my ($lonid) = @_;
12039: return $hostname{$lonid};
12040: }
1.845 albertel 12041:
1.838 albertel 12042: sub all_hostnames {
1.852 albertel 12043: &load_hosts_tab() if (!$loaded);
12044:
1.838 albertel 12045: return %hostname;
12046: }
1.845 albertel 12047:
1.888 albertel 12048: sub all_names {
12049: &load_hosts_tab() if (!$loaded);
12050:
12051: return %name_to_host;
12052: }
12053:
1.974 raeburn 12054: sub all_host_domain {
12055: &load_hosts_tab() if (!$loaded);
12056: return %hostdom;
12057: }
12058:
1.845 albertel 12059: sub is_library {
1.852 albertel 12060: &load_hosts_tab() if (!$loaded);
12061:
1.845 albertel 12062: return exists($libserv{$_[0]});
12063: }
12064:
12065: sub all_library {
1.852 albertel 12066: &load_hosts_tab() if (!$loaded);
12067:
1.845 albertel 12068: return %libserv;
12069: }
12070:
1.1062 droeschl 12071: sub unique_library {
12072: #2x reverse removes all hostnames that appear more than once
12073: my %unique = reverse &all_library();
12074: return reverse %unique;
12075: }
12076:
1.841 albertel 12077: sub get_servers {
1.852 albertel 12078: &load_hosts_tab() if (!$loaded);
12079:
1.841 albertel 12080: my ($domain,$type) = @_;
12081: my %possible_hosts = ($type eq 'library') ? %libserv
12082: : %hostname;
12083: my %result;
1.842 albertel 12084: if (ref($domain) eq 'ARRAY') {
12085: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12086: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12087: $result{$host} = $hostname;
12088: }
12089: }
12090: } else {
12091: while ( my ($host,$hostname) = each(%possible_hosts)) {
12092: if ($hostdom{$host} eq $domain) {
12093: $result{$host} = $hostname;
12094: }
1.841 albertel 12095: }
12096: }
12097: return %result;
12098: }
1.845 albertel 12099:
1.1062 droeschl 12100: sub get_unique_servers {
12101: my %unique = reverse &get_servers(@_);
12102: return reverse %unique;
12103: }
12104:
1.844 albertel 12105: sub host_domain {
1.852 albertel 12106: &load_hosts_tab() if (!$loaded);
12107:
1.844 albertel 12108: my ($lonid) = @_;
12109: return $hostdom{$lonid};
12110: }
12111:
1.841 albertel 12112: sub all_domains {
1.852 albertel 12113: &load_hosts_tab() if (!$loaded);
12114:
1.841 albertel 12115: my %seen;
12116: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12117: return @uniq;
12118: }
1.1074 raeburn 12119:
12120: sub internet_dom {
12121: &load_hosts_tab() if (!$loaded);
12122:
12123: my ($lonid) = @_;
12124: return $internetdom{$lonid};
12125: }
1.1107 raeburn 12126:
12127: sub is_LC_dns {
12128: &load_hosts_tab() if (!$loaded);
12129:
12130: my ($hostname) = @_;
12131: return exists($LC_dns_serv{$hostname});
12132: }
12133:
1.1 albertel 12134: }
12135:
1.847 albertel 12136: {
12137: my %iphost;
1.856 albertel 12138: my %name_to_ip;
12139: my %lonid_to_ip;
1.869 albertel 12140:
1.847 albertel 12141: sub get_hosts_from_ip {
12142: my ($ip) = @_;
12143: my %iphosts = &get_iphost();
12144: if (ref($iphosts{$ip})) {
12145: return @{$iphosts{$ip}};
12146: }
12147: return;
1.839 albertel 12148: }
1.864 albertel 12149:
12150: sub reset_hosts_ip_info {
12151: undef(%iphost);
12152: undef(%name_to_ip);
12153: undef(%lonid_to_ip);
12154: }
1.856 albertel 12155:
12156: sub get_host_ip {
12157: my ($lonid) = @_;
12158: if (exists($lonid_to_ip{$lonid})) {
12159: return $lonid_to_ip{$lonid};
12160: }
12161: my $name=&hostname($lonid);
12162: my $ip = gethostbyname($name);
12163: return if (!$ip || length($ip) ne 4);
12164: $ip=inet_ntoa($ip);
12165: $name_to_ip{$name} = $ip;
12166: $lonid_to_ip{$lonid} = $ip;
12167: return $ip;
12168: }
1.847 albertel 12169:
12170: sub get_iphost {
1.869 albertel 12171: my ($ignore_cache) = @_;
1.894 albertel 12172:
1.869 albertel 12173: if (!$ignore_cache) {
12174: if (%iphost) {
12175: return %iphost;
12176: }
12177: my ($ip_info,$cached)=
12178: &Apache::lonnet::is_cached_new('iphost','iphost');
12179: if ($cached) {
12180: %iphost = %{$ip_info->[0]};
12181: %name_to_ip = %{$ip_info->[1]};
12182: %lonid_to_ip = %{$ip_info->[2]};
12183: return %iphost;
12184: }
12185: }
1.894 albertel 12186:
12187: # get yesterday's info for fallback
12188: my %old_name_to_ip;
12189: my ($ip_info,$cached)=
12190: &Apache::lonnet::is_cached_new('iphost','iphost');
12191: if ($cached) {
12192: %old_name_to_ip = %{$ip_info->[1]};
12193: }
12194:
1.888 albertel 12195: my %name_to_host = &all_names();
12196: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12197: my $ip;
12198: if (!exists($name_to_ip{$name})) {
12199: $ip = gethostbyname($name);
12200: if (!$ip || length($ip) ne 4) {
1.894 albertel 12201: if (defined($old_name_to_ip{$name})) {
12202: $ip = $old_name_to_ip{$name};
12203: &logthis("Can't find $name defaulting to old $ip");
12204: } else {
12205: &logthis("Name $name no IP found");
12206: next;
12207: }
12208: } else {
12209: $ip=inet_ntoa($ip);
1.847 albertel 12210: }
12211: $name_to_ip{$name} = $ip;
12212: } else {
12213: $ip = $name_to_ip{$name};
1.653 albertel 12214: }
1.888 albertel 12215: foreach my $id (@{ $name_to_host{$name} }) {
12216: $lonid_to_ip{$id} = $ip;
12217: }
12218: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12219: }
1.1172.2.23 raeburn 12220: &do_cache_new('iphost','iphost',
12221: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12222: 48*60*60);
1.869 albertel 12223:
1.847 albertel 12224: return %iphost;
1.598 albertel 12225: }
12226:
1.992 raeburn 12227: #
12228: # Given a DNS returns the loncapa host name for that DNS
12229: #
12230: sub host_from_dns {
12231: my ($dns) = @_;
12232: my @hosts;
12233: my $ip;
12234:
1.993 raeburn 12235: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12236: $ip = $name_to_ip{$dns};
12237: }
12238: if (!$ip) {
12239: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12240: if (length($ip) == 4) {
12241: $ip = &IO::Socket::inet_ntoa($ip);
12242: }
12243: }
12244: if ($ip) {
12245: @hosts = get_hosts_from_ip($ip);
12246: return $hosts[0];
12247: }
12248: return undef;
1.986 foxr 12249: }
1.992 raeburn 12250:
1.1074 raeburn 12251: sub get_internet_names {
12252: my ($lonid) = @_;
12253: return if ($lonid eq '');
12254: my ($idnref,$cached)=
12255: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12256: if ($cached) {
12257: return $idnref;
12258: }
12259: my $ip = &get_host_ip($lonid);
12260: my @hosts = &get_hosts_from_ip($ip);
12261: my %iphost = &get_iphost();
12262: my (@idns,%seen);
12263: foreach my $id (@hosts) {
12264: my $dom = &host_domain($id);
12265: my $prim_id = &domain($dom,'primary');
12266: my $prim_ip = &get_host_ip($prim_id);
12267: next if ($seen{$prim_ip});
12268: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12269: foreach my $id (@{$iphost{$prim_ip}}) {
12270: my $intdom = &internet_dom($id);
12271: unless (grep(/^\Q$intdom\E$/,@idns)) {
12272: push(@idns,$intdom);
12273: }
12274: }
12275: }
12276: $seen{$prim_ip} = 1;
12277: }
1.1172.2.23 raeburn 12278: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12279: }
12280:
1.986 foxr 12281: }
12282:
1.1079 raeburn 12283: sub all_loncaparevs {
1.1172.2.39 raeburn 12284: 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 12285: }
12286:
1.1172.2.27 raeburn 12287: # ------------------------------------------------------- Read loncaparev table
12288: {
12289: sub load_loncaparevs {
12290: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12291: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12292: while (my $configline=<$config>) {
12293: chomp($configline);
12294: my ($hostid,$loncaparev)=split(/:/,$configline);
12295: $loncaparevs{$hostid}=$loncaparev;
12296: }
12297: close($config);
12298: }
12299: }
12300: }
12301: }
12302:
12303: # ----------------------------------------------------- Read serverhostID table
12304: {
12305: sub load_serverhomeIDs {
12306: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12307: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12308: while (my $configline=<$config>) {
12309: chomp($configline);
12310: my ($name,$id)=split(/:/,$configline);
12311: $serverhomeIDs{$name}=$id;
12312: }
12313: close($config);
12314: }
12315: }
12316: }
12317: }
12318:
12319:
1.862 albertel 12320: BEGIN {
12321:
12322: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12323: unless ($readit) {
12324: {
12325: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12326: %perlvar = (%perlvar,%{$configvars});
12327: }
12328:
12329:
1.1 albertel 12330: # ------------------------------------------------------ Read spare server file
12331: {
1.448 albertel 12332: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12333:
12334: while (my $configline=<$config>) {
12335: chomp($configline);
1.284 matthew 12336: if ($configline) {
1.784 albertel 12337: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12338: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12339: push(@{ $spareid{$type} }, $host);
1.1 albertel 12340: }
12341: }
1.448 albertel 12342: close($config);
1.1 albertel 12343: }
1.11 www 12344: # ------------------------------------------------------------ Read permissions
12345: {
1.448 albertel 12346: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12347:
12348: while (my $configline=<$config>) {
1.448 albertel 12349: chomp($configline);
12350: if ($configline) {
12351: my ($role,$perm)=split(/ /,$configline);
12352: if ($perm ne '') { $pr{$role}=$perm; }
12353: }
1.11 www 12354: }
1.448 albertel 12355: close($config);
1.11 www 12356: }
12357:
12358: # -------------------------------------------- Read plain texts for permissions
12359: {
1.448 albertel 12360: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12361:
12362: while (my $configline=<$config>) {
1.448 albertel 12363: chomp($configline);
12364: if ($configline) {
1.742 raeburn 12365: my ($short,@plain)=split(/:/,$configline);
12366: %{$prp{$short}} = ();
12367: if (@plain > 0) {
12368: $prp{$short}{'std'} = $plain[0];
12369: for (my $i=1; $i<@plain; $i++) {
12370: $prp{$short}{'alt'.$i} = $plain[$i];
12371: }
12372: }
1.448 albertel 12373: }
1.135 www 12374: }
1.448 albertel 12375: close($config);
1.135 www 12376: }
12377:
12378: # ---------------------------------------------------------- Read package table
12379: {
1.448 albertel 12380: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12381:
12382: while (my $configline=<$config>) {
1.483 albertel 12383: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12384: chomp($configline);
12385: my ($short,$plain)=split(/:/,$configline);
12386: my ($pack,$name)=split(/\&/,$short);
12387: if ($plain ne '') {
12388: $packagetab{$pack.'&'.$name.'&name'}=$name;
12389: $packagetab{$short}=$plain;
12390: }
1.11 www 12391: }
1.448 albertel 12392: close($config);
1.329 matthew 12393: }
12394:
1.1172.2.27 raeburn 12395: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12396:
1.1172.2.27 raeburn 12397: &load_loncaparevs();
12398:
12399: # ------------------------------------------------------- Read serverhostID table
12400:
12401: &load_serverhomeIDs();
1.1074 raeburn 12402:
1.1172.2.27 raeburn 12403: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12404: {
12405: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12406: if (-e $file) {
12407: my $parser = HTML::LCParser->new($file);
12408: while (my $token = $parser->get_token()) {
12409: if ($token->[0] eq 'S') {
12410: my $item = $token->[1];
12411: my $name = $token->[2]{'name'};
12412: my $value = $token->[2]{'value'};
12413: if ($item ne '' && $name ne '' && $value ne '') {
12414: my $release = $parser->get_text();
12415: $release =~ s/(^\s*|\s*$ )//gx;
12416: $needsrelease{$item.':'.$name.':'.$value} = $release;
12417: }
12418: }
12419: }
12420: }
1.1073 raeburn 12421: }
12422:
1.1138 raeburn 12423: # ---------------------------------------------------------- Read managers table
12424: {
12425: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12426: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12427: while (my $configline=<$config>) {
12428: chomp($configline);
12429: next if ($configline =~ /^\#/);
12430: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12431: $managerstab{$configline} = 1;
12432: }
12433: }
12434: close($config);
12435: }
12436: }
12437: }
12438:
1.329 matthew 12439: # ------------- set up temporary directory
12440: {
1.1117 foxr 12441: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12442:
1.11 www 12443: }
12444:
1.794 albertel 12445: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12446: 'compress_threshold'=> 20_000,
12447: });
1.185 www 12448:
1.281 www 12449: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12450: $dumpcount=0;
1.958 www 12451: $locknum=0;
1.22 www 12452:
1.163 harris41 12453: &logtouch();
1.672 albertel 12454: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12455: $readit=1;
1.564 albertel 12456: {
12457: use integer;
12458: my $test=(2**32)+1;
1.568 albertel 12459: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12460: &logthis(" Detected 64bit platform ($_64bit)");
12461: }
1.195 www 12462: }
1.1 albertel 12463: }
1.179 www 12464:
1.1 albertel 12465: 1;
1.191 harris41 12466: __END__
12467:
1.243 albertel 12468: =pod
12469:
1.191 harris41 12470: =head1 NAME
12471:
1.243 albertel 12472: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12473:
12474: =head1 SYNOPSIS
12475:
1.243 albertel 12476: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12477:
12478: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12479:
1.243 albertel 12480: Common parameters:
12481:
12482: =over 4
12483:
12484: =item *
12485:
12486: $uname : an internal username (if $cname expecting a course Id specifically)
12487:
12488: =item *
12489:
12490: $udom : a domain (if $cdom expecting a course's domain specifically)
12491:
12492: =item *
12493:
12494: $symb : a resource instance identifier
12495:
12496: =item *
12497:
12498: $namespace : the name of a .db file that contains the data needed or
12499: being set.
12500:
12501: =back
12502:
1.394 bowersj2 12503: =head1 OVERVIEW
1.191 harris41 12504:
1.394 bowersj2 12505: lonnet provides subroutines which interact with the
12506: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12507: about classes, users, and resources.
1.243 albertel 12508:
12509: For many of these objects you can also use this to store data about
12510: them or modify them in various ways.
1.191 harris41 12511:
1.394 bowersj2 12512: =head2 Symbs
1.191 harris41 12513:
1.394 bowersj2 12514: To identify a specific instance of a resource, LON-CAPA uses symbols
12515: or "symbs"X<symb>. These identifiers are built from the URL of the
12516: map, the resource number of the resource in the map, and the URL of
12517: the resource itself. The latter is somewhat redundant, but might help
12518: if maps change.
12519:
12520: An example is
12521:
12522: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12523:
12524: The respective map entry is
12525:
12526: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12527: title="Problem 2">
12528: </resource>
12529:
12530: Symbs are used by the random number generator, as well as to store and
12531: restore data specific to a certain instance of for example a problem.
12532:
12533: =head2 Storing And Retrieving Data
12534:
12535: X<store()>X<cstore()>X<restore()>Three of the most important functions
12536: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12537: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12538: is is the non-critical message twin of cstore. These functions are for
12539: handlers to store a perl hash to a user's permanent data space in an
12540: easy manner, and to retrieve it again on another call. It is expected
12541: that a handler would use this once at the beginning to retrieve data,
12542: and then again once at the end to send only the new data back.
12543:
12544: The data is stored in the user's data directory on the user's
12545: homeserver under the ID of the course.
12546:
12547: The hash that is returned by restore will have all of the previous
12548: value for all of the elements of the hash.
12549:
12550: Example:
12551:
12552: #creating a hash
12553: my %hash;
12554: $hash{'foo'}='bar';
12555:
12556: #storing it
12557: &Apache::lonnet::cstore(\%hash);
12558:
12559: #changing a value
12560: $hash{'foo'}='notbar';
12561:
12562: #adding a new value
12563: $hash{'bar'}='foo';
12564: &Apache::lonnet::cstore(\%hash);
12565:
12566: #retrieving the hash
12567: my %history=&Apache::lonnet::restore();
12568:
12569: #print the hash
12570: foreach my $key (sort(keys(%history))) {
12571: print("\%history{$key} = $history{$key}");
12572: }
12573:
12574: Will print out:
1.191 harris41 12575:
1.394 bowersj2 12576: %history{1:foo} = bar
12577: %history{1:keys} = foo:timestamp
12578: %history{1:timestamp} = 990455579
12579: %history{2:bar} = foo
12580: %history{2:foo} = notbar
12581: %history{2:keys} = foo:bar:timestamp
12582: %history{2:timestamp} = 990455580
12583: %history{bar} = foo
12584: %history{foo} = notbar
12585: %history{timestamp} = 990455580
12586: %history{version} = 2
12587:
12588: Note that the special hash entries C<keys>, C<version> and
12589: C<timestamp> were added to the hash. C<version> will be equal to the
12590: total number of versions of the data that have been stored. The
12591: C<timestamp> attribute will be the UNIX time the hash was
12592: stored. C<keys> is available in every historical section to list which
12593: keys were added or changed at a specific historical revision of a
12594: hash.
12595:
12596: B<Warning>: do not store the hash that restore returns directly. This
12597: will cause a mess since it will restore the historical keys as if the
12598: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12599:
1.394 bowersj2 12600: Calling convention:
1.191 harris41 12601:
1.1172.2.27 raeburn 12602: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12603: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12604:
1.394 bowersj2 12605: For more detailed information, see lonnet specific documentation.
1.191 harris41 12606:
1.394 bowersj2 12607: =head1 RETURN MESSAGES
1.191 harris41 12608:
1.394 bowersj2 12609: =over 4
1.191 harris41 12610:
1.394 bowersj2 12611: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12612:
1.394 bowersj2 12613: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12614: when the connection is brought back up
1.191 harris41 12615:
1.394 bowersj2 12616: =item * B<con_failed>: unable to contact remote host and unable to save message
12617: for later delivery
1.191 harris41 12618:
1.967 bisitz 12619: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12620:
1.394 bowersj2 12621: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12622: that was requested
1.191 harris41 12623:
1.243 albertel 12624: =back
1.191 harris41 12625:
1.243 albertel 12626: =head1 PUBLIC SUBROUTINES
1.191 harris41 12627:
1.243 albertel 12628: =head2 Session Environment Functions
1.191 harris41 12629:
1.243 albertel 12630: =over 4
1.191 harris41 12631:
1.394 bowersj2 12632: =item *
12633: X<appenv()>
1.949 raeburn 12634: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12635: the user envirnoment file, and will be restored for each access this
1.620 albertel 12636: user makes during this session, also modifies the %env for the current
1.949 raeburn 12637: process. Optional rolesarrayref - if defined contains a reference to an array
12638: of roles which are exempt from the restriction on modifying user.role entries
12639: in the user's environment.db and in %env.
1.191 harris41 12640:
12641: =item *
1.394 bowersj2 12642: X<delenv()>
1.987 raeburn 12643: B<delenv($delthis,$regexp)>: removes all items from the session
12644: environment file that begin with $delthis. If the
12645: optional second arg - $regexp - is true, $delthis is treated as a
12646: regular expression, otherwise \Q$delthis\E is used.
12647: The values are also deleted from the current processes %env.
1.191 harris41 12648:
1.795 albertel 12649: =item * get_env_multiple($name)
12650:
12651: gets $name from the %env hash, it seemlessly handles the cases where multiple
12652: values may be defined and end up as an array ref.
12653:
12654: returns an array of values
12655:
1.243 albertel 12656: =back
12657:
12658: =head2 User Information
1.191 harris41 12659:
1.243 albertel 12660: =over 4
1.191 harris41 12661:
12662: =item *
1.394 bowersj2 12663: X<queryauthenticate()>
12664: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12665: authentication scheme
12666:
12667: =item *
1.394 bowersj2 12668: X<authenticate()>
1.1073 raeburn 12669: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12670: authenticate user from domain's lib servers (first use the current
12671: one). C<$upass> should be the users password.
1.1073 raeburn 12672: $checkdefauth is optional (value is 1 if a check should be made to
12673: authenticate user using default authentication method, and allow
12674: account creation if username does not have account in the domain).
12675: $clientcancheckhost is optional (value is 1 if checking whether the
12676: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12677:
12678: =item *
1.394 bowersj2 12679: X<homeserver()>
12680: B<homeserver($uname,$udom)>: find the server which has
12681: the user's directory and files (there must be only one), this caches
12682: the answer, and also caches if there is a borken connection.
1.191 harris41 12683:
12684: =item *
1.394 bowersj2 12685: X<idget()>
12686: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12687: (IDs are a unique resource in a domain, there must be only 1 ID per
12688: username, and only 1 username per ID in a specific domain) (returns
12689: hash: id=>name,id=>name)
1.191 harris41 12690:
12691: =item *
1.394 bowersj2 12692: X<idrget()>
12693: B<idrget($udom,@unames)>: find the IDs behind a list of
12694: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12695:
12696: =item *
1.394 bowersj2 12697: X<idput()>
12698: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12699:
12700: =item *
1.394 bowersj2 12701: X<rolesinit()>
1.1169 droeschl 12702: B<rolesinit($udom,$username)>: get user privileges.
12703: returns user role, first access and timer interval hashes
1.243 albertel 12704:
12705: =item *
1.1171 droeschl 12706: X<privileged()>
12707: B<privileged($username,$domain)>: returns a true if user has a
12708: privileged and active role (i.e. su or dc), false otherwise.
12709:
12710: =item *
1.551 albertel 12711: X<getsection()>
12712: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12713: course $cname, return section name/number or '' for "not in course"
12714: and '-1' for "no section"
12715:
12716: =item *
1.394 bowersj2 12717: X<userenvironment()>
12718: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12719: passed in @what from the requested user's environment, returns a hash
12720:
1.858 raeburn 12721: =item *
12722: X<userlog_query()>
1.859 albertel 12723: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12724: activity.log file. %filters defines filters applied when parsing the
12725: log file. These can be start or end timestamps, or the type of action
12726: - log to look for Login or Logout events, check for Checkin or
12727: Checkout, role for role selection. The response is in the form
12728: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12729: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12730:
1.243 albertel 12731: =back
12732:
12733: =head2 User Roles
12734:
12735: =over 4
12736:
12737: =item *
12738:
1.810 raeburn 12739: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12740: F: full access
12741: U,I,K: authentication modes (cxx only)
12742: '': forbidden
12743: 1: user needs to choose course
12744: 2: browse allowed
1.766 albertel 12745: A: passphrase authentication needed
1.243 albertel 12746:
12747: =item *
12748:
1.1172.2.13 raeburn 12749: constructaccess($url,$setpriv) : check for access to construction space URL
12750:
12751: See if the owner domain and name in the URL match those in the
12752: expected environment. If so, return three element list
12753: ($ownername,$ownerdomain,$ownerhome).
12754:
12755: Otherwise return the null string.
12756:
12757: If second argument 'setpriv' is true, it assigns the privileges,
12758: and returns the same three element list, unless the owner has
12759: blocked "ad hoc" Domain Coordinator access to the Author Space,
12760: in which case the null string is returned.
12761:
12762: =item *
12763:
1.243 albertel 12764: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12765: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12766: and course level
12767:
12768: =item *
12769:
1.988 raeburn 12770: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12771: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12772: $type is Course (default) or Community.
1.988 raeburn 12773: If $forcedefault evaluates to true, text returned will be default
12774: text for $type. Otherwise, if this is a course, the text returned
12775: will be a custom name for the role (if defined in the course's
12776: environment). If no custom name is defined the default is returned.
12777:
1.832 raeburn 12778: =item *
12779:
1.1172.2.23 raeburn 12780: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12781: All arguments are optional. Returns a hash of a roles, either for
12782: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12783: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12784: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12785: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12786: For each key, value is set to colon-separated start and end times for
12787: the role. If no username and domain are specified, will default to
1.934 raeburn 12788: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12789: of role statuses (active, future or previous), roles
12790: (e.g., cc,in, st etc.) and domains of the roles which can be used
12791: to restrict the list of roles reported. If no array ref is
12792: provided for types, will default to return only active roles.
1.834 albertel 12793:
1.1172.2.13 raeburn 12794: =item *
12795:
12796: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12797: user: $uname:$udom has a role in the course: $cdom_$cnum.
12798:
12799: Additional optional arguments are: $type (if role checking is to be restricted
12800: to certain user status types -- previous (expired roles), active (currently
12801: available roles) or future (roles available in the future), and
12802: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12803: have active Domain Coordinator role in course's domain or in additional
12804: domains (specified in 'Domains to check for privileged users' in course
12805: environment -- set via: Course Settings -> Classlists and staff listing).
12806:
12807: =item *
12808:
12809: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12810: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12811: $possdomains and $possroles are optional array refs -- to domains to check and
12812: roles to check. If $possdomains is not specified, a dump will be done of the
12813: users' roles.db to check for a dc or su role in any domain. This can be
12814: time consuming if &privileged is called repeatedly (e.g., when displaying a
12815: classlist), so in such cases, supplying a $possdomains array is preferred, as
12816: this then allows &privileged_by_domain() to be used, which caches the identity
12817: of privileged users, eliminating the need for repeated calls to &dump().
12818:
12819: =item *
12820:
12821: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12822: where the outer hash keys are domains specified in the $possdomains array ref,
12823: next inner hash keys are privileged roles specified in the $roles array ref,
12824: and the innermost hash contains key = value pairs for username:domain = end:start
12825: for active or future "privileged" users with that role in that domain. To avoid
12826: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12827: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12828:
1.243 albertel 12829: =back
12830:
12831: =head2 User Modification
12832:
12833: =over 4
12834:
12835: =item *
12836:
1.957 raeburn 12837: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12838: user for the level given by URL. Optional start and end dates (leave empty
12839: string or zero for "no date")
1.191 harris41 12840:
12841: =item *
12842:
1.243 albertel 12843: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12844: change a users, password, possible return values are: ok,
12845: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12846: refused
1.191 harris41 12847:
12848: =item *
12849:
1.243 albertel 12850: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12851:
12852: =item *
12853:
1.1058 raeburn 12854: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12855: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12856:
12857: will update user information (firstname,middlename,lastname,generation,
12858: permanentemail), and if forceid is true, student/employee ID also.
12859: A user's institutional affiliation(s) can also be updated.
12860: User information fields will not be overwritten with empty entries
12861: unless the field is included in the $candelete array reference.
12862: This array is included when a single user is modified via "Manage Users",
12863: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12864:
12865: =item *
12866:
1.286 matthew 12867: modifystudent
12868:
1.957 raeburn 12869: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12870: The course id is resolved based on the current user's environment.
12871: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12872: associated with a course.
12873:
1.297 matthew 12874: This call is essentially a wrapper for lonnet::modifyuser and
12875: lonnet::modify_student_enrollment
1.286 matthew 12876:
12877: Inputs:
12878:
12879: =over 4
12880:
1.957 raeburn 12881: =item B<$udom> Student's loncapa domain
1.286 matthew 12882:
1.957 raeburn 12883: =item B<$uname> Student's loncapa login name
1.286 matthew 12884:
1.964 bisitz 12885: =item B<$uid> Student/Employee ID
1.286 matthew 12886:
1.957 raeburn 12887: =item B<$umode> Student's authentication mode
1.286 matthew 12888:
1.957 raeburn 12889: =item B<$upass> Student's password
1.286 matthew 12890:
1.957 raeburn 12891: =item B<$first> Student's first name
1.286 matthew 12892:
1.957 raeburn 12893: =item B<$middle> Student's middle name
1.286 matthew 12894:
1.957 raeburn 12895: =item B<$last> Student's last name
1.286 matthew 12896:
1.957 raeburn 12897: =item B<$gene> Student's generation
1.286 matthew 12898:
1.957 raeburn 12899: =item B<$usec> Student's section in course
1.286 matthew 12900:
12901: =item B<$end> Unix time of the roles expiration
12902:
12903: =item B<$start> Unix time of the roles start date
12904:
12905: =item B<$forceid> If defined, allow $uid to be changed
12906:
12907: =item B<$desiredhome> server to use as home server for student
12908:
1.957 raeburn 12909: =item B<$email> Student's permanent e-mail address
12910:
12911: =item B<$type> Type of enrollment (auto or manual)
12912:
1.963 raeburn 12913: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12914:
12915: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12916:
1.963 raeburn 12917: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12918:
1.963 raeburn 12919: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12920:
1.1172.2.19 raeburn 12921: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12922:
12923: =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 12924:
1.286 matthew 12925: =back
1.297 matthew 12926:
12927: =item *
12928:
12929: modify_student_enrollment
12930:
1.1172.2.31 raeburn 12931: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12932: 'role.request.course' must be defined for this function to proceed.
12933:
12934: Inputs:
12935:
12936: =over 4
12937:
1.1172.2.31 raeburn 12938: =item $udom, student's domain
1.297 matthew 12939:
1.1172.2.31 raeburn 12940: =item $uname, student's name
1.297 matthew 12941:
1.1172.2.31 raeburn 12942: =item $uid, student's user id
1.297 matthew 12943:
1.1172.2.31 raeburn 12944: =item $first, student's first name
1.297 matthew 12945:
12946: =item $middle
12947:
12948: =item $last
12949:
12950: =item $gene
12951:
12952: =item $usec
12953:
12954: =item $end
12955:
12956: =item $start
12957:
1.957 raeburn 12958: =item $type
12959:
12960: =item $locktype
12961:
12962: =item $cid
12963:
12964: =item $selfenroll
12965:
12966: =item $context
12967:
1.1172.2.19 raeburn 12968: =item $credits, number of credits student will earn from this class
12969:
1.297 matthew 12970: =back
12971:
1.191 harris41 12972:
12973: =item *
12974:
1.243 albertel 12975: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12976: custom role; give a custom role to a user for the level given by URL. Specify
12977: name and domain of role author, and role name
1.191 harris41 12978:
12979: =item *
12980:
1.243 albertel 12981: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12982:
12983: =item *
12984:
1.243 albertel 12985: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12986:
12987: =back
12988:
12989: =head2 Course Infomation
12990:
12991: =over 4
1.191 harris41 12992:
12993: =item *
12994:
1.1118 foxr 12995: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12996: specified course id, including all environment settings for the
12997: course, the description of the course will be in the hash under the
12998: key 'description'
1.191 harris41 12999:
1.1118 foxr 13000: $options is an optional parameter that if supplied is a hash reference that controls
13001: what how this function works. It has the following key/values:
13002:
13003: =over 4
13004:
13005: =item freshen_cache
13006:
13007: If defined, and the environment cache for the course is valid, it is
13008: returned in the returned hash.
13009:
13010: =item one_time
13011:
13012: If defined, the last cache time is set to _now_
13013:
13014: =item user
13015:
13016: If defined, the supplied username is used instead of the current user.
13017:
13018:
13019: =back
13020:
1.191 harris41 13021: =item *
13022:
1.624 albertel 13023: resdata($name,$domain,$type,@which) : request for current parameter
13024: setting for a specific $type, where $type is either 'course' or 'user',
13025: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13026: answers for 10 minutes.
1.243 albertel 13027:
1.877 foxr 13028: =item *
13029:
13030: get_courseresdata($courseid, $domain) : dump the entire course resource
13031: data base, returning a hash that is keyed by the resource name and has
13032: values that are the resource value. I believe that the timestamps and
13033: versions are also returned.
13034:
1.1172.2.31 raeburn 13035: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13036: supplemental content area. This routine caches the number of files for
13037: 10 minutes.
13038:
1.243 albertel 13039: =back
13040:
13041: =head2 Course Modification
13042:
13043: =over 4
1.191 harris41 13044:
13045: =item *
13046:
1.243 albertel 13047: writecoursepref($courseid,%prefs) : write preferences (environment
13048: database) for a course
1.191 harris41 13049:
13050: =item *
13051:
1.1011 raeburn 13052: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13053:
13054: =item *
13055:
1.1038 raeburn 13056: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13057:
1.1167 droeschl 13058: =item *
13059:
13060: is_course($courseid), is_course($cdom, $cnum)
13061:
13062: Accepts either a combined $courseid (in the form of domain_courseid) or the
13063: two component version $cdom, $cnum. It checks if the specified course exists.
13064:
13065: Returns:
13066: undef if the course doesn't exist, otherwise
13067: in scalar context the combined courseid.
13068: in list context the two components of the course identifier, domain and
13069: courseid.
13070:
1.243 albertel 13071: =back
13072:
13073: =head2 Resource Subroutines
13074:
13075: =over 4
1.191 harris41 13076:
13077: =item *
13078:
1.243 albertel 13079: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13080:
13081: =item *
13082:
1.243 albertel 13083: repcopy($filename) : subscribes to the requested file, and attempts to
13084: replicate from the owning library server, Might return
1.607 raeburn 13085: 'unavailable', 'not_found', 'forbidden', 'ok', or
13086: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13087: resource. Expects the local filesystem pathname
13088: (/home/httpd/html/res/....)
13089:
13090: =back
13091:
13092: =head2 Resource Information
13093:
13094: =over 4
1.191 harris41 13095:
13096: =item *
13097:
1.1172.2.28 raeburn 13098: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13099: and returns the value of a variety of different possible values,
13100: $varname should be a request string, and the other parameters can be
13101: used to specify who and what one is asking about. Ordinarily, $cid
13102: does not need to be specified, as it is retrived from
13103: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13104: within lonuserstate::loadmap() when initializing a course, before
13105: $env{'request.course.id'} has been set, so it needs to be provided
13106: in that one case.
1.243 albertel 13107:
13108: Possible values for $varname are environment.lastname (or other item
13109: from the envirnment hash), user.name (or someother aspect about the
13110: user), resource.0.maxtries (or some other part and parameter of a
13111: resource)
1.204 albertel 13112:
13113: =item *
13114:
1.243 albertel 13115: directcondval($number) : get current value of a condition; reads from a state
13116: string
1.204 albertel 13117:
13118: =item *
13119:
1.243 albertel 13120: condval($condidx) : value of condition index based on state
1.204 albertel 13121:
13122: =item *
13123:
1.243 albertel 13124: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13125: resource's metadata, $what should be either a specific key, or either
13126: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13127: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13128:
13129: this function automatically caches all requests
1.191 harris41 13130:
13131: =item *
13132:
1.243 albertel 13133: metadata_query($query,$custom,$customshow) : make a metadata query against the
13134: network of library servers; returns file handle of where SQL and regex results
13135: will be stored for query
1.191 harris41 13136:
13137: =item *
13138:
1.243 albertel 13139: symbread($filename) : return symbolic list entry (filename argument optional);
13140: returns the data handle
1.191 harris41 13141:
13142: =item *
13143:
1.1172.2.17 raeburn 13144: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13145: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13146: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13147: on failure, user must be in a course, as it assumes the existence of
13148: the course initial hash, and uses $env('request.course.id'}. The third
13149: arg is an optional reference to a scalar. If this arg is passed in the
13150: call to symbverify, it will be set to 1 if the symb has been set to be
13151: encrypted; otherwise it will be null.
1.243 albertel 13152:
1.191 harris41 13153: =item *
13154:
1.243 albertel 13155: symbclean($symb) : removes versions numbers from a symb, returns the
13156: cleaned symb
1.191 harris41 13157:
13158: =item *
13159:
1.243 albertel 13160: is_on_map($uri) : checks if the $uri is somewhere on the current
13161: course map, user must be in a course for it to work.
1.191 harris41 13162:
13163: =item *
13164:
1.243 albertel 13165: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13166:
13167: =item *
13168:
1.243 albertel 13169: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13170: a random seed, all arguments are optional, if they aren't sent it uses the
13171: environment to derive them. Note: if symb isn't sent and it can't get one
13172: from &symbread it will use the current time as its return value
1.191 harris41 13173:
13174: =item *
13175:
1.243 albertel 13176: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13177: unfakeable, receipt
1.191 harris41 13178:
13179: =item *
13180:
1.620 albertel 13181: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13182:
13183: =item *
13184:
1.243 albertel 13185: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13186:
13187: =item *
13188:
1.243 albertel 13189: 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 13190:
13191: =item *
13192:
1.243 albertel 13193: 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 13194:
13195: =item *
13196:
1.243 albertel 13197: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13198:
13199: =item *
13200:
1.243 albertel 13201: devalidate($symb) : devalidate temporary spreadsheet calculations,
13202: forcing spreadsheet to reevaluate the resource scores next time.
13203:
1.1172.2.13 raeburn 13204: =item *
13205:
13206: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13207: when viewing in course context.
13208:
13209: input: six args -- filename (decluttered), course number, course domain,
13210: url, symb (if registered) and group (if this is a
13211: group item -- e.g., bulletin board, group page etc.).
13212:
13213: output: array of five scalars --
13214: $cfile -- url for file editing if editable on current server
13215: $home -- homeserver of resource (i.e., for author if published,
13216: or course if uploaded.).
13217: $switchserver -- 1 if server switch will be needed.
13218: $forceedit -- 1 if icon/link should be to go to edit mode
13219: $forceview -- 1 if icon/link should be to go to view mode
13220:
13221: =item *
13222:
13223: is_course_upload($file,$cnum,$cdom)
13224:
13225: Used in course context to determine if current file was uploaded to
13226: the course (i.e., would be found in /userfiles/docs on the course's
13227: homeserver.
13228:
13229: input: 3 args -- filename (decluttered), course number and course domain.
13230: output: boolean -- 1 if file was uploaded.
13231:
1.243 albertel 13232: =back
13233:
13234: =head2 Storing/Retreiving Data
13235:
13236: =over 4
1.191 harris41 13237:
13238: =item *
13239:
1.243 albertel 13240: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13241: for this url; hashref needs to be given and should be a \%hashname; the
13242: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13243: be derived from the env
1.191 harris41 13244:
13245: =item *
13246:
1.243 albertel 13247: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13248: uses critical subroutine
1.191 harris41 13249:
13250: =item *
13251:
1.243 albertel 13252: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13253: all args are optional
1.191 harris41 13254:
13255: =item *
13256:
1.717 albertel 13257: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13258: dumps the complete (or key matching regexp) namespace into a hash
13259: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13260: normally &store()ed into
13261:
13262: $range should be either an integer '100' (give me the first 100
13263: matching records)
13264: or be two integers sperated by a - with no spaces
13265: '30-50' (give me the 30th through the 50th matching
13266: records)
13267:
13268:
13269: =item *
13270:
13271: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13272: replaces a &store() version of data with a replacement set of data
13273: for a particular resource in a namespace passed in the $storehash hash
13274: reference
13275:
13276: =item *
13277:
1.243 albertel 13278: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13279: works very similar to store/cstore, but all data is stored in a
13280: temporary location and can be reset using tmpreset, $storehash should
13281: be a hash reference, returns nothing on success
1.191 harris41 13282:
13283: =item *
13284:
1.243 albertel 13285: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13286: similar to restore, but all data is stored in a temporary location and
13287: can be reset using tmpreset. Returns a hash of values on success,
13288: error string otherwise.
1.191 harris41 13289:
13290: =item *
13291:
1.243 albertel 13292: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13293: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13294:
13295: =item *
13296:
1.243 albertel 13297: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13298: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13299:
13300: =item *
13301:
1.243 albertel 13302: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13303: namesp ($udom and $uname are optional)
1.191 harris41 13304:
13305: =item *
13306:
1.702 albertel 13307: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13308: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13309: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13310:
1.702 albertel 13311: $range should be either an integer '100' (give me the first 100
13312: matching records)
13313: or be two integers sperated by a - with no spaces
13314: '30-50' (give me the 30th through the 50th matching
13315: records)
1.449 matthew 13316: =item *
13317:
13318: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13319: $store can be a scalar, an array reference, or if the amount to be
13320: incremented is > 1, a hash reference.
13321:
13322: ($udom and $uname are optional)
1.191 harris41 13323:
13324: =item *
13325:
1.243 albertel 13326: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13327: ($udom and $uname are optional)
1.191 harris41 13328:
13329: =item *
13330:
1.243 albertel 13331: cput($namespace,$storehash,$udom,$uname) : critical put
13332: ($udom and $uname are optional)
1.191 harris41 13333:
13334: =item *
13335:
1.748 albertel 13336: newput($namespace,$storehash,$udom,$uname) :
13337:
13338: Attempts to store the items in the $storehash, but only if they don't
13339: currently exist, if this succeeds you can be certain that you have
13340: successfully created a new key value pair in the $namespace db.
13341:
13342:
13343: Args:
13344: $namespace: name of database to store values to
13345: $storehash: hashref to store to the db
13346: $udom: (optional) domain of user containing the db
13347: $uname: (optional) name of user caontaining the db
13348:
13349: Returns:
13350: 'ok' -> succeeded in storing all keys of $storehash
13351: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13352: least <key> already existed in the db (other
13353: requested keys may also already exist)
1.967 bisitz 13354: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13355: 'con_lost' -> unable to contact request server
13356: 'refused' -> action was not allowed by remote machine
13357:
13358:
13359: =item *
13360:
1.243 albertel 13361: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13362: reference filled in from namesp (encrypts the return communication)
13363: ($udom and $uname are optional)
1.191 harris41 13364:
13365: =item *
13366:
1.243 albertel 13367: log($udom,$name,$home,$message) : write to permanent log for user; use
13368: critical subroutine
13369:
1.806 raeburn 13370: =item *
13371:
1.860 raeburn 13372: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13373: array reference filled in from namespace found in domain level on either
13374: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13375:
13376: =item *
13377:
1.860 raeburn 13378: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13379: domain level either on specified domain server ($uhome) or primary domain
13380: server ($udom and $uhome are optional)
1.806 raeburn 13381:
1.943 raeburn 13382: =item *
13383:
1.1172.2.35 raeburn 13384: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13385: for: authentication, language, quotas, timezone, date locale, and portal URL in
13386: the target domain.
13387:
13388: May also include additional key => value pairs for the following groups:
13389:
13390: =over
13391:
13392: =item
13393: disk quotas (MB allocated by default to portfolios and authoring spaces).
13394:
13395: =over
13396:
13397: =item defaultquota, authorquota
13398:
13399: =back
13400:
13401: =item
13402: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13403: portfolio for users).
13404:
13405: =over
13406:
13407: =item
13408: aboutme, blog, webdav, portfolio
13409:
13410: =back
13411:
13412: =item
13413: requestcourses: ability to request courses, and how requests are processed.
13414:
13415: =over
13416:
13417: =item
1.1172.2.37 raeburn 13418: official, unofficial, community, textbook
1.1172.2.35 raeburn 13419:
13420: =back
13421:
13422: =item
13423: inststatus: types of institutional affiliation, and order in which they are displayed.
13424:
13425: =over
13426:
13427: =item
1.1172.2.44 raeburn 13428: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13429:
13430: =back
13431:
13432: =item
13433: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13434: for course's uploaded content.
13435:
13436: =over
13437:
13438: =item
1.1172.2.37 raeburn 13439: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13440:
13441: =back
13442:
13443: =item
13444: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13445: on your servers.
13446:
13447: =over
13448:
13449: =item
13450: remotesessions, hostedsessions
13451:
13452: =back
13453:
13454: =back
13455:
13456: In cases where a domain coordinator has never used the "Set Domain Configuration"
13457: utility to create a configuration.db file on a domain's primary library server
13458: only the following domain defaults: auth_def, auth_arg_def, lang_def
13459: -- corresponding values are authentication type (internal, krb4, krb5,
13460: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13461: will be available. Values are retrieved from cache (if current), unless the
13462: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13463: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13464:
13465: Typical usage:
1.943 raeburn 13466:
1.1172.2.35 raeburn 13467: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13468:
1.243 albertel 13469: =back
13470:
13471: =head2 Network Status Functions
13472:
13473: =over 4
1.191 harris41 13474:
13475: =item *
13476:
1.1137 raeburn 13477: dirlist() : return directory list based on URI (first arg).
13478:
13479: Inputs: 1 required, 5 optional.
13480:
13481: =over
13482:
13483: =item
13484: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13485:
13486: =item
13487: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13488:
13489: =item
13490: $username - username of user/course to be listed. Extracted from $uri if absent.
13491:
13492: =item
13493: $getpropath - boolean: 1 if prepend path using &propath().
13494:
13495: =item
13496: $getuserdir - boolean: 1 if prepend path for "userfiles".
13497:
13498: =item
13499: $alternateRoot - path to prepend in place of path from $uri.
13500:
13501: =back
13502:
13503: Returns: Array of up to two items.
13504:
13505: =over
13506:
13507: a reference to an array of files/subdirectories
13508:
13509: =over
13510:
13511: Each element in the array of files/subdirectories is a & separated list of
13512: item name and the result of running stat on the item. If dirlist was requested
13513: for a file instead of a directory, the item name will be ''. For a directory
13514: listing, if the item is a metadata file, the element will end &N&M
13515: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13516: default copyright set (1).
13517:
13518: =back
13519:
13520: a scalar containing error condition (if encountered).
13521:
13522: =over
13523:
13524: =item
13525: no_host (no homeserver identified for $username:$domain).
13526:
13527: =item
13528: no_such_host (server contacted for listing not identified as valid host).
13529:
13530: =item
13531: con_lost (connection to remote server failed).
13532:
13533: =item
13534: refused (invalid $username:$domain received on lond side).
13535:
13536: =item
13537: no_such_dir (directory at specified path on lond side does not exist).
13538:
13539: =item
13540: empty (directory at specified path on lond side is empty).
13541:
13542: =over
13543:
13544: This is currently not encountered because the &ls3, &ls2,
13545: &ls (_handler) routines on the lond side do not filter out
13546: . and .. from a directory listing.
13547:
13548: =back
13549:
13550: =back
13551:
13552: =back
1.191 harris41 13553:
13554: =item *
13555:
1.243 albertel 13556: spareserver() : find server with least workload from spare.tab
13557:
1.986 foxr 13558:
13559: =item *
13560:
13561: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13562: if there is no corresponding loncapa host.
13563:
1.243 albertel 13564: =back
13565:
1.986 foxr 13566:
1.243 albertel 13567: =head2 Apache Request
13568:
13569: =over 4
1.191 harris41 13570:
13571: =item *
13572:
1.243 albertel 13573: ssi($url,%hash) : server side include, does a complete request cycle on url to
13574: localhost, posts hash
13575:
13576: =back
13577:
13578: =head2 Data to String to Data
13579:
13580: =over 4
1.191 harris41 13581:
13582: =item *
13583:
1.243 albertel 13584: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13585: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13586:
13587: =item *
13588:
1.243 albertel 13589: hashref2str($hashref) : convert a hashref into a string complete with
13590: escaping and '=' and '&' separators, supports elements that are
13591: arrayrefs and hashrefs
1.191 harris41 13592:
13593: =item *
13594:
1.243 albertel 13595: arrayref2str($arrayref) : convert an arrayref into a string complete
13596: with escaping and '&' separators, supports elements that are arrayrefs
13597: and hashrefs
1.191 harris41 13598:
13599: =item *
13600:
1.243 albertel 13601: str2hash($string) : convert string to hash using unescaping and
13602: splitting on '=' and '&', supports elements that are arrayrefs and
13603: hashrefs
1.191 harris41 13604:
13605: =item *
13606:
1.243 albertel 13607: str2array($string) : convert string to hash using unescaping and
13608: splitting on '&', supports elements that are arrayrefs and hashrefs
13609:
13610: =back
13611:
13612: =head2 Logging Routines
13613:
13614:
13615: These routines allow one to make log messages in the lonnet.log and
13616: lonnet.perm logfiles.
1.191 harris41 13617:
1.1119 foxr 13618: =over 4
13619:
1.191 harris41 13620: =item *
13621:
1.243 albertel 13622: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13623:
13624: =item *
13625:
1.243 albertel 13626: logthis() : append message to the normal lonnet.log file, it gets
13627: preiodically rolled over and deleted.
1.191 harris41 13628:
13629: =item *
13630:
1.243 albertel 13631: logperm() : append a permanent message to lonnet.perm.log, this log
13632: file never gets deleted by any automated portion of the system, only
13633: messages of critical importance should go in here.
13634:
1.1119 foxr 13635:
1.243 albertel 13636: =back
13637:
13638: =head2 General File Helper Routines
13639:
13640: =over 4
1.191 harris41 13641:
13642: =item *
13643:
1.481 raeburn 13644: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13645: (a) files in /uploaded
13646: (i) If a local copy of the file exists -
13647: compares modification date of local copy with last-modified date for
13648: definitive version stored on home server for course. If local copy is
13649: stale, requests a new version from the home server and stores it.
13650: If the original has been removed from the home server, then local copy
13651: is unlinked.
13652: (ii) If local copy does not exist -
13653: requests the file from the home server and stores it.
13654:
13655: If $caller is 'uploadrep':
13656: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13657: for request for files originally uploaded via DOCS.
13658: - returns 'ok' if fresh local copy now available, -1 otherwise.
13659:
13660: Otherwise:
13661: This indicates a call from the content generation phase of the request.
13662: - returns the entire contents of the file or -1.
13663:
13664: (b) files in /res
13665: - returns the entire contents of a file or -1;
13666: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13667:
1.712 albertel 13668:
13669: =item *
13670:
13671: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13672: reference
13673:
13674: returns either a stat() list of data about the file or an empty list
13675: if the file doesn't exist or couldn't find out about it (connection
13676: problems or user unknown)
13677:
1.191 harris41 13678: =item *
13679:
1.243 albertel 13680: filelocation($dir,$file) : returns file system location of a file
13681: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13682: directory that relative $file lookups are to looked in ($dir of /a/dir
13683: and a file of ../bob will become /a/bob)
1.191 harris41 13684:
13685: =item *
13686:
13687: hreflocation($dir,$file) : returns file system location or a URL; same as
13688: filelocation except for hrefs
13689:
13690: =item *
13691:
13692: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13693:
1.243 albertel 13694: =back
13695:
1.608 albertel 13696: =head2 Usererfile file routines (/uploaded*)
13697:
13698: =over 4
13699:
13700: =item *
13701:
13702: userfileupload(): main rotine for putting a file in a user or course's
13703: filespace, arguments are,
13704:
1.620 albertel 13705: formname - required - this is the name of the element in $env where the
1.608 albertel 13706: filename, and the contents of the file to create/modifed exist
1.620 albertel 13707: the filename is in $env{'form.'.$formname.'.filename'} and the
13708: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13709: context - if coursedoc, store the file in the course of the active role
13710: of the current user;
13711: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13712: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13713: subdir - required - subdirectory to put the file in under ../userfiles/
13714: if undefined, it will be placed in "unknown"
13715:
13716: (This routine calls clean_filename() to remove any dangerous
13717: characters from the filename, and then calls finuserfileupload() to
13718: complete the transaction)
13719:
13720: returns either the url of the uploaded file (/uploaded/....) if successful
13721: and /adm/notfound.html if unsuccessful
13722:
13723: =item *
13724:
13725: clean_filename(): routine for cleaing a filename up for storage in
13726: userfile space, argument is:
13727:
13728: filename - proposed filename
13729:
13730: returns: the new clean filename
13731:
13732: =item *
13733:
1.1090 raeburn 13734: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13735: userspace, probably shouldn't be called directly
13736:
13737: docuname: username or courseid of destination for the file
13738: docudom: domain of user/course of destination for the file
13739: formname: same as for userfileupload()
1.1090 raeburn 13740: fname: filename (including subdirectories) for the file
13741: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13742: allfiles: reference to hash used to store objects found by parser
13743: codebase: reference to hash used for codebases of java objects found by parser
13744: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13745: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13746: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13747: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13748: context: if 'overwrite', will move the uploaded file from its temporary location to
13749: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13750: mimetype: reference to scalar to accommodate mime type determined
13751: from File::MMagic if $parser = parse.
1.608 albertel 13752:
13753: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13754: and /adm/notfound.html if unsuccessful (or an error message if context
13755: was 'overwrite').
13756:
1.608 albertel 13757:
13758: =item *
13759:
13760: renameuserfile(): renames an existing userfile to a new name
13761:
13762: Args:
13763: docuname: username or courseid of destination for the file
13764: docudom: domain of user/course of destination for the file
13765: old: current file name (including any subdirs under userfiles)
13766: new: desired file name (including any subdirs under userfiles)
13767:
13768: =item *
13769:
13770: mkdiruserfile(): creates a directory is a userfiles dir
13771:
13772: Args:
13773: docuname: username or courseid of destination for the file
13774: docudom: domain of user/course of destination for the file
13775: dir: dir to create (including any subdirs under userfiles)
13776:
13777: =item *
13778:
13779: removeuserfile(): removes a file that exists in userfiles
13780:
13781: Args:
13782: docuname: username or courseid of destination for the file
13783: docudom: domain of user/course of destination for the file
13784: fname: filname to delete (including any subdirs under userfiles)
13785:
13786: =item *
13787:
13788: removeuploadedurl(): convience function for removeuserfile()
13789:
13790: Args:
13791: url: a full /uploaded/... url to delete
13792:
1.747 albertel 13793: =item *
13794:
13795: get_portfile_permissions():
13796: Args:
13797: domain: domain of user or course contain the portfolio files
13798: user: name of user or num of course contain the portfolio files
13799: Returns:
13800: hashref of a dump of the proper file_permissions.db
13801:
13802:
13803: =item *
13804:
13805: get_access_controls():
13806:
13807: Args:
13808: current_permissions: the hash ref returned from get_portfile_permissions()
13809: group: (optional) the group you want the files associated with
13810: file: (optional) the file you want access info on
13811:
13812: Returns:
1.749 raeburn 13813: a hash (keys are file names) of hashes containing
13814: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13815: values are XML containing access control settings (see below)
1.747 albertel 13816:
13817: Internal notes:
13818:
1.749 raeburn 13819: access controls are stored in file_permissions.db as key=value pairs.
13820: key -> path to file/file_name\0uniqueID:scope_end_start
13821: where scope -> public,guest,course,group,domains or users.
13822: end -> UNIX time for end of access (0 -> no end date)
13823: start -> UNIX time for start of access
13824:
13825: value -> XML description of access control
13826: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13827: <start></start>
13828: <end></end>
13829:
13830: <password></password> for scope type = guest
13831:
13832: <domain></domain> for scope type = course or group
13833: <number></number>
13834: <roles id="">
13835: <role></role>
13836: <access></access>
13837: <section></section>
13838: <group></group>
13839: </roles>
13840:
13841: <dom></dom> for scope type = domains
13842:
13843: <users> for scope type = users
13844: <user>
13845: <uname></uname>
13846: <udom></udom>
13847: </user>
13848: </users>
13849: </scope>
13850:
13851: Access data is also aggregated for each file in an additional key=value pair:
13852: key -> path to file/file_name\0accesscontrol
13853: value -> reference to hash
13854: hash contains key = value pairs
13855: where key = uniqueID:scope_end_start
13856: value = UNIX time record was last updated
13857:
13858: Used to improve speed of look-ups of access controls for each file.
13859:
13860: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13861:
1.1172.2.13 raeburn 13862: =item *
13863:
1.749 raeburn 13864: modify_access_controls():
13865:
13866: Modifies access controls for a portfolio file
13867: Args
13868: 1. file name
13869: 2. reference to hash of required changes,
13870: 3. domain
13871: 4. username
13872: where domain,username are the domain of the portfolio owner
13873: (either a user or a course)
13874:
13875: Returns:
13876: 1. result of additions or updates ('ok' or 'error', with error message).
13877: 2. result of deletions ('ok' or 'error', with error message).
13878: 3. reference to hash of any new or updated access controls.
13879: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13880: key = integer (inbound ID)
1.1172.2.13 raeburn 13881: value = uniqueID
13882:
13883: =item *
13884:
13885: get_timebased_id():
13886:
13887: Attempts to get a unique timestamp-based suffix for use with items added to a
13888: course via the Course Editor (e.g., folders, composite pages,
13889: group bulletin boards).
13890:
13891: Args: (first three required; six others optional)
13892:
13893: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13894: docssequence, or name of group
13895:
13896: 2. keyid (alphanumeric): name of temporary locking key in hash,
13897: e.g., num, boardids
13898:
13899: 3. namespace: name of gdbm file used to store suffixes already assigned;
13900: file will be named nohist_namespace.db
13901:
13902: 4. cdom: domain of course; default is current course domain from %env
13903:
13904: 5. cnum: course number; default is current course number from %env
13905:
13906: 6. idtype: set to concat if an additional digit is to be appended to the
13907: unix timestamp to form the suffix, if the plain timestamp is already
13908: in use. Default is to not do this, but simply increment the unix
13909: timestamp by 1 until a unique key is obtained.
13910:
13911: 7. who: holder of locking key; defaults to user:domain for user.
13912:
13913: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13914: retrying); default is 3.
13915:
13916: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13917:
13918: Returns:
13919:
13920: 1. suffix obtained (numeric)
13921:
13922: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13923:
13924: 3. error: contains (localized) error message if an error occurred.
13925:
1.747 albertel 13926:
1.608 albertel 13927: =back
13928:
1.243 albertel 13929: =head2 HTTP Helper Routines
13930:
13931: =over 4
13932:
1.191 harris41 13933: =item *
13934:
13935: escape() : unpack non-word characters into CGI-compatible hex codes
13936:
13937: =item *
13938:
13939: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13940:
1.243 albertel 13941: =back
13942:
13943: =head1 PRIVATE SUBROUTINES
13944:
13945: =head2 Underlying communication routines (Shouldn't call)
13946:
13947: =over 4
13948:
13949: =item *
13950:
13951: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13952:
13953: =item *
13954:
13955: reply() : uses subreply to send a message to remote machine, logs all failures
13956:
13957: =item *
13958:
13959: critical() : passes a critical message to another server; if cannot
13960: get through then place message in connection buffer directory and
13961: returns con_delayed, if incapable of saving message, returns
13962: con_failed
13963:
13964: =item *
13965:
13966: reconlonc() : tries to reconnect lonc client processes.
13967:
13968: =back
13969:
13970: =head2 Resource Access Logging
13971:
13972: =over 4
13973:
13974: =item *
13975:
13976: flushcourselogs() : flush (save) buffer logs and access logs
13977:
13978: =item *
13979:
13980: courselog($what) : save message for course in hash
13981:
13982: =item *
13983:
13984: courseacclog($what) : save message for course using &courselog(). Perform
13985: special processing for specific resource types (problems, exams, quizzes, etc).
13986:
1.191 harris41 13987: =item *
13988:
13989: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13990: as a PerlChildExitHandler
1.243 albertel 13991:
13992: =back
13993:
13994: =head2 Other
13995:
13996: =over 4
13997:
13998: =item *
13999:
14000: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14001:
14002: =back
14003:
14004: =cut
1.877 foxr 14005:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>