Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1259
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1259 ! raeburn 4: # $Id: lonnet.pm,v 1.1258 2014/05/04 21:49:00 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.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
1.1083 raeburn 859: }
1.784 albertel 860:
1.1123 raeburn 861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
1.1253 raeburn 893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
1.784 albertel 904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 909: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
1.411 albertel 918: } else {
1.784 albertel 919: $load = $loadans;
1.411 albertel 920: }
1.784 albertel 921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
1.370 albertel 928: }
1.784 albertel 929: return ($spare_server,$lowest_load);
1.202 matthew 930: }
1.914 albertel 931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
1.1123 raeburn 935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
1.914 albertel 947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
1.1076 raeburn 961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
1.1259 ! raeburn 964: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 966: my %servers = &get_servers($udom);
1.1076 raeburn 967: my $lowest_load = 30000;
1.1259 ! raeburn 968: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
! 969: if ($skiploadbal) {
! 970: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
! 971: unless (defined($cached)) {
! 972: my $cachetime = 60*60*24;
! 973: my %domconfig =
! 974: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
! 975: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
! 976: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
! 977: $cachetime);
! 978: }
! 979: }
! 980: }
1.1076 raeburn 981: foreach my $lonhost (keys(%servers)) {
1.1259 ! raeburn 982: if ($skiploadbal) {
! 983: if (ref($balancers) eq 'HASH') {
! 984: next if (exists($balancers->{$lonhost}));
! 985: }
! 986: }
1.1115 raeburn 987: my $loginvia;
988: if ($checkloginvia) {
989: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 990: if ($loginvia) {
991: my ($server,$path) = split(/:/,$loginvia);
992: ($login_host, $lowest_load) =
1.1253 raeburn 993: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 994: if ($login_host eq $server) {
995: $portal_path = $path;
1.1151 raeburn 996: $isredirect = 1;
1.1116 raeburn 997: }
998: } else {
999: ($login_host, $lowest_load) =
1.1253 raeburn 1000: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1001: if ($login_host eq $lonhost) {
1002: $portal_path = '';
1.1151 raeburn 1003: $isredirect = '';
1.1116 raeburn 1004: }
1005: }
1006: } else {
1.1076 raeburn 1007: ($login_host, $lowest_load) =
1.1253 raeburn 1008: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1009: }
1010: }
1011: if ($login_host ne '') {
1.1116 raeburn 1012: $hostname = &hostname($login_host);
1.1076 raeburn 1013: }
1.1151 raeburn 1014: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1015: }
1016:
1.202 matthew 1017: # --------------------------------------------- Try to change a user's password
1018:
1019: sub changepass {
1.799 raeburn 1020: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1021: $currentpass = &escape($currentpass);
1022: $newpass = &escape($newpass);
1.1030 raeburn 1023: my $lonhost = $perlvar{'lonHostID'};
1024: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1025: $server);
1026: if (! $answer) {
1027: &logthis("No reply on password change request to $server ".
1028: "by $uname in domain $udom.");
1029: } elsif ($answer =~ "^ok") {
1030: &logthis("$uname in $udom successfully changed their password ".
1031: "on $server.");
1032: } elsif ($answer =~ "^pwchange_failure") {
1033: &logthis("$uname in $udom was unable to change their password ".
1034: "on $server. The action was blocked by either lcpasswd ".
1035: "or pwchange");
1036: } elsif ($answer =~ "^non_authorized") {
1037: &logthis("$uname in $udom did not get their password correct when ".
1038: "attempting to change it on $server.");
1039: } elsif ($answer =~ "^auth_mode_error") {
1040: &logthis("$uname in $udom attempted to change their password despite ".
1041: "not being locally or internally authenticated on $server.");
1042: } elsif ($answer =~ "^unknown_user") {
1043: &logthis("$uname in $udom attempted to change their password ".
1044: "on $server but were unable to because $server is not ".
1045: "their home server.");
1046: } elsif ($answer =~ "^refused") {
1047: &logthis("$server refused to change $uname in $udom password because ".
1048: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1049: } elsif ($answer =~ "invalid_client") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1052: }
1053: return $answer;
1.1 albertel 1054: }
1055:
1.169 harris41 1056: # ----------------------- Try to determine user's current authentication scheme
1057:
1058: sub queryauthenticate {
1059: my ($uname,$udom)=@_;
1.456 albertel 1060: my $uhome=&homeserver($uname,$udom);
1061: if (!$uhome) {
1062: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1063: return 'no_host';
1064: }
1065: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1066: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1067: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1068: }
1.456 albertel 1069: return $answer;
1.169 harris41 1070: }
1071:
1.1 albertel 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1073:
1.1 albertel 1074: sub authenticate {
1.1073 raeburn 1075: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1076: $upass=&escape($upass);
1077: $uname= &LONCAPA::clean_username($uname);
1.836 www 1078: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1079: my $newhome;
1.836 www 1080: if ((!$uhome) || ($uhome eq 'no_host')) {
1081: # Maybe the machine was offline and only re-appeared again recently?
1082: &reconlonc();
1083: # One more
1.952 raeburn 1084: $uhome=&homeserver($uname,$udom,1);
1085: if (($uhome eq 'no_host') && $checkdefauth) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $newhome=&domain($udom,'primary');
1088: }
1089: if ($newhome ne '') {
1090: $uhome = $newhome;
1091: }
1092: }
1.836 www 1093: if ((!$uhome) || ($uhome eq 'no_host')) {
1094: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1095: return 'no_host';
1096: }
1.1 albertel 1097: }
1.1073 raeburn 1098: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1099: if ($answer eq 'authorized') {
1.952 raeburn 1100: if ($newhome) {
1101: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1102: return 'no_account_on_host';
1103: } else {
1104: &logthis("User $uname at $udom authorized by $uhome");
1105: return $uhome;
1106: }
1.471 albertel 1107: }
1108: if ($answer eq 'non_authorized') {
1109: &logthis("User $uname at $udom rejected by $uhome");
1110: return 'no_host';
1.9 www 1111: }
1.471 albertel 1112: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1113: return 'no_host';
1114: }
1115:
1.1073 raeburn 1116: sub can_host_session {
1.1074 raeburn 1117: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1118: my $canhost = 1;
1.1074 raeburn 1119: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1120: if (ref($remotesessions) eq 'HASH') {
1121: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1122: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1123: $canhost = 0;
1124: } else {
1125: $canhost = 1;
1126: }
1127: }
1128: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1129: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1130: $canhost = 1;
1131: } else {
1132: $canhost = 0;
1133: }
1134: }
1135: if ($canhost) {
1136: if ($remotesessions->{'version'} ne '') {
1137: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1138: if ($reqmajor ne '' && $reqminor ne '') {
1139: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1140: my $major = $1;
1141: my $minor = $2;
1142: if (($major < $reqmajor ) ||
1143: (($major == $reqmajor) && ($minor < $reqminor))) {
1144: $canhost = 0;
1145: }
1146: } else {
1147: $canhost = 0;
1148: }
1149: }
1150: }
1151: }
1152: }
1153: if ($canhost) {
1154: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1155: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1156: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1157: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1158: if (($uint_dom ne '') &&
1159: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1160: $canhost = 0;
1161: } else {
1162: $canhost = 1;
1163: }
1164: }
1165: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1166: if (($uint_dom ne '') &&
1167: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: }
1174: }
1175: return $canhost;
1176: }
1177:
1.1083 raeburn 1178: sub spare_can_host {
1179: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1180: my $canhost=1;
1181: my @intdoms;
1182: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1183: if (ref($internet_names) eq 'ARRAY') {
1184: @intdoms = @{$internet_names};
1185: }
1186: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1187: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1188: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1189: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1190: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1191: $canhost = &can_host_session($udom,$try_server,$remoterev,
1192: $remotesessions,
1193: $defdomdefaults{'hostedsessions'});
1194: }
1195: return $canhost;
1196: }
1197:
1.1123 raeburn 1198: sub this_host_spares {
1199: my ($dom) = @_;
1.1126 raeburn 1200: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1201: my @hosts = ¤t_machine_ids();
1202: foreach my $lonhost (@hosts) {
1203: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1204: $dom_in_use = $dom;
1205: $lonhost_in_use = $lonhost;
1.1123 raeburn 1206: last;
1207: }
1208: }
1.1126 raeburn 1209: if ($dom_in_use ne '') {
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: }
1212: if (ref($result) ne 'HASH') {
1213: $lonhost_in_use = $perlvar{'lonHostID'};
1214: $dom_in_use = &host_domain($lonhost_in_use);
1215: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1216: if (ref($result) ne 'HASH') {
1217: $result = \%spareid;
1218: }
1219: }
1220: return $result;
1221: }
1222:
1223: sub spares_for_offload {
1224: my ($dom_in_use,$lonhost_in_use) = @_;
1225: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1226: if (defined($cached)) {
1227: return $result;
1228: } else {
1.1126 raeburn 1229: my $cachetime = 60*60*24;
1230: my %domconfig =
1231: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1232: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1234: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1235: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1236: }
1237: }
1238: }
1239: }
1.1126 raeburn 1240: return;
1.1123 raeburn 1241: }
1242:
1.1129 raeburn 1243: sub get_lonbalancer_config {
1244: my ($servers) = @_;
1245: my ($currbalancer,$currtargets);
1246: if (ref($servers) eq 'HASH') {
1247: foreach my $server (keys(%{$servers})) {
1248: my %what = (
1249: spareid => 1,
1250: perlvar => 1,
1251: );
1252: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1253: if ($result eq 'ok') {
1254: if (ref($returnhash) eq 'HASH') {
1255: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1256: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1257: $currbalancer = $server;
1258: $currtargets = {};
1259: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1260: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1261: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1262: }
1263: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1264: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1265: }
1266: }
1267: last;
1268: }
1269: }
1270: }
1271: }
1272: }
1273: }
1274: return ($currbalancer,$currtargets);
1275: }
1276:
1277: sub check_loadbalancing {
1278: my ($uname,$udom) = @_;
1.1191 raeburn 1279: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1280: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1281: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1282: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1283: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1284: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1285: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1286: my $serverhomedom = &host_domain($lonhost);
1287:
1288: my $cachetime = 60*60*24;
1289:
1290: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1291: $dom_in_use = $udom;
1292: $homeintdom = 1;
1293: } else {
1294: $dom_in_use = $serverhomedom;
1295: }
1296: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1297: unless (defined($cached)) {
1298: my %domconfig =
1299: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1300: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1301: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1302: }
1303: }
1304: if (ref($result) eq 'HASH') {
1.1191 raeburn 1305: ($is_balancer,$currtargets,$currrules) =
1306: &check_balancer_result($result,@hosts);
1.1129 raeburn 1307: if ($is_balancer) {
1308: if (ref($currrules) eq 'HASH') {
1309: if ($homeintdom) {
1310: if ($uname ne '') {
1311: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1312: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1313: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1314: $rule_in_effect = $currrules->{'_LC_author'};
1315: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1316: $rule_in_effect = $currrules->{'_LC_adv'}
1317: }
1318: }
1319: if ($rule_in_effect eq '') {
1320: my %userenv = &userenvironment($udom,$uname,'inststatus');
1321: if ($userenv{'inststatus'} ne '') {
1322: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1323: my ($othertitle,$usertypes,$types) =
1324: &Apache::loncommon::sorted_inst_types($udom);
1325: if (ref($types) eq 'ARRAY') {
1326: foreach my $type (@{$types}) {
1327: if (grep(/^\Q$type\E$/,@statuses)) {
1328: if (exists($currrules->{$type})) {
1329: $rule_in_effect = $currrules->{$type};
1330: }
1331: }
1332: }
1333: }
1334: } else {
1335: if (exists($currrules->{'default'})) {
1336: $rule_in_effect = $currrules->{'default'};
1337: }
1338: }
1339: }
1340: } else {
1341: if (exists($currrules->{'default'})) {
1342: $rule_in_effect = $currrules->{'default'};
1343: }
1344: }
1345: } else {
1346: if ($currrules->{'_LC_external'} ne '') {
1347: $rule_in_effect = $currrules->{'_LC_external'};
1348: }
1349: }
1350: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1351: $uname,$udom);
1352: }
1353: }
1354: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1355: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1356: unless (defined($cached)) {
1357: my %domconfig =
1358: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1359: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1360: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1361: }
1362: }
1363: if (ref($result) eq 'HASH') {
1.1191 raeburn 1364: ($is_balancer,$currtargets,$currrules) =
1365: &check_balancer_result($result,@hosts);
1366: if ($is_balancer) {
1.1129 raeburn 1367: if (ref($currrules) eq 'HASH') {
1368: if ($currrules->{'_LC_internetdom'} ne '') {
1369: $rule_in_effect = $currrules->{'_LC_internetdom'};
1370: }
1371: }
1372: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1373: $uname,$udom);
1374: }
1375: } else {
1376: if ($perlvar{'lonBalancer'} eq 'yes') {
1377: $is_balancer = 1;
1378: $offloadto = &this_host_spares($dom_in_use);
1379: }
1380: }
1381: } else {
1382: if ($perlvar{'lonBalancer'} eq 'yes') {
1383: $is_balancer = 1;
1384: $offloadto = &this_host_spares($dom_in_use);
1385: }
1386: }
1.1176 raeburn 1387: if ($is_balancer) {
1388: my $lowest_load = 30000;
1389: if (ref($offloadto) eq 'HASH') {
1390: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1391: foreach my $try_server (@{$offloadto->{'primary'}}) {
1392: ($otherserver,$lowest_load) =
1393: &compare_server_load($try_server,$otherserver,$lowest_load);
1394: }
1.1129 raeburn 1395: }
1.1176 raeburn 1396: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1397:
1.1176 raeburn 1398: if (!$found_server) {
1399: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1400: foreach my $try_server (@{$offloadto->{'default'}}) {
1401: ($otherserver,$lowest_load) =
1402: &compare_server_load($try_server,$otherserver,$lowest_load);
1403: }
1404: }
1405: }
1406: } elsif (ref($offloadto) eq 'ARRAY') {
1407: if (@{$offloadto} == 1) {
1408: $otherserver = $offloadto->[0];
1409: } elsif (@{$offloadto} > 1) {
1410: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1411: ($otherserver,$lowest_load) =
1412: &compare_server_load($try_server,$otherserver,$lowest_load);
1413: }
1414: }
1415: }
1.1176 raeburn 1416: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1417: $is_balancer = 0;
1418: if ($uname ne '' && $udom ne '') {
1419: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1420:
1421: &appenv({'user.loadbalexempt' => $lonhost,
1422: 'user.loadbalcheck.time' => time});
1423: }
1.1129 raeburn 1424: }
1425: }
1426: }
1427: return ($is_balancer,$otherserver);
1428: }
1429:
1.1191 raeburn 1430: sub check_balancer_result {
1431: my ($result,@hosts) = @_;
1432: my ($is_balancer,$currtargets,$currrules);
1433: if (ref($result) eq 'HASH') {
1434: if ($result->{'lonhost'} ne '') {
1435: my $currbalancer = $result->{'lonhost'};
1436: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1437: $is_balancer = 1;
1438: $currtargets = $result->{'targets'};
1439: $currrules = $result->{'rules'};
1440: }
1441: } else {
1442: foreach my $key (keys(%{$result})) {
1443: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1444: (ref($result->{$key}) eq 'HASH')) {
1445: $is_balancer = 1;
1446: $currrules = $result->{$key}{'rules'};
1447: $currtargets = $result->{$key}{'targets'};
1448: last;
1449: }
1450: }
1451: }
1452: }
1453: return ($is_balancer,$currtargets,$currrules);
1454: }
1455:
1.1129 raeburn 1456: sub get_loadbalancer_targets {
1457: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1458: my $offloadto;
1.1175 raeburn 1459: if ($rule_in_effect eq 'none') {
1460: return [$perlvar{'lonHostID'}];
1461: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1462: $offloadto = $currtargets;
1463: } else {
1464: if ($rule_in_effect eq 'homeserver') {
1465: my $homeserver = &homeserver($uname,$udom);
1466: if ($homeserver ne 'no_host') {
1467: $offloadto = [$homeserver];
1468: }
1469: } elsif ($rule_in_effect eq 'externalbalancer') {
1470: my %domconfig =
1471: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1472: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1473: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1474: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1475: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1476: }
1477: }
1478: } else {
1.1178 raeburn 1479: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1480: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1481: if (&hostname($remotebalancer) ne '') {
1482: $offloadto = [$remotebalancer];
1483: }
1484: }
1485: } elsif (&hostname($rule_in_effect) ne '') {
1486: $offloadto = [$rule_in_effect];
1487: }
1488: }
1489: return $offloadto;
1490: }
1491:
1.1127 raeburn 1492: sub internet_dom_servers {
1493: my ($dom) = @_;
1494: my (%uniqservers,%servers);
1495: my $primaryserver = &hostname(&domain($dom,'primary'));
1496: my @machinedoms = &machine_domains($primaryserver);
1497: foreach my $mdom (@machinedoms) {
1498: my %currservers = %servers;
1499: my %server = &get_servers($mdom);
1500: %servers = (%currservers,%server);
1501: }
1502: my %by_hostname;
1503: foreach my $id (keys(%servers)) {
1504: push(@{$by_hostname{$servers{$id}}},$id);
1505: }
1506: foreach my $hostname (sort(keys(%by_hostname))) {
1507: if (@{$by_hostname{$hostname}} > 1) {
1508: my $match = 0;
1509: foreach my $id (@{$by_hostname{$hostname}}) {
1510: if (&host_domain($id) eq $dom) {
1511: $uniqservers{$id} = $hostname;
1512: $match = 1;
1513: }
1514: }
1515: unless ($match) {
1516: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1517: }
1518: } else {
1519: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1520: }
1521: }
1522: return %uniqservers;
1523: }
1524:
1.1 albertel 1525: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1526:
1.599 albertel 1527: my %homecache;
1.1 albertel 1528: sub homeserver {
1.230 stredwic 1529: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1530: my $index="$uname:$udom";
1.426 albertel 1531:
1.599 albertel 1532: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1533:
1534: my %servers = &get_servers($udom,'library');
1535: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1536: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1537: exists($badServerCache{$tryserver}));
1.841 albertel 1538:
1539: my $answer=reply("home:$udom:$uname",$tryserver);
1540: if ($answer eq 'found') {
1541: delete($badServerCache{$tryserver});
1542: return $homecache{$index}=$tryserver;
1543: } elsif ($answer eq 'no_host') {
1544: $badServerCache{$tryserver}=1;
1545: }
1.1 albertel 1546: }
1547: return 'no_host';
1.70 www 1548: }
1549:
1550: # ------------------------------------- Find the usernames behind a list of IDs
1551:
1552: sub idget {
1553: my ($udom,@ids)=@_;
1554: my %returnhash=();
1555:
1.841 albertel 1556: my %servers = &get_servers($udom,'library');
1557: foreach my $tryserver (keys(%servers)) {
1558: my $idlist=join('&',@ids);
1559: $idlist=~tr/A-Z/a-z/;
1560: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1561: my @answer=();
1562: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1563: @answer=split(/\&/,$reply);
1564: } ;
1565: my $i;
1566: for ($i=0;$i<=$#ids;$i++) {
1567: if ($answer[$i]) {
1568: $returnhash{$ids[$i]}=$answer[$i];
1569: }
1570: }
1571: }
1.70 www 1572: return %returnhash;
1573: }
1574:
1575: # ------------------------------------- Find the IDs behind a list of usernames
1576:
1577: sub idrget {
1578: my ($udom,@unames)=@_;
1579: my %returnhash=();
1.800 albertel 1580: foreach my $uname (@unames) {
1581: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1582: }
1.70 www 1583: return %returnhash;
1584: }
1585:
1586: # ------------------------------- Store away a list of names and associated IDs
1587:
1588: sub idput {
1589: my ($udom,%ids)=@_;
1590: my %servers=();
1.800 albertel 1591: foreach my $uname (keys(%ids)) {
1592: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1593: my $uhom=&homeserver($uname,$udom);
1.70 www 1594: if ($uhom ne 'no_host') {
1.800 albertel 1595: my $id=&escape($ids{$uname});
1.70 www 1596: $id=~tr/A-Z/a-z/;
1.800 albertel 1597: my $esc_unam=&escape($uname);
1.70 www 1598: if ($servers{$uhom}) {
1.800 albertel 1599: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1600: } else {
1.800 albertel 1601: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1602: }
1603: }
1.191 harris41 1604: }
1.800 albertel 1605: foreach my $server (keys(%servers)) {
1606: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1607: }
1.344 www 1608: }
1609:
1.1231 raeburn 1610: # ---------------------------------------- Delete unwanted IDs from ids.db file
1611:
1612: sub iddel {
1613: my ($udom,$idshashref,$uhome)=@_;
1614: my %result=();
1615: unless (ref($idshashref) eq 'HASH') {
1616: return %result;
1617: }
1618: my %servers=();
1619: while (my ($id,$uname) = each(%{$idshashref})) {
1620: my $uhom;
1621: if ($uhome) {
1622: $uhom = $uhome;
1623: } else {
1624: $uhom=&homeserver($uname,$udom);
1625: }
1626: if ($uhom ne 'no_host') {
1627: if ($servers{$uhom}) {
1628: $servers{$uhom}.='&'.&escape($id);
1629: } else {
1630: $servers{$uhom}=&escape($id);
1631: }
1632: }
1633: }
1634: foreach my $server (keys(%servers)) {
1635: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1636: }
1637: return %result;
1638: }
1639:
1.1023 raeburn 1640: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1641: sub dump_dom {
1.1165 droeschl 1642: my ($namespace, $udom, $regexp) = @_;
1643:
1644: $udom ||= $env{'user.domain'};
1645:
1646: return () unless $udom;
1647:
1648: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1649: }
1650:
1.1023 raeburn 1651: # ------------------------------------------ get items from domain db files
1.806 raeburn 1652:
1653: sub get_dom {
1.860 raeburn 1654: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1655: my $items='';
1656: foreach my $item (@$storearr) {
1657: $items.=&escape($item).'&';
1658: }
1659: $items=~s/\&$//;
1.860 raeburn 1660: if (!$udom) {
1661: $udom=$env{'user.domain'};
1662: if (defined(&domain($udom,'primary'))) {
1663: $uhome=&domain($udom,'primary');
1664: } else {
1.874 albertel 1665: undef($uhome);
1.860 raeburn 1666: }
1667: } else {
1668: if (!$uhome) {
1669: if (defined(&domain($udom,'primary'))) {
1670: $uhome=&domain($udom,'primary');
1671: }
1672: }
1673: }
1674: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1675: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1676: my %returnhash;
1.875 albertel 1677: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1678: return %returnhash;
1679: }
1.806 raeburn 1680: my @pairs=split(/\&/,$rep);
1681: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1682: return @pairs;
1683: }
1684: my $i=0;
1685: foreach my $item (@$storearr) {
1686: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1687: $i++;
1688: }
1689: return %returnhash;
1690: } else {
1.880 banghart 1691: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1692: }
1693: }
1694:
1695: # -------------------------------------------- put items in domain db files
1696:
1697: sub put_dom {
1.860 raeburn 1698: my ($namespace,$storehash,$udom,$uhome)=@_;
1699: if (!$udom) {
1700: $udom=$env{'user.domain'};
1701: if (defined(&domain($udom,'primary'))) {
1702: $uhome=&domain($udom,'primary');
1703: } else {
1.874 albertel 1704: undef($uhome);
1.860 raeburn 1705: }
1706: } else {
1707: if (!$uhome) {
1708: if (defined(&domain($udom,'primary'))) {
1709: $uhome=&domain($udom,'primary');
1710: }
1711: }
1712: }
1713: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1714: my $items='';
1715: foreach my $item (keys(%$storehash)) {
1716: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1717: }
1718: $items=~s/\&$//;
1719: return &reply("putdom:$udom:$namespace:$items",$uhome);
1720: } else {
1.860 raeburn 1721: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1722: }
1723: }
1724:
1.1023 raeburn 1725: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1726: sub newput_dom {
1.1023 raeburn 1727: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1728: my $result;
1729: if (!$udom) {
1730: $udom=$env{'user.domain'};
1731: }
1.1023 raeburn 1732: if ($udom) {
1733: my $uname = &get_domainconfiguser($udom);
1734: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1735: }
1736: return $result;
1737: }
1738:
1.1023 raeburn 1739: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1740: sub del_dom {
1.1023 raeburn 1741: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1742: if (ref($storearr) eq 'ARRAY') {
1743: if (!$udom) {
1744: $udom=$env{'user.domain'};
1745: }
1.1023 raeburn 1746: if ($udom) {
1747: my $uname = &get_domainconfiguser($udom);
1748: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1749: }
1750: }
1751: }
1752:
1.1023 raeburn 1753: # ----------------------------------construct domainconfig user for a domain
1754: sub get_domainconfiguser {
1755: my ($udom) = @_;
1756: return $udom.'-domainconfig';
1757: }
1758:
1.837 raeburn 1759: sub retrieve_inst_usertypes {
1760: my ($udom) = @_;
1761: my (%returnhash,@order);
1.989 raeburn 1762: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1763: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1764: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1765: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1766: } else {
1767: if (defined(&domain($udom,'primary'))) {
1768: my $uhome=&domain($udom,'primary');
1769: my $rep=&reply("inst_usertypes:$udom",$uhome);
1770: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1771: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1772: return (\%returnhash,\@order);
1773: }
1774: my ($hashitems,$orderitems) = split(/:/,$rep);
1775: my @pairs=split(/\&/,$hashitems);
1776: foreach my $item (@pairs) {
1777: my ($key,$value)=split(/=/,$item,2);
1778: $key = &unescape($key);
1779: next if ($key =~ /^error: 2 /);
1780: $returnhash{$key}=&thaw_unescape($value);
1781: }
1782: my @esc_order = split(/\&/,$orderitems);
1783: foreach my $item (@esc_order) {
1784: push(@order,&unescape($item));
1785: }
1786: } else {
1.1256 raeburn 1787: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1788: }
1.1256 raeburn 1789: return (\%returnhash,\@order);
1.837 raeburn 1790: }
1791: }
1792:
1.868 raeburn 1793: sub is_domainimage {
1794: my ($url) = @_;
1795: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1796: if (&domain($1) ne '') {
1797: return '1';
1798: }
1799: }
1800: return;
1801: }
1802:
1.899 raeburn 1803: sub inst_directory_query {
1804: my ($srch) = @_;
1805: my $udom = $srch->{'srchdomain'};
1806: my %results;
1807: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1808: my $outcome;
1.899 raeburn 1809: if ($homeserver ne '') {
1.904 albertel 1810: my $queryid=&reply("querysend:instdirsearch:".
1811: &escape($srch->{'srchby'}).':'.
1812: &escape($srch->{'srchterm'}).':'.
1813: &escape($srch->{'srchtype'}),$homeserver);
1814: my $host=&hostname($homeserver);
1815: if ($queryid !~/^\Q$host\E\_/) {
1816: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1817: return;
1818: }
1819: my $response = &get_query_reply($queryid);
1820: my $maxtries = 5;
1821: my $tries = 1;
1822: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1823: $response = &get_query_reply($queryid);
1824: $tries ++;
1825: }
1826:
1827: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1828: if ($response eq 'unavailable') {
1829: $outcome = $response;
1830: } else {
1831: $outcome = 'ok';
1832: my @matches = split(/\n/,$response);
1833: foreach my $match (@matches) {
1834: my ($key,$value) = split(/=/,$match);
1835: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1836: }
1.899 raeburn 1837: }
1838: }
1839: }
1.909 raeburn 1840: return ($outcome,%results);
1.899 raeburn 1841: }
1842:
1843: sub usersearch {
1844: my ($srch) = @_;
1845: my $dom = $srch->{'srchdomain'};
1846: my %results;
1847: my %libserv = &all_library();
1848: my $query = 'usersearch';
1849: foreach my $tryserver (keys(%libserv)) {
1850: if (&host_domain($tryserver) eq $dom) {
1851: my $host=&hostname($tryserver);
1852: my $queryid=
1.911 raeburn 1853: &reply("querysend:".&escape($query).':'.
1854: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1855: &escape($srch->{'srchtype'}).':'.
1856: &escape($srch->{'srchterm'}),$tryserver);
1857: if ($queryid !~/^\Q$host\E\_/) {
1858: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1859: next;
1.899 raeburn 1860: }
1861: my $reply = &get_query_reply($queryid);
1862: my $maxtries = 1;
1863: my $tries = 1;
1864: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1865: $reply = &get_query_reply($queryid);
1866: $tries ++;
1867: }
1868: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1869: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1870: } else {
1.911 raeburn 1871: my @matches;
1872: if ($reply =~ /\n/) {
1873: @matches = split(/\n/,$reply);
1874: } else {
1875: @matches = split(/\&/,$reply);
1876: }
1.899 raeburn 1877: foreach my $match (@matches) {
1878: my ($uname,$udom,%userhash);
1.911 raeburn 1879: foreach my $entry (split(/:/,$match)) {
1880: my ($key,$value) =
1881: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1882: $userhash{$key} = $value;
1883: if ($key eq 'username') {
1884: $uname = $value;
1885: } elsif ($key eq 'domain') {
1886: $udom = $value;
1.911 raeburn 1887: }
1.899 raeburn 1888: }
1889: $results{$uname.':'.$udom} = \%userhash;
1890: }
1891: }
1892: }
1893: }
1894: return %results;
1895: }
1896:
1.912 raeburn 1897: sub get_instuser {
1898: my ($udom,$uname,$id) = @_;
1899: my $homeserver = &domain($udom,'primary');
1900: my ($outcome,%results);
1901: if ($homeserver ne '') {
1902: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1903: &escape($id).':'.&escape($udom),$homeserver);
1904: my $host=&hostname($homeserver);
1905: if ($queryid !~/^\Q$host\E\_/) {
1906: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1907: return;
1908: }
1909: my $response = &get_query_reply($queryid);
1910: my $maxtries = 5;
1911: my $tries = 1;
1912: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1913: $response = &get_query_reply($queryid);
1914: $tries ++;
1915: }
1916: if (!&error($response) && $response ne 'refused') {
1917: if ($response eq 'unavailable') {
1918: $outcome = $response;
1919: } else {
1920: $outcome = 'ok';
1921: my @matches = split(/\n/,$response);
1922: foreach my $match (@matches) {
1923: my ($key,$value) = split(/=/,$match);
1924: $results{&unescape($key)} = &thaw_unescape($value);
1925: }
1926: }
1927: }
1928: }
1929: my %userinfo;
1930: if (ref($results{$uname}) eq 'HASH') {
1931: %userinfo = %{$results{$uname}};
1932: }
1933: return ($outcome,%userinfo);
1934: }
1935:
1936: sub inst_rulecheck {
1.923 raeburn 1937: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1938: my %returnhash;
1939: if ($udom ne '') {
1940: if (ref($rules) eq 'ARRAY') {
1941: @{$rules} = map {&escape($_);} (@{$rules});
1942: my $rulestr = join(':',@{$rules});
1943: my $homeserver=&domain($udom,'primary');
1944: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1945: my $response;
1946: if ($item eq 'username') {
1947: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1948: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1949: $homeserver));
1.923 raeburn 1950: } elsif ($item eq 'id') {
1951: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1952: ':'.&escape($id).':'.$rulestr,
1953: $homeserver));
1.945 raeburn 1954: } elsif ($item eq 'selfcreate') {
1955: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1956: &escape($udom).':'.&escape($uname).
1957: ':'.$rulestr,$homeserver));
1.923 raeburn 1958: }
1.912 raeburn 1959: if ($response ne 'refused') {
1960: my @pairs=split(/\&/,$response);
1961: foreach my $item (@pairs) {
1962: my ($key,$value)=split(/=/,$item,2);
1963: $key = &unescape($key);
1964: next if ($key =~ /^error: 2 /);
1965: $returnhash{$key}=&thaw_unescape($value);
1966: }
1967: }
1968: }
1969: }
1970: }
1971: return %returnhash;
1972: }
1973:
1974: sub inst_userrules {
1.923 raeburn 1975: my ($udom,$check) = @_;
1.912 raeburn 1976: my (%ruleshash,@ruleorder);
1977: if ($udom ne '') {
1978: my $homeserver=&domain($udom,'primary');
1979: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1980: my $response;
1981: if ($check eq 'id') {
1982: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1983: $homeserver);
1.943 raeburn 1984: } elsif ($check eq 'email') {
1985: $response=&reply('instemailrules:'.&escape($udom),
1986: $homeserver);
1.923 raeburn 1987: } else {
1988: $response=&reply('instuserrules:'.&escape($udom),
1989: $homeserver);
1990: }
1.912 raeburn 1991: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1992: ($response ne 'unknown_cmd') &&
1.912 raeburn 1993: ($response ne 'no_such_host')) {
1994: my ($hashitems,$orderitems) = split(/:/,$response);
1995: my @pairs=split(/\&/,$hashitems);
1996: foreach my $item (@pairs) {
1997: my ($key,$value)=split(/=/,$item,2);
1998: $key = &unescape($key);
1999: next if ($key =~ /^error: 2 /);
2000: $ruleshash{$key}=&thaw_unescape($value);
2001: }
2002: my @esc_order = split(/\&/,$orderitems);
2003: foreach my $item (@esc_order) {
2004: push(@ruleorder,&unescape($item));
2005: }
2006: }
2007: }
2008: }
2009: return (\%ruleshash,\@ruleorder);
2010: }
2011:
1.976 raeburn 2012: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2013:
2014: sub get_domain_defaults {
1.1240 raeburn 2015: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2016: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2017: my $cachetime = 60*60*24;
1.1240 raeburn 2018: unless ($ignore_cache) {
2019: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2020: if (defined($cached)) {
2021: if (ref($result) eq 'HASH') {
2022: return %{$result};
2023: }
1.943 raeburn 2024: }
2025: }
2026: my %domdefaults;
2027: my %domconfig =
1.989 raeburn 2028: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2029: 'requestcourses','inststatus',
1.1183 raeburn 2030: 'coursedefaults','usersessions',
1.1258 raeburn 2031: 'requestauthor','selfenrollment',
2032: 'coursecategories'],$domain);
1.1254 raeburn 2033: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2034: if (ref($domconfig{'defaults'}) eq 'HASH') {
2035: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2036: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2037: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2038: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2039: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2040: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2041: } else {
2042: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2043: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2044: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2045: }
1.976 raeburn 2046: if (ref($domconfig{'quotas'}) eq 'HASH') {
2047: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2048: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2049: } else {
2050: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2051: }
1.1177 raeburn 2052: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2053: foreach my $item (@usertools) {
2054: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2055: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2056: }
2057: }
1.1229 raeburn 2058: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2059: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2060: }
1.976 raeburn 2061: }
1.985 raeburn 2062: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2063: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2064: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2065: }
2066: }
1.1183 raeburn 2067: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2068: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2069: }
1.989 raeburn 2070: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2071: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2072: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2073: }
2074: }
1.1047 raeburn 2075: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2076: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254 raeburn 2077: foreach my $type (@coursetypes) {
2078: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2079: unless ($type eq 'community') {
2080: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2081: }
2082: }
2083: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2084: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2085: }
1.1230 raeburn 2086: }
1.1047 raeburn 2087: }
1.1073 raeburn 2088: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2089: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2090: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2091: }
2092: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2093: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2094: }
2095: }
1.1254 raeburn 2096: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2097: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2098: my @settings = ('types','registered','enroll_dates','access_dates','section',
2099: 'approval','limit');
2100: foreach my $type (@coursetypes) {
2101: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2102: my @mgrdc = ();
2103: foreach my $item (@settings) {
2104: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2105: push(@mgrdc,$item);
2106: }
2107: }
2108: if (@mgrdc) {
2109: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2110: }
2111: }
2112: }
2113: }
2114: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2115: foreach my $type (@coursetypes) {
2116: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2117: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2118: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2119: }
2120: }
2121: }
2122: }
2123: }
1.1258 raeburn 2124: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2125: $domdefaults{'catauth'} = 'std';
2126: $domdefaults{'catunauth'} = 'std';
2127: if ($domconfig{'coursecategories'}{'auth'}) {
2128: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2129: }
2130: if ($domconfig{'coursecategories'}{'unauth'}) {
2131: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2132: }
2133: }
1.1219 raeburn 2134: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2135: return %domdefaults;
2136: }
2137:
1.344 www 2138: # --------------------------------------------------- Assign a key to a student
2139:
2140: sub assign_access_key {
1.364 www 2141: #
2142: # a valid key looks like uname:udom#comments
2143: # comments are being appended
2144: #
1.498 www 2145: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2146: $kdom=
1.620 albertel 2147: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2148: $knum=
1.620 albertel 2149: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2150: $cdom=
1.620 albertel 2151: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2152: $cnum=
1.620 albertel 2153: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2154: $udom=$env{'user.name'} unless (defined($udom));
2155: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2156: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2157: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2158: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2159: # assigned to this person
2160: # - this should not happen,
1.345 www 2161: # unless something went wrong
2162: # the first time around
2163: # ready to assign
1.364 www 2164: $logentry=$1.'; '.$logentry;
1.496 www 2165: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2166: $kdom,$knum) eq 'ok') {
1.345 www 2167: # key now belongs to user
1.346 www 2168: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2169: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2170: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2171: return 'ok';
2172: } else {
2173: return
2174: 'error: Count not permanently assign key, will need to be re-entered later.';
2175: }
2176: } else {
2177: return 'error: Could not assign key, try again later.';
2178: }
1.364 www 2179: } elsif (!$existing{$ckey}) {
1.345 www 2180: # the key does not exist
2181: return 'error: The key does not exist';
2182: } else {
2183: # the key is somebody else's
2184: return 'error: The key is already in use';
2185: }
1.344 www 2186: }
2187:
1.364 www 2188: # ------------------------------------------ put an additional comment on a key
2189:
2190: sub comment_access_key {
2191: #
2192: # a valid key looks like uname:udom#comments
2193: # comments are being appended
2194: #
2195: my ($ckey,$cdom,$cnum,$logentry)=@_;
2196: $cdom=
1.620 albertel 2197: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2198: $cnum=
1.620 albertel 2199: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2200: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2201: if ($existing{$ckey}) {
2202: $existing{$ckey}.='; '.$logentry;
2203: # ready to assign
1.367 www 2204: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2205: $cdom,$cnum) eq 'ok') {
2206: return 'ok';
2207: } else {
2208: return 'error: Count not store comment.';
2209: }
2210: } else {
2211: # the key does not exist
2212: return 'error: The key does not exist';
2213: }
2214: }
2215:
1.344 www 2216: # ------------------------------------------------------ Generate a set of keys
2217:
2218: sub generate_access_keys {
1.364 www 2219: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2220: $cdom=
1.620 albertel 2221: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2222: $cnum=
1.620 albertel 2223: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2224: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2225: unless (($cdom) && ($cnum)) { return 0; }
2226: if ($number>10000) { return 0; }
2227: sleep(2); # make sure don't get same seed twice
2228: srand(time()^($$+($$<<15))); # from "Programming Perl"
2229: my $total=0;
2230: for (my $i=1;$i<=$number;$i++) {
2231: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2232: sprintf("%lx",int(100000*rand)).'-'.
2233: sprintf("%lx",int(100000*rand));
2234: $newkey=~s/1/g/g; # folks mix up 1 and l
2235: $newkey=~s/0/h/g; # and also 0 and O
2236: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2237: if ($existing{$newkey}) {
2238: $i--;
2239: } else {
1.364 www 2240: if (&put('accesskeys',
2241: { $newkey => '# generated '.localtime().
1.620 albertel 2242: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2243: '; '.$logentry },
2244: $cdom,$cnum) eq 'ok') {
1.344 www 2245: $total++;
2246: }
2247: }
2248: }
1.620 albertel 2249: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2250: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2251: return $total;
2252: }
2253:
2254: # ------------------------------------------------------- Validate an accesskey
2255:
2256: sub validate_access_key {
2257: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2258: $cdom=
1.620 albertel 2259: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2260: $cnum=
1.620 albertel 2261: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2262: $udom=$env{'user.domain'} unless (defined($udom));
2263: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2264: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2265: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2266: }
2267:
2268: # ------------------------------------- Find the section of student in a course
1.652 albertel 2269: sub devalidate_getsection_cache {
2270: my ($udom,$unam,$courseid)=@_;
2271: my $hashid="$udom:$unam:$courseid";
2272: &devalidate_cache_new('getsection',$hashid);
2273: }
1.298 matthew 2274:
1.815 albertel 2275: sub courseid_to_courseurl {
2276: my ($courseid) = @_;
2277: #already url style courseid
2278: return $courseid if ($courseid =~ m{^/});
2279:
2280: if (exists($env{'course.'.$courseid.'.num'})) {
2281: my $cnum = $env{'course.'.$courseid.'.num'};
2282: my $cdom = $env{'course.'.$courseid.'.domain'};
2283: return "/$cdom/$cnum";
2284: }
2285:
2286: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2287: if (exists($courseinfo{'num'})) {
2288: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2289: }
2290:
2291: return undef;
2292: }
2293:
1.298 matthew 2294: sub getsection {
2295: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2296: my $cachetime=1800;
1.551 albertel 2297:
2298: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2299: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2300: if (defined($cached)) { return $result; }
2301:
1.298 matthew 2302: my %Pending;
2303: my %Expired;
2304: #
2305: # Each role can either have not started yet (pending), be active,
2306: # or have expired.
2307: #
2308: # If there is an active role, we are done.
2309: #
2310: # If there is more than one role which has not started yet,
2311: # choose the one which will start sooner
2312: # If there is one role which has not started yet, return it.
2313: #
2314: # If there is more than one expired role, choose the one which ended last.
2315: # If there is a role which has expired, return it.
2316: #
1.815 albertel 2317: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2318: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2319: foreach my $key (keys(%roleshash)) {
1.479 albertel 2320: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2321: my $section=$1;
2322: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2323: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2324: my $now=time;
1.548 albertel 2325: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2326: $Expired{$end}=$section;
2327: next;
2328: }
1.548 albertel 2329: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2330: $Pending{$start}=$section;
2331: next;
2332: }
1.599 albertel 2333: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2334: }
2335: #
2336: # Presumedly there will be few matching roles from the above
2337: # loop and the sorting time will be negligible.
2338: if (scalar(keys(%Pending))) {
2339: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2340: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2341: }
2342: if (scalar(keys(%Expired))) {
2343: my @sorted = sort {$a <=> $b} keys(%Expired);
2344: my $time = pop(@sorted);
1.599 albertel 2345: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2346: }
1.599 albertel 2347: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2348: }
1.70 www 2349:
1.599 albertel 2350: sub save_cache {
2351: &purge_remembered();
1.722 albertel 2352: #&Apache::loncommon::validate_page();
1.620 albertel 2353: undef(%env);
1.780 albertel 2354: undef($env_loaded);
1.599 albertel 2355: }
1.452 albertel 2356:
1.599 albertel 2357: my $to_remember=-1;
2358: my %remembered;
2359: my %accessed;
2360: my $kicks=0;
2361: my $hits=0;
1.849 albertel 2362: sub make_key {
2363: my ($name,$id) = @_;
1.872 albertel 2364: if (length($id) > 65
2365: && length(&escape($id)) > 200) {
2366: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2367: }
1.849 albertel 2368: return &escape($name.':'.$id);
2369: }
2370:
1.599 albertel 2371: sub devalidate_cache_new {
2372: my ($name,$id,$debug) = @_;
2373: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2374: $id=&make_key($name,$id);
1.599 albertel 2375: $memcache->delete($id);
2376: delete($remembered{$id});
2377: delete($accessed{$id});
2378: }
2379:
2380: sub is_cached_new {
2381: my ($name,$id,$debug) = @_;
1.849 albertel 2382: $id=&make_key($name,$id);
1.599 albertel 2383: if (exists($remembered{$id})) {
1.1133 foxr 2384: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2385: $accessed{$id}=[&gettimeofday()];
2386: $hits++;
2387: return ($remembered{$id},1);
2388: }
2389: my $value = $memcache->get($id);
2390: if (!(defined($value))) {
2391: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2392: return (undef,undef);
1.416 albertel 2393: }
1.599 albertel 2394: if ($value eq '__undef__') {
2395: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2396: $value=undef;
2397: }
2398: &make_room($id,$value,$debug);
2399: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2400: return ($value,1);
2401: }
2402:
2403: sub do_cache_new {
2404: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2405: $id=&make_key($name,$id);
1.599 albertel 2406: my $setvalue=$value;
2407: if (!defined($setvalue)) {
2408: $setvalue='__undef__';
2409: }
1.623 albertel 2410: if (!defined($time) ) {
2411: $time=600;
2412: }
1.599 albertel 2413: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2414: my $result = $memcache->set($id,$setvalue,$time);
2415: if (! $result) {
1.872 albertel 2416: &logthis("caching of id -> $id failed");
1.910 albertel 2417: $memcache->disconnect_all();
1.872 albertel 2418: }
1.600 albertel 2419: # need to make a copy of $value
1.919 albertel 2420: &make_room($id,$value,$debug);
1.599 albertel 2421: return $value;
2422: }
2423:
2424: sub make_room {
2425: my ($id,$value,$debug)=@_;
1.919 albertel 2426:
2427: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2428: : $value;
1.599 albertel 2429: if ($to_remember<0) { return; }
2430: $accessed{$id}=[&gettimeofday()];
2431: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2432: my $to_kick;
2433: my $max_time=0;
2434: foreach my $other (keys(%accessed)) {
2435: if (&tv_interval($accessed{$other}) > $max_time) {
2436: $to_kick=$other;
2437: $max_time=&tv_interval($accessed{$other});
2438: }
2439: }
2440: delete($remembered{$to_kick});
2441: delete($accessed{$to_kick});
2442: $kicks++;
2443: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2444: return;
2445: }
2446:
1.599 albertel 2447: sub purge_remembered {
1.604 albertel 2448: #&logthis("Tossing ".scalar(keys(%remembered)));
2449: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2450: undef(%remembered);
2451: undef(%accessed);
1.428 albertel 2452: }
1.70 www 2453: # ------------------------------------- Read an entry from a user's environment
2454:
2455: sub userenvironment {
2456: my ($udom,$unam,@what)=@_;
1.976 raeburn 2457: my $items;
2458: foreach my $item (@what) {
2459: $items.=&escape($item).'&';
2460: }
2461: $items=~s/\&$//;
1.70 www 2462: my %returnhash=();
1.1009 raeburn 2463: my $uhome = &homeserver($unam,$udom);
2464: unless ($uhome eq 'no_host') {
2465: my @answer=split(/\&/,
2466: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2467: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2468: return %returnhash;
2469: }
1.1009 raeburn 2470: my $i;
2471: for ($i=0;$i<=$#what;$i++) {
2472: $returnhash{$what[$i]}=&unescape($answer[$i]);
2473: }
1.70 www 2474: }
2475: return %returnhash;
1.1 albertel 2476: }
2477:
1.617 albertel 2478: # ---------------------------------------------------------- Get a studentphoto
2479: sub studentphoto {
2480: my ($udom,$unam,$ext) = @_;
2481: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2482: if (defined($env{'request.course.id'})) {
1.708 raeburn 2483: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2484: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2485: return(&retrievestudentphoto($udom,$unam,$ext));
2486: } else {
2487: my ($result,$perm_reqd)=
1.707 albertel 2488: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2489: if ($result eq 'ok') {
2490: if (!($perm_reqd eq 'yes')) {
2491: return(&retrievestudentphoto($udom,$unam,$ext));
2492: }
2493: }
2494: }
2495: }
2496: } else {
2497: my ($result,$perm_reqd) =
1.707 albertel 2498: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2499: if ($result eq 'ok') {
2500: if (!($perm_reqd eq 'yes')) {
2501: return(&retrievestudentphoto($udom,$unam,$ext));
2502: }
2503: }
2504: }
2505: return '/adm/lonKaputt/lonlogo_broken.gif';
2506: }
2507:
2508: sub retrievestudentphoto {
2509: my ($udom,$unam,$ext,$type) = @_;
2510: my $home=&Apache::lonnet::homeserver($unam,$udom);
2511: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2512: if ($ret eq 'ok') {
2513: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2514: if ($type eq 'thumbnail') {
2515: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2516: }
2517: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2518: return $tokenurl;
2519: } else {
2520: if ($type eq 'thumbnail') {
2521: return '/adm/lonKaputt/genericstudent_tn.gif';
2522: } else {
2523: return '/adm/lonKaputt/lonlogo_broken.gif';
2524: }
1.617 albertel 2525: }
2526: }
2527:
1.263 www 2528: # -------------------------------------------------------------------- New chat
2529:
2530: sub chatsend {
1.724 raeburn 2531: my ($newentry,$anon,$group)=@_;
1.620 albertel 2532: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2533: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2534: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2535: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2536: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2537: &escape($newentry)).':'.$group,$chome);
1.292 www 2538: }
2539:
2540: # ------------------------------------------ Find current version of a resource
2541:
2542: sub getversion {
2543: my $fname=&clutter(shift);
1.1189 raeburn 2544: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2545: return ¤tversion(&filelocation('',$fname));
2546: }
2547:
2548: sub currentversion {
2549: my $fname=shift;
2550: my $author=$fname;
2551: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2552: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2553: my $home=&homeserver($uname,$udom);
1.292 www 2554: if ($home eq 'no_host') {
2555: return -1;
2556: }
1.1112 www 2557: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2558: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2559: return -1;
2560: }
1.1112 www 2561: return $answer;
1.263 www 2562: }
2563:
1.1111 www 2564: #
2565: # Return special version number of resource if set by override, empty otherwise
2566: #
2567: sub usedversion {
2568: my $fname=shift;
2569: unless ($fname) { $fname=$env{'request.uri'}; }
2570: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2571: if ($urlversion) { return $urlversion; }
2572: return '';
2573: }
2574:
1.1 albertel 2575: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2576:
1.1 albertel 2577: sub subscribe {
2578: my $fname=shift;
1.761 raeburn 2579: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2580: $fname=~s/[\n\r]//g;
1.1 albertel 2581: my $author=$fname;
2582: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2583: my ($udom,$uname)=split(/\//,$author);
2584: my $home=homeserver($uname,$udom);
1.335 albertel 2585: if ($home eq 'no_host') {
2586: return 'not_found';
1.1 albertel 2587: }
2588: my $answer=reply("sub:$fname",$home);
1.64 www 2589: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2590: $answer.=' by '.$home;
2591: }
1.1 albertel 2592: return $answer;
2593: }
2594:
1.8 www 2595: # -------------------------------------------------------------- Replicate file
2596:
2597: sub repcopy {
2598: my $filename=shift;
1.23 www 2599: $filename=~s/\/+/\//g;
1.1142 raeburn 2600: my $londocroot = $perlvar{'lonDocRoot'};
2601: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2602: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2603: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2604: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2605: return &repcopy_userfile($filename);
2606: }
1.532 albertel 2607: $filename=~s/[\n\r]//g;
1.8 www 2608: my $transname="$filename.in.transfer";
1.828 www 2609: # FIXME: this should flock
1.607 raeburn 2610: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2611: my $remoteurl=subscribe($filename);
1.64 www 2612: if ($remoteurl =~ /^con_lost by/) {
2613: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2614: return 'unavailable';
1.8 www 2615: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2616: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2617: return 'not_found';
1.64 www 2618: } elsif ($remoteurl =~ /^rejected by/) {
2619: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2620: return 'forbidden';
1.20 www 2621: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2622: return 'ok';
1.8 www 2623: } else {
1.290 www 2624: my $author=$filename;
2625: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2626: my ($udom,$uname)=split(/\//,$author);
2627: my $home=homeserver($uname,$udom);
2628: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2629: my @parts=split(/\//,$filename);
2630: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2631: if ($path ne "$londocroot/res") {
1.8 www 2632: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2633: return 'bad_request';
1.8 www 2634: }
2635: my $count;
2636: for ($count=5;$count<$#parts;$count++) {
2637: $path.="/$parts[$count]";
2638: if ((-e $path)!=1) {
2639: mkdir($path,0777);
2640: }
2641: }
2642: my $ua=new LWP::UserAgent;
2643: my $request=new HTTP::Request('GET',"$remoteurl");
2644: my $response=$ua->request($request,$transname);
2645: if ($response->is_error()) {
2646: unlink($transname);
2647: my $message=$response->status_line;
1.672 albertel 2648: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2649: ." LWP get: $message: $filename</font>");
1.607 raeburn 2650: return 'unavailable';
1.8 www 2651: } else {
1.16 www 2652: if ($remoteurl!~/\.meta$/) {
2653: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2654: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2655: if ($mresponse->is_error()) {
2656: unlink($filename.'.meta');
2657: &logthis(
1.672 albertel 2658: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2659: }
2660: }
1.8 www 2661: rename($transname,$filename);
1.607 raeburn 2662: return 'ok';
1.8 www 2663: }
1.290 www 2664: }
1.8 www 2665: }
1.330 www 2666: }
2667:
2668: # ------------------------------------------------ Get server side include body
2669: sub ssi_body {
1.381 albertel 2670: my ($filelink,%form)=@_;
1.606 matthew 2671: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2672: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2673: }
1.953 www 2674: my $output='';
2675: my $response;
1.980 raeburn 2676: if ($filelink=~/^https?\:/) {
1.954 raeburn 2677: ($output,$response)=&externalssi($filelink);
1.953 www 2678: } else {
1.1004 droeschl 2679: $filelink .= $filelink=~/\?/ ? '&' : '?';
2680: $filelink .= 'inhibitmenu=yes';
1.953 www 2681: ($output,$response)=&ssi($filelink,%form);
2682: }
1.778 albertel 2683: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2684: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2685: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2686: if (wantarray) {
2687: return ($output, $response);
2688: } else {
2689: return $output;
2690: }
1.8 www 2691: }
2692:
1.15 www 2693: # --------------------------------------------------------- Server Side Include
2694:
1.782 albertel 2695: sub absolute_url {
2696: my ($host_name) = @_;
2697: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2698: if ($host_name eq '') {
2699: $host_name = $ENV{'SERVER_NAME'};
2700: }
2701: return $protocol.$host_name;
2702: }
2703:
1.942 foxr 2704: #
2705: # Server side include.
2706: # Parameters:
2707: # fn Possibly encrypted resource name/id.
2708: # form Hash that describes how the rendering should be done
2709: # and other things.
1.944 foxr 2710: # Returns:
1.950 raeburn 2711: # Scalar context: The content of the response.
2712: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2713: #
1.15 www 2714: sub ssi {
2715:
1.944 foxr 2716: my ($fn,%form)=@_;
1.15 www 2717: my $ua=new LWP::UserAgent;
1.23 www 2718: my $request;
1.711 albertel 2719:
2720: $form{'no_update_last_known'}=1;
1.895 albertel 2721: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2722: if (%form) {
1.782 albertel 2723: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2724: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2725: } else {
1.782 albertel 2726: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2727: }
2728:
1.15 www 2729: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2730: my $response= $ua->request($request);
1.1182 foxr 2731: my $content = $response->content;
2732:
2733:
1.944 foxr 2734: if (wantarray) {
1.1173 foxr 2735: return ($content, $response);
1.944 foxr 2736: } else {
1.1173 foxr 2737: return $content;
1.942 foxr 2738: }
1.324 www 2739: }
2740:
2741: sub externalssi {
2742: my ($url)=@_;
2743: my $ua=new LWP::UserAgent;
2744: my $request=new HTTP::Request('GET',$url);
2745: my $response=$ua->request($request);
1.954 raeburn 2746: if (wantarray) {
2747: return ($response->content, $response);
2748: } else {
2749: return $response->content;
2750: }
1.15 www 2751: }
1.254 www 2752:
1.492 albertel 2753: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2754:
2755: sub allowuploaded {
2756: my ($srcurl,$url)=@_;
2757: $url=&clutter(&declutter($url));
2758: my $dir=$url;
2759: $dir=~s/\/[^\/]+$//;
2760: my %httpref=();
2761: my $httpurl=&hreflocation('',$url);
2762: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2763: &Apache::lonnet::appenv(\%httpref);
1.254 www 2764: }
1.477 raeburn 2765:
1.1193 raeburn 2766: #
2767: # Determine if the current user should be able to edit a particular resource,
2768: # when viewing in course context.
2769: # (a) When viewing resource used to determine if "Edit" item is included in
2770: # Functions.
2771: # (b) When displaying folder contents in course editor, used to determine if
2772: # "Edit" link will be displayed alongside resource.
2773: #
1.1196 raeburn 2774: # input: six args -- filename (decluttered), course number, course domain,
2775: # url, symb (if registered) and group (if this is a group
2776: # item -- e.g., bulletin board, group page etc.).
2777: # output: array of five scalars --
1.1193 raeburn 2778: # $cfile -- url for file editing if editable on current server
2779: # $home -- homeserver of resource (i.e., for author if published,
2780: # or course if uploaded.).
2781: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2782: # $forceedit -- 1 if icon/link should be to go to edit mode
2783: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2784: #
2785:
2786: sub can_edit_resource {
1.1194 raeburn 2787: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2788: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2789: #
2790: # For aboutme pages user can only edit his/her own.
2791: #
1.1199 raeburn 2792: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2793: my ($sdom,$sname) = ($1,$2);
2794: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2795: $home = $env{'user.home'};
2796: $cfile = $resurl;
2797: if ($env{'form.forceedit'}) {
2798: $forceview = 1;
2799: } else {
2800: $forceedit = 1;
2801: }
2802: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2803: } else {
2804: return;
2805: }
2806: }
2807:
2808: if ($env{'request.course.id'}) {
2809: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2810: if ($group ne '') {
2811: # if this is a group homepage or group bulletin board, check group privs
2812: my $allowed = 0;
1.1197 raeburn 2813: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2814: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2815: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2816: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2817: $allowed = 1;
2818: }
1.1197 raeburn 2819: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2820: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2821: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2822: $allowed = 1;
2823: }
2824: }
2825: if ($allowed) {
2826: $home=&homeserver($cnum,$cdom);
2827: if ($env{'form.forceedit'}) {
2828: $forceview = 1;
2829: } else {
2830: $forceedit = 1;
2831: }
2832: $cfile = $resurl;
2833: } else {
2834: return;
2835: }
2836: } else {
1.1208 raeburn 2837: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2838: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2839: return;
2840: }
2841: } elsif (!$crsedit) {
1.1194 raeburn 2842: #
2843: # No edit allowed where CC has switched to student role.
2844: #
2845: return;
2846: }
2847: }
2848: }
2849:
1.1193 raeburn 2850: if ($file ne '') {
2851: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2852: if (&is_course_upload($file,$cnum,$cdom)) {
2853: $uploaded = 1;
2854: $incourse = 1;
1.1193 raeburn 2855: if ($file =~/\.(htm|html|css|js|txt)$/) {
2856: $cfile = &hreflocation('',$file);
1.1201 raeburn 2857: if ($env{'form.forceedit'}) {
2858: $forceview = 1;
2859: } else {
2860: $forceedit = 1;
2861: }
1.1194 raeburn 2862: }
2863: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2864: $incourse = 1;
2865: if ($env{'form.forceedit'}) {
2866: $forceview = 1;
2867: } else {
2868: $forceedit = 1;
2869: }
2870: $cfile = $resurl;
2871: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2872: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2873: $incourse = 1;
2874: if ($env{'form.forceedit'}) {
2875: $forceview = 1;
2876: } else {
2877: $forceedit = 1;
2878: }
2879: $cfile = $resurl;
1.1199 raeburn 2880: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2881: $incourse = 1;
2882: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2883: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2884: $incourse = 1;
1.1199 raeburn 2885: if ($env{'form.forceedit'}) {
2886: $forceview = 1;
2887: } else {
2888: $forceedit = 1;
2889: }
2890: $cfile = $resurl;
1.1208 raeburn 2891: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2892: $incourse = 1;
2893: if ($env{'form.forceedit'}) {
2894: $forceview = 1;
2895: } else {
2896: $forceedit = 1;
2897: }
2898: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2899: }
2900: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2901: my $template = '/res/lib/templates/simpleproblem.problem';
2902: if (&is_on_map($template)) {
2903: $incourse = 1;
2904: $forceview = 1;
2905: $cfile = $template;
1.1193 raeburn 2906: }
1.1199 raeburn 2907: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2908: $incourse = 1;
2909: if ($env{'form.forceedit'}) {
2910: $forceview = 1;
2911: } else {
2912: $forceedit = 1;
2913: }
2914: $cfile = $resurl;
2915: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2916: $incourse = 1;
2917: $forceview = 1;
2918: if ($symb) {
2919: my ($map,$id,$res)=&decode_symb($symb);
2920: $env{'request.symb'} = $symb;
2921: $cfile = &clutter($res);
2922: } else {
2923: $cfile = $env{'form.suppurl'};
2924: $cfile =~ s{^http://}{};
2925: $cfile = '/adm/wrapper/ext/'.$cfile;
2926: }
1.1234 raeburn 2927: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2928: if ($env{'form.forceedit'}) {
2929: $forceview = 1;
2930: } else {
2931: $forceedit = 1;
2932: }
2933: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2934: }
2935: }
1.1194 raeburn 2936: if ($uploaded || $incourse) {
2937: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2938: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2939: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2940: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2941: # Check that the user has permission to edit this resource
2942: my $setpriv = 1;
2943: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2944: if (defined($cfudom)) {
2945: $home=&homeserver($cfuname,$cfudom);
2946: $cfile=$file;
2947: }
2948: }
1.1194 raeburn 2949: if (($cfile ne '') && (!$incourse || $uploaded) &&
2950: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2951: my @ids=¤t_machine_ids();
2952: unless (grep(/^\Q$home\E$/,@ids)) {
2953: $switchserver=1;
2954: }
2955: }
2956: }
1.1194 raeburn 2957: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2958: }
2959:
2960: sub is_course_upload {
2961: my ($file,$cnum,$cdom) = @_;
2962: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2963: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2964: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2965: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2966: return 1;
2967: }
2968: return;
2969: }
2970:
1.1194 raeburn 2971: sub in_course {
1.1195 raeburn 2972: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2973: if ($hideprivileged) {
2974: my $skipuser;
1.1219 raeburn 2975: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2976: my @possdoms = ($cdom);
2977: if ($coursehash{'checkforpriv'}) {
2978: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2979: }
2980: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2981: $skipuser = 1;
2982: if ($coursehash{'nothideprivileged'}) {
2983: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2984: my $user;
2985: if ($item =~ /:/) {
2986: $user = $item;
2987: } else {
2988: $user = join(':',split(/[\@]/,$item));
2989: }
2990: if ($user eq $uname.':'.$udom) {
2991: undef($skipuser);
2992: last;
2993: }
2994: }
2995: }
2996: if ($skipuser) {
2997: return 0;
2998: }
2999: }
3000: }
1.1194 raeburn 3001: $type ||= 'any';
3002: if (!defined($cdom) || !defined($cnum)) {
3003: my $cid = $env{'request.course.id'};
3004: $cdom = $env{'course.'.$cid.'.domain'};
3005: $cnum = $env{'course.'.$cid.'.num'};
3006: }
3007: my $typesref;
1.1195 raeburn 3008: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3009: $typesref = ['active','previous','future'];
3010: } elsif ($type eq 'previous' || $type eq 'future') {
3011: $typesref = [$type];
3012: }
3013: my %roles = &get_my_roles($uname,$udom,'userroles',
3014: $typesref,undef,[$cdom]);
3015: my ($tmp) = keys(%roles);
3016: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3017: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3018: if (@course_roles > 0) {
3019: return 1;
3020: }
3021: return 0;
3022: }
3023:
1.478 albertel 3024: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3025: # input: action, courseID, current domain, intended
1.637 raeburn 3026: # path to file, source of file, instruction to parse file for objects,
3027: # ref to hash for embedded objects,
3028: # ref to hash for codebase of java objects.
1.1095 raeburn 3029: # reference to scalar to accommodate mime type determined
3030: # from File::MMagic if $parser = parse.
1.637 raeburn 3031: #
1.485 raeburn 3032: # output: url to file (if action was uploaddoc),
3033: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3034: #
1.478 albertel 3035: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3036: # course.
1.477 raeburn 3037: #
1.478 albertel 3038: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3039: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3040: # course's home server.
1.477 raeburn 3041: #
1.478 albertel 3042: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3043: # be copied from $source (current location) to
3044: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3045: # and will then be copied to
3046: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3047: # course's home server.
1.485 raeburn 3048: #
1.481 raeburn 3049: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3050: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3051: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3052: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3053: # in course's home server.
1.637 raeburn 3054: #
1.477 raeburn 3055:
3056: sub process_coursefile {
1.1095 raeburn 3057: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3058: $mimetype)=@_;
1.477 raeburn 3059: my $fetchresult;
1.638 albertel 3060: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3061: if ($action eq 'propagate') {
1.638 albertel 3062: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3063: $home);
1.481 raeburn 3064: } else {
1.477 raeburn 3065: my $fpath = '';
3066: my $fname = $file;
1.478 albertel 3067: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3068: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3069: my $filepath = &build_filepath($fpath);
1.481 raeburn 3070: if ($action eq 'copy') {
3071: if ($source eq '') {
3072: $fetchresult = 'no source file';
3073: return $fetchresult;
3074: } else {
3075: my $destination = $filepath.'/'.$fname;
3076: rename($source,$destination);
3077: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3078: $home);
1.481 raeburn 3079: }
3080: } elsif ($action eq 'uploaddoc') {
3081: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3082: print $fh $env{'form.'.$source};
1.481 raeburn 3083: close($fh);
1.637 raeburn 3084: if ($parser eq 'parse') {
1.1024 raeburn 3085: my $mm = new File::MMagic;
1.1095 raeburn 3086: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3087: if ($type eq 'text/html') {
1.1024 raeburn 3088: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3089: unless ($parse_result eq 'ok') {
3090: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3091: }
1.637 raeburn 3092: }
1.1095 raeburn 3093: if (ref($mimetype)) {
3094: $$mimetype = $type;
3095: }
1.637 raeburn 3096: }
1.477 raeburn 3097: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3098: $home);
1.481 raeburn 3099: if ($fetchresult eq 'ok') {
3100: return '/uploaded/'.$fpath.'/'.$fname;
3101: } else {
3102: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3103: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3104: return '/adm/notfound.html';
3105: }
1.477 raeburn 3106: }
3107: }
1.485 raeburn 3108: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3109: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3110: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3111: }
3112: return $fetchresult;
3113: }
3114:
1.637 raeburn 3115: sub build_filepath {
3116: my ($fpath) = @_;
3117: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3118: unless ($fpath eq '') {
3119: my @parts=split('/',$fpath);
3120: foreach my $part (@parts) {
3121: $filepath.= '/'.$part;
3122: if ((-e $filepath)!=1) {
3123: mkdir($filepath,0777);
3124: }
3125: }
3126: }
3127: return $filepath;
3128: }
3129:
3130: sub store_edited_file {
1.638 albertel 3131: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3132: my $file = $primary_url;
3133: $file =~ s#^/uploaded/$docudom/$docuname/##;
3134: my $fpath = '';
3135: my $fname = $file;
3136: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3137: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3138: my $filepath = &build_filepath($fpath);
3139: open(my $fh,'>'.$filepath.'/'.$fname);
3140: print $fh $content;
3141: close($fh);
1.638 albertel 3142: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3143: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3144: $home);
1.637 raeburn 3145: if ($$fetchresult eq 'ok') {
3146: return '/uploaded/'.$fpath.'/'.$fname;
3147: } else {
1.638 albertel 3148: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3149: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3150: return '/adm/notfound.html';
3151: }
3152: }
3153:
1.531 albertel 3154: sub clean_filename {
1.831 albertel 3155: my ($fname,$args)=@_;
1.315 www 3156: # Replace Windows backslashes by forward slashes
1.257 www 3157: $fname=~s/\\/\//g;
1.831 albertel 3158: if (!$args->{'keep_path'}) {
3159: # Get rid of everything but the actual filename
3160: $fname=~s/^.*\/([^\/]+)$/$1/;
3161: }
1.315 www 3162: # Replace spaces by underscores
3163: $fname=~s/\s+/\_/g;
3164: # Replace all other weird characters by nothing
1.831 albertel 3165: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3166: # Replace all .\d. sequences with _\d. so they no longer look like version
3167: # numbers
3168: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3169: return $fname;
3170: }
1.1051 raeburn 3171: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3172: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3173: # image with the same aspect ratio as the original, but with dimensions which do
3174: # not exceed $resizewidth and $resizeheight.
3175:
1.984 neumanie 3176: sub resizeImage {
1.1051 raeburn 3177: my ($img_path,$resizewidth,$resizeheight) = @_;
3178: my $ima = Image::Magick->new;
3179: my $resized;
3180: if (-e $img_path) {
3181: $ima->Read($img_path);
3182: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3183: my $width = $ima->Get('width');
3184: my $height = $ima->Get('height');
3185: if ($width > $resizewidth) {
3186: my $factor = $width/$resizewidth;
3187: my $newheight = $height/$factor;
3188: $ima->Scale(width=>$resizewidth,height=>$newheight);
3189: $resized = 1;
3190: }
3191: }
3192: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3193: my $width = $ima->Get('width');
3194: my $height = $ima->Get('height');
3195: if ($height > $resizeheight) {
3196: my $factor = $height/$resizeheight;
3197: my $newwidth = $width/$factor;
3198: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3199: $resized = 1;
3200: }
3201: }
3202: if ($resized) {
3203: $ima->Write($img_path);
3204: }
3205: }
3206: return;
1.977 amueller 3207: }
3208:
1.608 albertel 3209: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3210: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3211: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3212: # $context - possible values: coursedoc, existingfile, overwrite,
3213: # canceloverwrite, or ''.
3214: # if 'coursedoc': upload to the current course
3215: # if 'existingfile': write file to tmp/overwrites directory
3216: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3217: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3218: # $subdir - directory in userfile to store the file into
1.858 raeburn 3219: # $parser - instruction to parse file for objects ($parser = parse)
3220: # $allfiles - reference to hash for embedded objects
3221: # $codebase - reference to hash for codebase of java objects
3222: # $desuname - username for permanent storage of uploaded file
3223: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3224: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3225: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3226: # $resizewidth - width (pixels) to which to resize uploaded image
3227: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3228: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3229: # from File::MMagic.
1.858 raeburn 3230: #
1.686 albertel 3231: # output: url of file in userspace, or error: <message>
3232: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3233:
1.531 albertel 3234: sub userfileupload {
1.1090 raeburn 3235: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3236: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3237: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3238: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3239: $fname=&clean_filename($fname);
1.1090 raeburn 3240: # See if there is anything left
1.257 www 3241: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3242: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3243: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3244: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3245: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3246: my $now = time;
1.1090 raeburn 3247: my $filepath;
1.1095 raeburn 3248: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3249: $filepath = 'tmp/helprequests/'.$now;
3250: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3251: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3252: '_'.$env{'user.domain'}.'/pending';
3253: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3254: my ($docuname,$docudom);
3255: if ($destudom) {
3256: $docudom = $destudom;
3257: } else {
3258: $docudom = $env{'user.domain'};
3259: }
3260: if ($destuname) {
3261: $docuname = $destuname;
3262: } else {
3263: $docuname = $env{'user.name'};
3264: }
3265: if (exists($env{'form.group'})) {
3266: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3267: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3268: }
3269: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3270: if ($context eq 'canceloverwrite') {
3271: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3272: if (-e $tempfile) {
3273: my @info = stat($tempfile);
3274: if ($info[9] eq $env{'form.timestamp'}) {
3275: unlink($tempfile);
3276: }
3277: }
3278: return;
1.523 raeburn 3279: }
3280: }
1.1090 raeburn 3281: # Create the directory if not present
1.741 raeburn 3282: my @parts=split(/\//,$filepath);
3283: my $fullpath = $perlvar{'lonDaemons'};
3284: for (my $i=0;$i<@parts;$i++) {
3285: $fullpath .= '/'.$parts[$i];
3286: if ((-e $fullpath)!=1) {
3287: mkdir($fullpath,0777);
3288: }
3289: }
3290: open(my $fh,'>'.$fullpath.'/'.$fname);
3291: print $fh $env{'form.'.$formname};
3292: close($fh);
1.1090 raeburn 3293: if ($context eq 'existingfile') {
3294: my @info = stat($fullpath.'/'.$fname);
3295: return ($fullpath.'/'.$fname,$info[9]);
3296: } else {
3297: return $fullpath.'/'.$fname;
3298: }
1.523 raeburn 3299: }
1.995 raeburn 3300: if ($subdir eq 'scantron') {
3301: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3302: } else {
1.995 raeburn 3303: $fname="$subdir/$fname";
3304: }
1.1090 raeburn 3305: if ($context eq 'coursedoc') {
1.638 albertel 3306: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3307: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3308: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3309: return &finishuserfileupload($docuname,$docudom,
3310: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3311: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3312: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3313: } else {
1.1218 raeburn 3314: if ($env{'form.folder'}) {
3315: $fname=$env{'form.folder'}.'/'.$fname;
3316: }
1.638 albertel 3317: return &process_coursefile('uploaddoc',$docuname,$docudom,
3318: $fname,$formname,$parser,
1.1095 raeburn 3319: $allfiles,$codebase,$mimetype);
1.481 raeburn 3320: }
1.719 banghart 3321: } elsif (defined($destuname)) {
3322: my $docuname=$destuname;
3323: my $docudom=$destudom;
1.860 raeburn 3324: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3325: $parser,$allfiles,$codebase,
1.1051 raeburn 3326: $thumbwidth,$thumbheight,
1.1095 raeburn 3327: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3328: } else {
1.638 albertel 3329: my $docuname=$env{'user.name'};
3330: my $docudom=$env{'user.domain'};
1.1220 raeburn 3331: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3332: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3333: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3334: }
1.860 raeburn 3335: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3336: $parser,$allfiles,$codebase,
1.1051 raeburn 3337: $thumbwidth,$thumbheight,
1.1095 raeburn 3338: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3339: }
1.271 www 3340: }
3341:
3342: sub finishuserfileupload {
1.860 raeburn 3343: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3344: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3345: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3346: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3347:
1.860 raeburn 3348: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3349: $file=$fname;
3350: if ($fname=~m|/|) {
3351: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3352: $path.=$fnamepath.'/';
3353: }
1.259 www 3354: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3355: my $count;
3356: for ($count=4;$count<=$#parts;$count++) {
3357: $filepath.="/$parts[$count]";
3358: if ((-e $filepath)!=1) {
3359: mkdir($filepath,0777);
3360: }
3361: }
1.984 neumanie 3362:
1.258 www 3363: # Save the file
3364: {
1.701 albertel 3365: if (!open(FH,'>'.$filepath.'/'.$file)) {
3366: &logthis('Failed to create '.$filepath.'/'.$file);
3367: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3368: return '/adm/notfound.html';
3369: }
1.1090 raeburn 3370: if ($context eq 'overwrite') {
1.1117 foxr 3371: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3372: my $target = $filepath.'/'.$file;
3373: if (-e $source) {
3374: my @info = stat($source);
3375: if ($info[9] eq $env{'form.timestamp'}) {
3376: unless (&File::Copy::move($source,$target)) {
3377: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3378: return "Moving from $source failed";
3379: }
3380: } else {
3381: return "Temporary file: $source had unexpected date/time for last modification";
3382: }
3383: } else {
3384: return "Temporary file: $source missing";
3385: }
3386: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3387: &logthis('Failed to write to '.$filepath.'/'.$file);
3388: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3389: return '/adm/notfound.html';
3390: }
1.570 albertel 3391: close(FH);
1.1051 raeburn 3392: if ($resizewidth && $resizeheight) {
3393: my $mm = new File::MMagic;
3394: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3395: if ($mime_type =~ m{^image/}) {
3396: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3397: }
1.977 amueller 3398: }
1.258 www 3399: }
1.1152 raeburn 3400: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3401: if (ref($mimetype)) {
3402: if ($$mimetype eq '') {
3403: my $mm = new File::MMagic;
3404: my $type = $mm->checktype_filename($filepath.'/'.$file);
3405: $$mimetype = $type;
3406: }
3407: }
3408: }
1.637 raeburn 3409: if ($parser eq 'parse') {
1.1152 raeburn 3410: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3411: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3412: $allfiles,$codebase);
3413: unless ($parse_result eq 'ok') {
3414: &logthis('Failed to parse '.$filepath.$file.
3415: ' for embedded media: '.$parse_result);
3416: }
1.637 raeburn 3417: }
3418: }
1.860 raeburn 3419: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3420: my $input = $filepath.'/'.$file;
3421: my $output = $filepath.'/'.'tn-'.$file;
3422: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3423: system("convert -sample $thumbsize $input $output");
3424: if (-e $filepath.'/'.'tn-'.$file) {
3425: $fetchthumb = 1;
3426: }
3427: }
1.858 raeburn 3428:
1.259 www 3429: # Notify homeserver to grep it
3430: #
1.984 neumanie 3431: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3432: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3433: if ($fetchresult eq 'ok') {
1.860 raeburn 3434: if ($fetchthumb) {
3435: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3436: if ($thumbresult ne 'ok') {
3437: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3438: $docuhome.': '.$thumbresult);
3439: }
3440: }
1.259 www 3441: #
1.258 www 3442: # Return the URL to it
1.494 albertel 3443: return '/uploaded/'.$path.$file;
1.263 www 3444: } else {
1.494 albertel 3445: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3446: ': '.$fetchresult);
1.263 www 3447: return '/adm/notfound.html';
1.858 raeburn 3448: }
1.493 albertel 3449: }
3450:
1.637 raeburn 3451: sub extract_embedded_items {
1.961 raeburn 3452: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3453: my @state = ();
1.1164 raeburn 3454: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3455: my %javafiles = (
3456: codebase => '',
3457: code => '',
3458: archive => ''
3459: );
3460: my %mediafiles = (
3461: src => '',
3462: movie => '',
3463: );
1.648 raeburn 3464: my $p;
3465: if ($content) {
3466: $p = HTML::LCParser->new($content);
3467: } else {
1.961 raeburn 3468: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3469: }
1.641 albertel 3470: while (my $t=$p->get_token()) {
1.640 albertel 3471: if ($t->[0] eq 'S') {
3472: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3473: push(@state, $tagname);
1.648 raeburn 3474: if (lc($tagname) eq 'allow') {
3475: &add_filetype($allfiles,$attr->{'src'},'src');
3476: }
1.640 albertel 3477: if (lc($tagname) eq 'img') {
3478: &add_filetype($allfiles,$attr->{'src'},'src');
3479: }
1.886 albertel 3480: if (lc($tagname) eq 'a') {
1.1222 raeburn 3481: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3482: &add_filetype($allfiles,$attr->{'href'},'href');
3483: }
1.886 albertel 3484: }
1.645 raeburn 3485: if (lc($tagname) eq 'script') {
1.1164 raeburn 3486: my $src;
1.645 raeburn 3487: if ($attr->{'archive'} =~ /\.jar$/i) {
3488: &add_filetype($allfiles,$attr->{'archive'},'archive');
3489: } else {
1.1164 raeburn 3490: if ($attr->{'src'} ne '') {
3491: $src = $attr->{'src'};
3492: &add_filetype($allfiles,$src,'src');
3493: }
3494: }
3495: my $text = $p->get_trimmed_text();
3496: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3497: my @swfargs = split(/,/,$1);
3498: foreach my $item (@swfargs) {
3499: $item =~ s/["']//g;
3500: $item =~ s/^\s+//;
3501: $item =~ s/\s+$//;
3502: }
3503: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3504: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3505: push(@{$related{$swfargs[0]}},$swfargs[2]);
3506: } else {
3507: $related{$swfargs[0]} = [$swfargs[2]];
3508: }
3509: }
1.645 raeburn 3510: }
3511: }
3512: if (lc($tagname) eq 'link') {
3513: if (lc($attr->{'rel'}) eq 'stylesheet') {
3514: &add_filetype($allfiles,$attr->{'href'},'href');
3515: }
3516: }
1.640 albertel 3517: if (lc($tagname) eq 'object' ||
3518: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3519: foreach my $item (keys(%javafiles)) {
3520: $javafiles{$item} = '';
3521: }
1.1164 raeburn 3522: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3523: $lastids{lc($tagname)} = $attr->{'id'};
3524: }
1.640 albertel 3525: }
3526: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3527: my $name = lc($attr->{'name'});
3528: foreach my $item (keys(%javafiles)) {
3529: if ($name eq $item) {
3530: $javafiles{$item} = $attr->{'value'};
3531: last;
3532: }
3533: }
1.1164 raeburn 3534: my $pathfrom;
1.640 albertel 3535: foreach my $item (keys(%mediafiles)) {
3536: if ($name eq $item) {
1.1164 raeburn 3537: $pathfrom = $attr->{'value'};
3538: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3539: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3540: last;
3541: }
3542: }
1.1164 raeburn 3543: if ($name eq 'flashvars') {
3544: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3545: }
3546: if ($pathfrom ne '') {
3547: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3548: $pathfrom);
3549: }
1.640 albertel 3550: }
3551: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3552: foreach my $item (keys(%javafiles)) {
3553: if ($attr->{$item}) {
3554: $javafiles{$item} = $attr->{$item};
3555: last;
3556: }
3557: }
3558: foreach my $item (keys(%mediafiles)) {
3559: if ($attr->{$item}) {
3560: &add_filetype($allfiles,$attr->{$item},$item);
3561: last;
3562: }
3563: }
1.1164 raeburn 3564: if (lc($tagname) eq 'embed') {
3565: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3566: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3567: $attr->{'src'});
3568: }
3569: }
1.640 albertel 3570: }
1.1243 raeburn 3571: if (lc($tagname) eq 'iframe') {
3572: my $src = $attr->{'src'} ;
3573: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3574: &add_filetype($allfiles,$src,'src');
3575: } elsif ($src =~ m{^/}) {
3576: if ($env{'request.course.id'}) {
3577: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3578: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3579: my $url = &hreflocation('',$fullpath);
3580: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3581: my $relpath = $1;
3582: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3583: &add_filetype($allfiles,$1,'src');
3584: }
3585: }
3586: }
3587: }
3588: }
1.1164 raeburn 3589: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3590: pop(@state);
1.1164 raeburn 3591: }
1.640 albertel 3592: } elsif ($t->[0] eq 'E') {
3593: my ($tagname) = ($t->[1]);
3594: if ($javafiles{'codebase'} ne '') {
3595: $javafiles{'codebase'} .= '/';
3596: }
3597: if (lc($tagname) eq 'applet' ||
3598: lc($tagname) eq 'object' ||
3599: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3600: ) {
3601: foreach my $item (keys(%javafiles)) {
3602: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3603: my $file=$javafiles{'codebase'}.$javafiles{$item};
3604: &add_filetype($allfiles,$file,$item);
3605: }
3606: }
3607: }
3608: pop @state;
3609: }
3610: }
1.1164 raeburn 3611: foreach my $id (sort(keys(%flashvars))) {
3612: if ($shockwave{$id} ne '') {
3613: my @pairs = split(/\&/,$flashvars{$id});
3614: foreach my $pair (@pairs) {
3615: my ($key,$value) = split(/\=/,$pair);
3616: if ($key eq 'thumb') {
3617: &add_filetype($allfiles,$value,$key);
3618: } elsif ($key eq 'content') {
3619: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3620: my ($ext) = ($value =~ /\.([^.]+)$/);
3621: if ($ext ne '') {
3622: &add_filetype($allfiles,$path.$value,$ext);
3623: }
3624: }
3625: }
3626: }
3627: }
1.637 raeburn 3628: return 'ok';
3629: }
3630:
1.639 albertel 3631: sub add_filetype {
3632: my ($allfiles,$file,$type)=@_;
3633: if (exists($allfiles->{$file})) {
3634: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3635: push(@{$allfiles->{$file}}, &escape($type));
3636: }
3637: } else {
3638: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3639: }
3640: }
3641:
1.1164 raeburn 3642: sub embedded_dependency {
3643: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3644: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3645: if (($identifier ne '') &&
3646: (ref($related->{$identifier}) eq 'ARRAY') &&
3647: ($pathfrom ne '')) {
3648: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3649: foreach my $dep (@{$related->{$identifier}}) {
3650: &add_filetype($allfiles,$path.$dep,'object');
3651: }
3652: }
3653: }
3654: return;
3655: }
3656:
1.493 albertel 3657: sub removeuploadedurl {
1.984 neumanie 3658: my ($url)=@_;
3659: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3660: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3661: }
3662:
3663: sub removeuserfile {
3664: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3665: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3666: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3667: if ($result eq 'ok') {
1.798 raeburn 3668: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3669: my $metafile = $fname.'.meta';
3670: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3671: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3672: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3673: my $sqlresult =
1.823 albertel 3674: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3675: 'portfolio_metadata',$group,
3676: 'delete');
1.798 raeburn 3677: }
3678: }
3679: return $result;
1.257 www 3680: }
1.15 www 3681:
1.530 albertel 3682: sub mkdiruserfile {
3683: my ($docuname,$docudom,$dir)=@_;
3684: my $home=&homeserver($docuname,$docudom);
3685: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3686: }
3687:
1.531 albertel 3688: sub renameuserfile {
3689: my ($docuname,$docudom,$old,$new)=@_;
3690: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3691: my $result = &reply("renameuserfile:$docudom:$docuname:".
3692: &escape("$old").':'.&escape("$new"),$home);
3693: if ($result eq 'ok') {
3694: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3695: my $oldmeta = $old.'.meta';
3696: my $newmeta = $new.'.meta';
3697: my $metaresult =
3698: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3699: my $url = "/uploaded/$docudom/$docuname/$old";
3700: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3701: my $sqlresult =
1.823 albertel 3702: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3703: 'portfolio_metadata',$group,
3704: 'delete');
1.798 raeburn 3705: }
3706: }
3707: return $result;
1.531 albertel 3708: }
3709:
1.14 www 3710: # ------------------------------------------------------------------------- Log
3711:
3712: sub log {
3713: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3714: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3715: }
3716:
3717: # ------------------------------------------------------------------ Course Log
1.352 www 3718: #
3719: # This routine flushes several buffers of non-mission-critical nature
3720: #
1.157 www 3721:
3722: sub flushcourselogs {
1.352 www 3723: &logthis('Flushing log buffers');
3724: #
3725: # course logs
3726: # This is a log of all transactions in a course, which can be used
3727: # for data mining purposes
3728: #
3729: # It also collects the courseid database, which lists last transaction
3730: # times and course titles for all courseids
3731: #
3732: my %courseidbuffer=();
1.921 raeburn 3733: foreach my $crsid (keys(%courselogs)) {
1.352 www 3734: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3735: &escape($courselogs{$crsid}),
3736: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3737: delete $courselogs{$crsid};
3738: } else {
3739: &logthis('Failed to flush log buffer for '.$crsid);
3740: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3741: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3742: " exceeded maximum size, deleting.</font>");
3743: delete $courselogs{$crsid};
3744: }
1.352 www 3745: }
1.920 raeburn 3746: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3747: 'description' => $coursedescrbuf{$crsid},
3748: 'inst_code' => $courseinstcodebuf{$crsid},
3749: 'type' => $coursetypebuf{$crsid},
3750: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3751: };
1.191 harris41 3752: }
1.352 www 3753: #
3754: # Write course id database (reverse lookup) to homeserver of courses
3755: # Is used in pickcourse
3756: #
1.840 albertel 3757: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3758: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3759: $courseidbuffer{$crs_home},
3760: $crs_home,'timeonly');
1.352 www 3761: }
3762: #
3763: # File accesses
3764: # Writes to the dynamic metadata of resources to get hit counts, etc.
3765: #
1.449 matthew 3766: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3767: if ($entry =~ /___count$/) {
3768: my ($dom,$name);
1.807 albertel 3769: ($dom,$name,undef)=
1.811 albertel 3770: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3771: if (! defined($dom) || $dom eq '' ||
3772: ! defined($name) || $name eq '') {
1.620 albertel 3773: my $cid = $env{'request.course.id'};
3774: $dom = $env{'request.'.$cid.'.domain'};
3775: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3776: }
1.450 matthew 3777: my $value = $accesshash{$entry};
3778: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3779: my %temphash=($url => $value);
1.449 matthew 3780: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3781: if ($result eq 'ok') {
3782: delete $accesshash{$entry};
3783: }
3784: } else {
1.811 albertel 3785: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3786: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3787: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3788: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3789: delete $accesshash{$entry};
3790: }
1.185 www 3791: }
1.191 harris41 3792: }
1.352 www 3793: #
3794: # Roles
3795: # Reverse lookup of user roles for course faculty/staff and co-authorship
3796: #
1.800 albertel 3797: foreach my $entry (keys(%userrolehash)) {
1.351 www 3798: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3799: split(/\:/,$entry);
3800: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3801: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3802: $rudom,$runame) eq 'ok') {
3803: delete $userrolehash{$entry};
3804: }
3805: }
1.662 raeburn 3806: #
3807: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3808: #
3809: my %domrolebuffer = ();
1.1000 raeburn 3810: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3811: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3812: if ($domrolebuffer{$rudom}) {
3813: $domrolebuffer{$rudom}.='&'.&escape($entry).
3814: '='.&escape($domainrolehash{$entry});
3815: } else {
3816: $domrolebuffer{$rudom}.=&escape($entry).
3817: '='.&escape($domainrolehash{$entry});
3818: }
3819: delete $domainrolehash{$entry};
3820: }
3821: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3822: my %servers = &get_servers($dom,'library');
3823: foreach my $tryserver (keys(%servers)) {
3824: unless (&reply('domroleput:'.$dom.':'.
3825: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3826: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3827: }
1.662 raeburn 3828: }
3829: }
1.186 www 3830: $dumpcount++;
1.157 www 3831: }
3832:
3833: sub courselog {
3834: my $what=shift;
1.158 www 3835: $what=time.':'.$what;
1.620 albertel 3836: unless ($env{'request.course.id'}) { return ''; }
3837: $coursedombuf{$env{'request.course.id'}}=
3838: $env{'course.'.$env{'request.course.id'}.'.domain'};
3839: $coursenumbuf{$env{'request.course.id'}}=
3840: $env{'course.'.$env{'request.course.id'}.'.num'};
3841: $coursehombuf{$env{'request.course.id'}}=
3842: $env{'course.'.$env{'request.course.id'}.'.home'};
3843: $coursedescrbuf{$env{'request.course.id'}}=
3844: $env{'course.'.$env{'request.course.id'}.'.description'};
3845: $courseinstcodebuf{$env{'request.course.id'}}=
3846: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3847: $courseownerbuf{$env{'request.course.id'}}=
3848: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3849: $coursetypebuf{$env{'request.course.id'}}=
3850: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3851: if (defined $courselogs{$env{'request.course.id'}}) {
3852: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3853: } else {
1.620 albertel 3854: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3855: }
1.620 albertel 3856: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3857: &flushcourselogs();
3858: }
1.158 www 3859: }
3860:
3861: sub courseacclog {
3862: my $fnsymb=shift;
1.620 albertel 3863: unless ($env{'request.course.id'}) { return ''; }
3864: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3865: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3866: $what.=':POST';
1.583 matthew 3867: # FIXME: Probably ought to escape things....
1.800 albertel 3868: foreach my $key (keys(%env)) {
3869: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3870: my $formitem = $1;
3871: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3872: $what.=':'.$formitem.'='.$env{$key};
3873: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3874: $what.=':'.$formitem.'='.$env{$key};
3875: }
1.158 www 3876: }
1.191 harris41 3877: }
1.583 matthew 3878: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3879: # FIXME: We should not be depending on a form parameter that someone
3880: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3881: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3882: $what.= ':POST';
3883: # FIXME: Probably ought to escape things....
3884: foreach my $element ('courseexp','crsfulltext','crsrelated',
3885: 'crsdiscuss') {
1.620 albertel 3886: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3887: }
3888: }
1.158 www 3889: }
3890: &courselog($what);
1.149 www 3891: }
3892:
1.185 www 3893: sub countacc {
3894: my $url=&declutter(shift);
1.458 matthew 3895: return if (! defined($url) || $url eq '');
1.620 albertel 3896: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3897: #
3898: # Mark that this url was used in this course
3899: #
1.620 albertel 3900: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3901: #
3902: # Increase the access count for this resource in this child process
3903: #
1.281 www 3904: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3905: $accesshash{$key}++;
1.185 www 3906: }
1.349 www 3907:
1.361 www 3908: sub linklog {
3909: my ($from,$to)=@_;
3910: $from=&declutter($from);
3911: $to=&declutter($to);
3912: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3913: $accesshash{$to.'___'.$from.'___goto'}=1;
3914: }
1.1160 www 3915:
3916: sub statslog {
3917: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3918: if ($users<2) { return; }
3919: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3920: 'course' => $env{'request.course.id'},
3921: 'sections' => '"all"',
3922: 'num_students' => $users,
3923: 'part' => $part,
3924: 'symb' => $symb,
3925: 'mean_tries' => $av_attempts,
3926: 'deg_of_diff' => $degdiff});
3927: foreach my $key (keys(%dynstore)) {
3928: $accesshash{$key}=$dynstore{$key};
3929: }
3930: }
1.361 www 3931:
1.349 www 3932: sub userrolelog {
3933: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3934: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3935: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3936: $userrolehash
3937: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3938: =$tend.':'.$tstart;
1.662 raeburn 3939: }
1.1169 droeschl 3940: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3941: $userrolehash
3942: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3943: =$tend.':'.$tstart;
3944: }
1.1169 droeschl 3945: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3946: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3947: $domainrolehash
3948: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3949: = $tend.':'.$tstart;
3950: }
1.351 www 3951: }
3952:
1.957 raeburn 3953: sub courserolelog {
3954: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3955: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3956: my $cdom = $1;
3957: my $cnum = $2;
3958: my $sec = $3;
3959: my $namespace = 'rolelog';
3960: my %storehash = (
3961: role => $trole,
3962: start => $tstart,
3963: end => $tend,
3964: selfenroll => $selfenroll,
3965: context => $context,
3966: );
3967: if ($trole eq 'gr') {
3968: $namespace = 'groupslog';
3969: $storehash{'group'} = $sec;
3970: } else {
3971: $storehash{'section'} = $sec;
3972: }
1.1188 raeburn 3973: &write_log('course',$namespace,\%storehash,$delflag,$username,
3974: $domain,$cnum,$cdom);
1.1184 raeburn 3975: if (($trole ne 'st') || ($sec ne '')) {
3976: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3977: }
3978: }
3979: return;
3980: }
3981:
1.1184 raeburn 3982: sub domainrolelog {
3983: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3984: if ($area =~ m{^/($match_domain)/$}) {
3985: my $cdom = $1;
3986: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3987: my $namespace = 'rolelog';
3988: my %storehash = (
3989: role => $trole,
3990: start => $tstart,
3991: end => $tend,
3992: context => $context,
3993: );
1.1188 raeburn 3994: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3995: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3996: }
3997: return;
3998:
3999: }
4000:
4001: sub coauthorrolelog {
4002: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4003: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4004: my $audom = $1;
4005: my $auname = $2;
4006: my $namespace = 'rolelog';
4007: my %storehash = (
4008: role => $trole,
4009: start => $tstart,
4010: end => $tend,
4011: context => $context,
4012: );
1.1188 raeburn 4013: &write_log('author',$namespace,\%storehash,$delflag,$username,
4014: $domain,$auname,$audom);
1.1184 raeburn 4015: }
4016: return;
4017: }
4018:
1.351 www 4019: sub get_course_adv_roles {
1.948 raeburn 4020: my ($cid,$codes) = @_;
1.620 albertel 4021: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4022: my %coursehash=&coursedescription($cid);
1.988 raeburn 4023: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4024: my %nothide=();
1.800 albertel 4025: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4026: if ($user !~ /:/) {
4027: $nothide{join(':',split(/[\@]/,$user))}=1;
4028: } else {
4029: $nothide{$user}=1;
4030: }
1.470 www 4031: }
1.1219 raeburn 4032: my @possdoms = ($coursehash{'domain'});
4033: if ($coursehash{'checkforpriv'}) {
4034: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4035: }
1.351 www 4036: my %returnhash=();
4037: my %dumphash=
4038: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4039: my $now=time;
1.997 raeburn 4040: my %privileged;
1.1000 raeburn 4041: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4042: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4043: if (($tstart) && ($tstart<0)) { next; }
4044: if (($tend) && ($tend<$now)) { next; }
4045: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4046: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4047: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4048: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4049: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4050: if ($role eq 'cr') { next; }
1.948 raeburn 4051: if ($codes) {
4052: if ($section) { $role .= ':'.$section; }
4053: if ($returnhash{$role}) {
4054: $returnhash{$role}.=','.$username.':'.$domain;
4055: } else {
4056: $returnhash{$role}=$username.':'.$domain;
4057: }
1.351 www 4058: } else {
1.988 raeburn 4059: my $key=&plaintext($role,$crstype);
1.973 bisitz 4060: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4061: if ($returnhash{$key}) {
4062: $returnhash{$key}.=','.$username.':'.$domain;
4063: } else {
4064: $returnhash{$key}=$username.':'.$domain;
4065: }
1.351 www 4066: }
1.948 raeburn 4067: }
1.400 www 4068: return %returnhash;
4069: }
4070:
4071: sub get_my_roles {
1.937 raeburn 4072: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4073: unless (defined($uname)) { $uname=$env{'user.name'}; }
4074: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4075: my (%dumphash,%nothide);
1.1086 raeburn 4076: if ($context eq 'userroles') {
1.1166 raeburn 4077: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4078: } else {
1.1219 raeburn 4079: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4080: if ($hidepriv) {
4081: my %coursehash=&coursedescription($udom.'_'.$uname);
4082: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4083: if ($user !~ /:/) {
4084: $nothide{join(':',split(/[\@]/,$user))} = 1;
4085: } else {
4086: $nothide{$user} = 1;
4087: }
4088: }
4089: }
1.858 raeburn 4090: }
1.400 www 4091: my %returnhash=();
4092: my $now=time;
1.999 raeburn 4093: my %privileged;
1.800 albertel 4094: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4095: my ($role,$tend,$tstart);
4096: if ($context eq 'userroles') {
1.1149 raeburn 4097: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4098: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4099: } else {
4100: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4101: }
1.400 www 4102: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4103: my $status = 'active';
1.939 raeburn 4104: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4105: $status = 'previous';
4106: }
4107: if (($tstart) && ($now<$tstart)) {
4108: $status = 'future';
4109: }
4110: if (ref($types) eq 'ARRAY') {
4111: if (!grep(/^\Q$status\E$/,@{$types})) {
4112: next;
4113: }
4114: } else {
4115: if ($status ne 'active') {
4116: next;
4117: }
4118: }
1.867 raeburn 4119: my ($rolecode,$username,$domain,$section,$area);
4120: if ($context eq 'userroles') {
1.1186 raeburn 4121: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4122: (undef,$domain,$username,$section) = split(/\//,$area);
4123: } else {
4124: ($role,$username,$domain,$section) = split(/\:/,$entry);
4125: }
1.832 raeburn 4126: if (ref($roledoms) eq 'ARRAY') {
4127: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4128: next;
4129: }
4130: }
4131: if (ref($roles) eq 'ARRAY') {
4132: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4133: if ($role =~ /^cr\//) {
4134: if (!grep(/^cr$/,@{$roles})) {
4135: next;
4136: }
1.1104 raeburn 4137: } elsif ($role =~ /^gr\//) {
4138: if (!grep(/^gr$/,@{$roles})) {
4139: next;
4140: }
1.922 raeburn 4141: } else {
4142: next;
4143: }
1.832 raeburn 4144: }
1.867 raeburn 4145: }
1.937 raeburn 4146: if ($hidepriv) {
1.1219 raeburn 4147: my @privroles = ('dc','su');
1.999 raeburn 4148: if ($context eq 'userroles') {
1.1219 raeburn 4149: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4150: } else {
1.1219 raeburn 4151: my $possdoms = [$domain];
4152: if (ref($roledoms) eq 'ARRAY') {
4153: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4154: }
1.1219 raeburn 4155: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4156: if (!$nothide{$username.':'.$domain}) {
4157: next;
4158: }
4159: }
1.937 raeburn 4160: }
4161: }
1.933 raeburn 4162: if ($withsec) {
4163: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4164: $tstart.':'.$tend;
4165: } else {
4166: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4167: }
1.832 raeburn 4168: }
1.373 www 4169: return %returnhash;
1.399 www 4170: }
4171:
4172: # ----------------------------------------------------- Frontpage Announcements
4173: #
4174: #
4175:
4176: sub postannounce {
4177: my ($server,$text)=@_;
1.844 albertel 4178: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4179: unless ($text=~/\w/) { $text=''; }
4180: return &reply('setannounce:'.&escape($text),$server);
4181: }
4182:
4183: sub getannounce {
1.448 albertel 4184:
4185: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4186: my $announcement='';
1.800 albertel 4187: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4188: close($fh);
1.399 www 4189: if ($announcement=~/\w/) {
4190: return
4191: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4192: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4193: } else {
4194: return '';
4195: }
4196: } else {
4197: return '';
4198: }
1.351 www 4199: }
1.353 www 4200:
4201: # ---------------------------------------------------------- Course ID routines
4202: # Deal with domain's nohist_courseid.db files
4203: #
4204:
4205: sub courseidput {
1.921 raeburn 4206: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4207: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4208: my $outcome;
4209: if ($caller eq 'timeonly') {
4210: my $cids = '';
4211: foreach my $item (keys(%$storehash)) {
4212: $cids.=&escape($item).'&';
4213: }
4214: $cids=~s/\&$//;
4215: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4216: $coursehome);
4217: } else {
4218: my $items = '';
4219: foreach my $item (keys(%$storehash)) {
4220: $items.= &escape($item).'='.
4221: &freeze_escape($$storehash{$item}).'&';
4222: }
4223: $items=~s/\&$//;
4224: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4225: $coursehome);
1.918 raeburn 4226: }
4227: if ($outcome eq 'unknown_cmd') {
4228: my $what;
4229: foreach my $cid (keys(%$storehash)) {
4230: $what .= &escape($cid).'=';
1.921 raeburn 4231: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4232: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4233: }
4234: $what =~ s/\:$/&/;
4235: }
4236: $what =~ s/\&$//;
4237: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4238: } else {
4239: return $outcome;
4240: }
1.353 www 4241: }
4242:
4243: sub courseiddump {
1.921 raeburn 4244: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4245: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4246: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4247: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4248: $hasuniquecode)=@_;
1.918 raeburn 4249: my $as_hash = 1;
4250: my %returnhash;
4251: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4252: my %libserv = &all_library();
4253: foreach my $tryserver (keys(%libserv)) {
4254: if ( ( $hostidflag == 1
4255: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4256: || (!defined($hostidflag)) ) {
4257:
1.918 raeburn 4258: if (($domfilter eq '') ||
4259: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4260: my $rep;
4261: if (grep { $_ eq $tryserver } current_machine_ids()) {
4262: $rep = LONCAPA::Lond::dump_course_id_handler(
4263: join(":", (&host_domain($tryserver), $sincefilter,
4264: &escape($descfilter), &escape($instcodefilter),
4265: &escape($ownerfilter), &escape($coursefilter),
4266: &escape($typefilter), &escape($regexp_ok),
4267: $as_hash, &escape($selfenrollonly),
4268: &escape($catfilter), $showhidden, $caller,
4269: &escape($cloner), &escape($cc_clone), $cloneonly,
4270: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4271: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4272: } else {
4273: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4274: $sincefilter.':'.&escape($descfilter).':'.
4275: &escape($instcodefilter).':'.&escape($ownerfilter).
4276: ':'.&escape($coursefilter).':'.&escape($typefilter).
4277: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4278: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4279: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4280: &escape($cc_clone).':'.$cloneonly.':'.
4281: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4282: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4283: $tryserver);
4284: }
4285:
1.918 raeburn 4286: my @pairs=split(/\&/,$rep);
4287: foreach my $item (@pairs) {
4288: my ($key,$value)=split(/\=/,$item,2);
4289: $key = &unescape($key);
4290: next if ($key =~ /^error: 2 /);
4291: my $result = &thaw_unescape($value);
4292: if (ref($result) eq 'HASH') {
4293: $returnhash{$key}=$result;
4294: } else {
1.921 raeburn 4295: my @responses = split(/:/,$value);
4296: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4297: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4298: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4299: }
1.1008 raeburn 4300: }
1.353 www 4301: }
4302: }
4303: }
4304: }
4305: return %returnhash;
4306: }
4307:
1.1055 raeburn 4308: sub courselastaccess {
4309: my ($cdom,$cnum,$hostidref) = @_;
4310: my %returnhash;
4311: if ($cdom && $cnum) {
4312: my $chome = &homeserver($cnum,$cdom);
4313: if ($chome ne 'no_host') {
4314: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4315: &extract_lastaccess(\%returnhash,$rep);
4316: }
4317: } else {
4318: if (!$cdom) { $cdom=''; }
4319: my %libserv = &all_library();
4320: foreach my $tryserver (keys(%libserv)) {
4321: if (ref($hostidref) eq 'ARRAY') {
4322: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4323: }
4324: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4325: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4326: &extract_lastaccess(\%returnhash,$rep);
4327: }
4328: }
4329: }
4330: return %returnhash;
4331: }
4332:
4333: sub extract_lastaccess {
4334: my ($returnhash,$rep) = @_;
4335: if (ref($returnhash) eq 'HASH') {
4336: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4337: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4338: $rep eq '') {
4339: my @pairs=split(/\&/,$rep);
4340: foreach my $item (@pairs) {
4341: my ($key,$value)=split(/\=/,$item,2);
4342: $key = &unescape($key);
4343: next if ($key =~ /^error: 2 /);
4344: $returnhash->{$key} = &thaw_unescape($value);
4345: }
4346: }
4347: }
4348: return;
4349: }
4350:
1.658 raeburn 4351: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4352:
4353: sub dcmailput {
1.685 raeburn 4354: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4355: my $status = &Apache::lonnet::critical(
1.740 www 4356: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4357: &escape($message),$server);
1.662 raeburn 4358: return $status;
4359: }
4360:
1.658 raeburn 4361: sub dcmaildump {
4362: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4363: my %returnhash=();
1.846 albertel 4364:
4365: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4366: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4367: &escape($enddate).':';
4368: my @esc_senders=map { &escape($_)} @$senders;
4369: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4370: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4371: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4372: if (($key) && ($value)) {
4373: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4374: }
4375: }
4376: }
4377: return %returnhash;
4378: }
1.662 raeburn 4379: # ---------------------------------------------------------- Domain roles
4380:
4381: sub get_domain_roles {
4382: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4383: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4384: $startdate = '.';
4385: }
1.1018 raeburn 4386: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4387: $enddate = '.';
4388: }
1.922 raeburn 4389: my $rolelist;
4390: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4391: $rolelist = join('&',@{$roles});
1.922 raeburn 4392: }
1.662 raeburn 4393: my %personnel = ();
1.841 albertel 4394:
4395: my %servers = &get_servers($dom,'library');
4396: foreach my $tryserver (keys(%servers)) {
4397: %{$personnel{$tryserver}}=();
4398: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4399: &escape($startdate).':'.
4400: &escape($enddate).':'.
4401: &escape($rolelist), $tryserver))) {
4402: my ($key,$value) = split(/\=/,$line,2);
4403: if (($key) && ($value)) {
4404: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4405: }
4406: }
1.662 raeburn 4407: }
4408: return %personnel;
4409: }
1.658 raeburn 4410:
1.1057 www 4411: # ----------------------------------------------------------- Interval timing
1.149 www 4412:
1.1153 www 4413: {
4414: # Caches needed for speedup of navmaps
4415: # We don't want to cache this for very long at all (5 seconds at most)
4416: #
4417: # The user for whom we cache
4418: my $cachedkey='';
4419: # The cached times for this user
4420: my %cachedtimes=();
4421: # When this was last done
4422: my $cachedtime=();
4423:
4424: sub load_all_first_access {
1.1154 raeburn 4425: my ($uname,$udom)=@_;
1.1156 www 4426: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4427: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4428: return;
4429: }
4430: $cachedtime=time;
4431: $cachedkey=$uname.':'.$udom;
4432: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4433: }
4434:
1.504 albertel 4435: sub get_first_access {
1.1162 raeburn 4436: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4437: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4438: if ($argsymb) { $symb=$argsymb; }
4439: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4440: if ($argmap) { $map = $argmap; }
1.926 albertel 4441: if ($type eq 'course') {
4442: $res='course';
4443: } elsif ($type eq 'map') {
1.588 albertel 4444: $res=&symbread($map);
4445: } else {
4446: $res=$symb;
4447: }
1.1153 www 4448: &load_all_first_access($uname,$udom);
4449: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4450: }
4451:
4452: sub set_first_access {
1.1162 raeburn 4453: my ($type,$interval)=@_;
1.790 albertel 4454: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4455: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4456: if ($type eq 'course') {
4457: $res='course';
4458: } elsif ($type eq 'map') {
1.588 albertel 4459: $res=&symbread($map);
4460: } else {
4461: $res=$symb;
4462: }
1.1153 www 4463: $cachedkey='';
1.1162 raeburn 4464: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4465: if (!$firstaccess) {
1.1162 raeburn 4466: my $start = time;
4467: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4468: $udom,$uname);
4469: if ($putres eq 'ok') {
4470: &put('timerinterval',{"$courseid\0$res"=>$interval},
4471: $udom,$uname);
4472: &appenv(
4473: {
4474: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4475: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4476: }
4477: );
4478: }
4479: return $putres;
1.505 albertel 4480: }
4481: return 'already_set';
1.504 albertel 4482: }
1.1153 www 4483: }
1.110 www 4484: # --------------------------------------------- Set Expire Date for Spreadsheet
4485:
4486: sub expirespread {
4487: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4488: my $cid=$env{'request.course.id'};
1.110 www 4489: if ($cid) {
4490: my $now=time;
4491: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4492: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4493: $env{'course.'.$cid.'.num'}.
1.110 www 4494: ':nohist_expirationdates:'.
4495: &escape($key).'='.$now,
1.620 albertel 4496: $env{'course.'.$cid.'.home'})
1.110 www 4497: }
4498: return 'ok';
1.14 www 4499: }
4500:
1.109 www 4501: # ----------------------------------------------------- Devalidate Spreadsheets
4502:
4503: sub devalidate {
1.325 www 4504: my ($symb,$uname,$udom)=@_;
1.620 albertel 4505: my $cid=$env{'request.course.id'};
1.109 www 4506: if ($cid) {
1.391 matthew 4507: # delete the stored spreadsheets for
4508: # - the student level sheet of this user in course's homespace
4509: # - the assessment level sheet for this resource
4510: # for this user in user's homespace
1.553 albertel 4511: # - current conditional state info
1.325 www 4512: my $key=$uname.':'.$udom.':';
1.109 www 4513: my $status=
1.299 matthew 4514: &del('nohist_calculatedsheets',
1.391 matthew 4515: [$key.'studentcalc:'],
1.620 albertel 4516: $env{'course.'.$cid.'.domain'},
4517: $env{'course.'.$cid.'.num'})
1.133 albertel 4518: .' '.
4519: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4520: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4521: unless ($status eq 'ok ok') {
4522: &logthis('Could not devalidate spreadsheet '.
1.325 www 4523: $uname.' at '.$udom.' for '.
1.109 www 4524: $symb.': '.$status);
1.133 albertel 4525: }
1.553 albertel 4526: &delenv('user.state.'.$cid);
1.109 www 4527: }
4528: }
4529:
1.265 albertel 4530: sub get_scalar {
4531: my ($string,$end) = @_;
4532: my $value;
4533: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4534: $value = $1;
4535: } elsif ($$string =~ s/^([^&]*?)&//) {
4536: $value = $1;
4537: }
4538: return &unescape($value);
4539: }
4540:
4541: sub array2str {
4542: my (@array) = @_;
4543: my $result=&arrayref2str(\@array);
4544: $result=~s/^__ARRAY_REF__//;
4545: $result=~s/__END_ARRAY_REF__$//;
4546: return $result;
4547: }
4548:
1.204 albertel 4549: sub arrayref2str {
4550: my ($arrayref) = @_;
1.265 albertel 4551: my $result='__ARRAY_REF__';
1.204 albertel 4552: foreach my $elem (@$arrayref) {
1.265 albertel 4553: if(ref($elem) eq 'ARRAY') {
4554: $result.=&arrayref2str($elem).'&';
4555: } elsif(ref($elem) eq 'HASH') {
4556: $result.=&hashref2str($elem).'&';
4557: } elsif(ref($elem)) {
4558: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4559: } else {
4560: $result.=&escape($elem).'&';
4561: }
4562: }
4563: $result=~s/\&$//;
1.265 albertel 4564: $result .= '__END_ARRAY_REF__';
1.204 albertel 4565: return $result;
4566: }
4567:
1.168 albertel 4568: sub hash2str {
1.204 albertel 4569: my (%hash) = @_;
4570: my $result=&hashref2str(\%hash);
1.265 albertel 4571: $result=~s/^__HASH_REF__//;
4572: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4573: return $result;
4574: }
4575:
4576: sub hashref2str {
4577: my ($hashref)=@_;
1.265 albertel 4578: my $result='__HASH_REF__';
1.800 albertel 4579: foreach my $key (sort(keys(%$hashref))) {
4580: if (ref($key) eq 'ARRAY') {
4581: $result.=&arrayref2str($key).'=';
4582: } elsif (ref($key) eq 'HASH') {
4583: $result.=&hashref2str($key).'=';
4584: } elsif (ref($key)) {
1.265 albertel 4585: $result.='=';
1.800 albertel 4586: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4587: } else {
1.1132 raeburn 4588: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4589: }
4590:
1.800 albertel 4591: if(ref($hashref->{$key}) eq 'ARRAY') {
4592: $result.=&arrayref2str($hashref->{$key}).'&';
4593: } elsif(ref($hashref->{$key}) eq 'HASH') {
4594: $result.=&hashref2str($hashref->{$key}).'&';
4595: } elsif(ref($hashref->{$key})) {
1.265 albertel 4596: $result.='&';
1.800 albertel 4597: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4598: } else {
1.800 albertel 4599: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4600: }
4601: }
1.168 albertel 4602: $result=~s/\&$//;
1.265 albertel 4603: $result .= '__END_HASH_REF__';
1.168 albertel 4604: return $result;
4605: }
4606:
4607: sub str2hash {
1.265 albertel 4608: my ($string)=@_;
4609: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4610: return %$hash;
4611: }
4612:
4613: sub str2hashref {
1.168 albertel 4614: my ($string) = @_;
1.265 albertel 4615:
4616: my %hash;
4617:
4618: if($string !~ /^__HASH_REF__/) {
4619: if (! ($string eq '' || !defined($string))) {
4620: $hash{'error'}='Not hash reference';
4621: }
4622: return (\%hash, $string);
4623: }
4624:
4625: $string =~ s/^__HASH_REF__//;
4626:
4627: while($string !~ /^__END_HASH_REF__/) {
4628: #key
4629: my $key='';
4630: if($string =~ /^__HASH_REF__/) {
4631: ($key, $string)=&str2hashref($string);
4632: if(defined($key->{'error'})) {
4633: $hash{'error'}='Bad data';
4634: return (\%hash, $string);
4635: }
4636: } elsif($string =~ /^__ARRAY_REF__/) {
4637: ($key, $string)=&str2arrayref($string);
4638: if($key->[0] eq 'Array reference error') {
4639: $hash{'error'}='Bad data';
4640: return (\%hash, $string);
4641: }
4642: } else {
4643: $string =~ s/^(.*?)=//;
1.267 albertel 4644: $key=&unescape($1);
1.265 albertel 4645: }
4646: $string =~ s/^=//;
4647:
4648: #value
4649: my $value='';
4650: if($string =~ /^__HASH_REF__/) {
4651: ($value, $string)=&str2hashref($string);
4652: if(defined($value->{'error'})) {
4653: $hash{'error'}='Bad data';
4654: return (\%hash, $string);
4655: }
4656: } elsif($string =~ /^__ARRAY_REF__/) {
4657: ($value, $string)=&str2arrayref($string);
4658: if($value->[0] eq 'Array reference error') {
4659: $hash{'error'}='Bad data';
4660: return (\%hash, $string);
4661: }
4662: } else {
4663: $value=&get_scalar(\$string,'__END_HASH_REF__');
4664: }
4665: $string =~ s/^&//;
4666:
4667: $hash{$key}=$value;
1.204 albertel 4668: }
1.265 albertel 4669:
4670: $string =~ s/^__END_HASH_REF__//;
4671:
4672: return (\%hash, $string);
1.204 albertel 4673: }
4674:
4675: sub str2array {
1.265 albertel 4676: my ($string)=@_;
4677: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4678: return @$array;
4679: }
4680:
4681: sub str2arrayref {
1.204 albertel 4682: my ($string) = @_;
1.265 albertel 4683: my @array;
4684:
4685: if($string !~ /^__ARRAY_REF__/) {
4686: if (! ($string eq '' || !defined($string))) {
4687: $array[0]='Array reference error';
4688: }
4689: return (\@array, $string);
4690: }
4691:
4692: $string =~ s/^__ARRAY_REF__//;
4693:
4694: while($string !~ /^__END_ARRAY_REF__/) {
4695: my $value='';
4696: if($string =~ /^__HASH_REF__/) {
4697: ($value, $string)=&str2hashref($string);
4698: if(defined($value->{'error'})) {
4699: $array[0] ='Array reference error';
4700: return (\@array, $string);
4701: }
4702: } elsif($string =~ /^__ARRAY_REF__/) {
4703: ($value, $string)=&str2arrayref($string);
4704: if($value->[0] eq 'Array reference error') {
4705: $array[0] ='Array reference error';
4706: return (\@array, $string);
4707: }
4708: } else {
4709: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4710: }
4711: $string =~ s/^&//;
4712:
4713: push(@array, $value);
1.191 harris41 4714: }
1.265 albertel 4715:
4716: $string =~ s/^__END_ARRAY_REF__//;
4717:
4718: return (\@array, $string);
1.168 albertel 4719: }
4720:
1.167 albertel 4721: # -------------------------------------------------------------------Temp Store
4722:
1.168 albertel 4723: sub tmpreset {
4724: my ($symb,$namespace,$domain,$stuname) = @_;
4725: if (!$symb) {
4726: $symb=&symbread();
1.620 albertel 4727: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4728: }
4729: $symb=escape($symb);
4730:
1.620 albertel 4731: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4732: $namespace=~s/\//\_/g;
4733: $namespace=~s/\W//g;
4734:
1.620 albertel 4735: if (!$domain) { $domain=$env{'user.domain'}; }
4736: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4737: if ($domain eq 'public' && $stuname eq 'public') {
4738: $stuname=$ENV{'REMOTE_ADDR'};
4739: }
1.1117 foxr 4740: my $path=LONCAPA::tempdir();
1.168 albertel 4741: my %hash;
4742: if (tie(%hash,'GDBM_File',
4743: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4744: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4745: foreach my $key (keys(%hash)) {
1.180 albertel 4746: if ($key=~ /:$symb/) {
1.168 albertel 4747: delete($hash{$key});
4748: }
4749: }
4750: }
4751: }
4752:
1.167 albertel 4753: sub tmpstore {
1.168 albertel 4754: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4755:
4756: if (!$symb) {
4757: $symb=&symbread();
1.620 albertel 4758: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4759: }
4760: $symb=escape($symb);
4761:
4762: if (!$namespace) {
4763: # I don't think we would ever want to store this for a course.
4764: # it seems this will only be used if we don't have a course.
1.620 albertel 4765: #$namespace=$env{'request.course.id'};
1.168 albertel 4766: #if (!$namespace) {
1.620 albertel 4767: $namespace=$env{'request.state'};
1.168 albertel 4768: #}
4769: }
4770: $namespace=~s/\//\_/g;
4771: $namespace=~s/\W//g;
1.620 albertel 4772: if (!$domain) { $domain=$env{'user.domain'}; }
4773: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4774: if ($domain eq 'public' && $stuname eq 'public') {
4775: $stuname=$ENV{'REMOTE_ADDR'};
4776: }
1.168 albertel 4777: my $now=time;
4778: my %hash;
1.1117 foxr 4779: my $path=LONCAPA::tempdir();
1.168 albertel 4780: if (tie(%hash,'GDBM_File',
4781: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4782: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4783: $hash{"version:$symb"}++;
4784: my $version=$hash{"version:$symb"};
4785: my $allkeys='';
4786: foreach my $key (keys(%$storehash)) {
4787: $allkeys.=$key.':';
1.591 albertel 4788: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4789: }
4790: $hash{"$version:$symb:timestamp"}=$now;
4791: $allkeys.='timestamp';
4792: $hash{"$version:keys:$symb"}=$allkeys;
4793: if (untie(%hash)) {
4794: return 'ok';
4795: } else {
4796: return "error:$!";
4797: }
4798: } else {
4799: return "error:$!";
4800: }
4801: }
1.167 albertel 4802:
1.168 albertel 4803: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4804:
1.168 albertel 4805: sub tmprestore {
4806: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4807:
1.168 albertel 4808: if (!$symb) {
4809: $symb=&symbread();
1.620 albertel 4810: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4811: }
4812: $symb=escape($symb);
4813:
1.620 albertel 4814: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4815:
1.620 albertel 4816: if (!$domain) { $domain=$env{'user.domain'}; }
4817: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4818: if ($domain eq 'public' && $stuname eq 'public') {
4819: $stuname=$ENV{'REMOTE_ADDR'};
4820: }
1.168 albertel 4821: my %returnhash;
4822: $namespace=~s/\//\_/g;
4823: $namespace=~s/\W//g;
4824: my %hash;
1.1117 foxr 4825: my $path=LONCAPA::tempdir();
1.168 albertel 4826: if (tie(%hash,'GDBM_File',
4827: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4828: &GDBM_READER(),0640)) {
1.168 albertel 4829: my $version=$hash{"version:$symb"};
4830: $returnhash{'version'}=$version;
4831: my $scope;
4832: for ($scope=1;$scope<=$version;$scope++) {
4833: my $vkeys=$hash{"$scope:keys:$symb"};
4834: my @keys=split(/:/,$vkeys);
4835: my $key;
4836: $returnhash{"$scope:keys"}=$vkeys;
4837: foreach $key (@keys) {
1.591 albertel 4838: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4839: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4840: }
4841: }
1.168 albertel 4842: if (!(untie(%hash))) {
4843: return "error:$!";
4844: }
4845: } else {
4846: return "error:$!";
4847: }
4848: return %returnhash;
1.167 albertel 4849: }
4850:
1.9 www 4851: # ----------------------------------------------------------------------- Store
4852:
4853: sub store {
1.124 www 4854: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4855: my $home='';
4856:
1.168 albertel 4857: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4858:
1.213 www 4859: $symb=&symbclean($symb);
1.122 albertel 4860: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4861:
1.620 albertel 4862: if (!$domain) { $domain=$env{'user.domain'}; }
4863: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4864:
4865: &devalidate($symb,$stuname,$domain);
1.109 www 4866:
4867: $symb=escape($symb);
1.187 www 4868: if (!$namespace) {
1.620 albertel 4869: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4870: return '';
4871: }
4872: }
1.620 albertel 4873: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4874:
4875: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4876: $$storehash{'host'}=$perlvar{'lonHostID'};
4877:
1.12 www 4878: my $namevalue='';
1.800 albertel 4879: foreach my $key (keys(%$storehash)) {
4880: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4881: }
1.12 www 4882: $namevalue=~s/\&$//;
1.187 www 4883: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4884: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4885: }
4886:
1.47 www 4887: # -------------------------------------------------------------- Critical Store
4888:
4889: sub cstore {
1.124 www 4890: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4891: my $home='';
4892:
1.168 albertel 4893: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4894:
1.213 www 4895: $symb=&symbclean($symb);
1.122 albertel 4896: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4897:
1.620 albertel 4898: if (!$domain) { $domain=$env{'user.domain'}; }
4899: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4900:
4901: &devalidate($symb,$stuname,$domain);
1.109 www 4902:
4903: $symb=escape($symb);
1.187 www 4904: if (!$namespace) {
1.620 albertel 4905: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4906: return '';
4907: }
4908: }
1.620 albertel 4909: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4910:
4911: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4912: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4913:
1.47 www 4914: my $namevalue='';
1.800 albertel 4915: foreach my $key (keys(%$storehash)) {
4916: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4917: }
1.47 www 4918: $namevalue=~s/\&$//;
1.187 www 4919: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4920: return critical
4921: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4922: }
4923:
1.9 www 4924: # --------------------------------------------------------------------- Restore
4925:
4926: sub restore {
1.124 www 4927: my ($symb,$namespace,$domain,$stuname) = @_;
4928: my $home='';
4929:
1.168 albertel 4930: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4931:
1.122 albertel 4932: if (!$symb) {
1.1224 raeburn 4933: return if ($namespace eq 'courserequests');
4934: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4935: } else {
1.1224 raeburn 4936: unless ($namespace eq 'courserequests') {
4937: $symb=&escape(&symbclean($symb));
4938: }
1.122 albertel 4939: }
1.188 www 4940: if (!$namespace) {
1.620 albertel 4941: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4942: return '';
4943: }
4944: }
1.620 albertel 4945: if (!$domain) { $domain=$env{'user.domain'}; }
4946: if (!$stuname) { $stuname=$env{'user.name'}; }
4947: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4948: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4949:
1.12 www 4950: my %returnhash=();
1.800 albertel 4951: foreach my $line (split(/\&/,$answer)) {
4952: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4953: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4954: }
1.75 www 4955: my $version;
4956: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4957: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4958: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4959: }
1.75 www 4960: }
1.13 www 4961: return %returnhash;
1.34 www 4962: }
4963:
4964: # ---------------------------------------------------------- Course Description
1.1118 foxr 4965: #
4966: #
1.34 www 4967:
4968: sub coursedescription {
1.731 albertel 4969: my ($courseid,$args)=@_;
1.34 www 4970: $courseid=~s/^\///;
1.49 www 4971: $courseid=~s/\_/\//g;
1.34 www 4972: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4973: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4974: my $normalid=$cdomain.'_'.$cnum;
4975: # need to always cache even if we get errors otherwise we keep
4976: # trying and trying and trying to get the course description.
4977: my %envhash=();
4978: my %returnhash=();
1.731 albertel 4979:
4980: my $expiretime=600;
4981: if ($env{'request.course.id'} eq $normalid) {
4982: $expiretime=120;
4983: }
4984:
4985: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4986: if (!$args->{'freshen_cache'}
4987: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4988: foreach my $key (keys(%env)) {
4989: next if ($key !~ /^\Q$prefix\E(.*)/);
4990: my ($setting) = $1;
4991: $returnhash{$setting} = $env{$key};
4992: }
4993: return %returnhash;
4994: }
4995:
1.1118 foxr 4996: # get the data again
4997:
1.731 albertel 4998: if (!$args->{'one_time'}) {
4999: $envhash{'course.'.$normalid.'.last_cache'}=time;
5000: }
1.811 albertel 5001:
1.34 www 5002: if ($chome ne 'no_host') {
1.302 albertel 5003: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5004: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5005: my $username = $env{'user.name'}; # Defult username
5006: if(defined $args->{'user'}) {
5007: $username = $args->{'user'};
5008: }
1.129 albertel 5009: $returnhash{'home'}= $chome;
5010: $returnhash{'domain'} = $cdomain;
5011: $returnhash{'num'} = $cnum;
1.741 raeburn 5012: if (!defined($returnhash{'type'})) {
5013: $returnhash{'type'} = 'Course';
5014: }
1.130 albertel 5015: while (my ($name,$value) = each %returnhash) {
1.53 www 5016: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5017: }
1.270 www 5018: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5019: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5020: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5021: $envhash{'course.'.$normalid.'.home'}=$chome;
5022: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5023: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5024: }
5025: }
1.731 albertel 5026: if (!$args->{'one_time'}) {
1.949 raeburn 5027: &appenv(\%envhash);
1.731 albertel 5028: }
1.302 albertel 5029: return %returnhash;
1.461 www 5030: }
5031:
1.1080 raeburn 5032: sub update_released_required {
5033: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5034: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5035: $cid = $env{'request.course.id'};
5036: $cdom = $env{'course.'.$cid.'.domain'};
5037: $cnum = $env{'course.'.$cid.'.num'};
5038: $chome = $env{'course.'.$cid.'.home'};
5039: }
5040: if ($needsrelease) {
5041: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5042: my $needsupdate;
5043: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5044: $needsupdate = 1;
5045: } else {
5046: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5047: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5048: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5049: $needsupdate = 1;
5050: }
5051: }
5052: if ($needsupdate) {
5053: my %needshash = (
5054: 'internal.releaserequired' => $needsrelease,
5055: );
5056: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5057: if ($putresult eq 'ok') {
5058: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5059: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5060: if (ref($crsinfo{$cid}) eq 'HASH') {
5061: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5062: &courseidput($cdom,\%crsinfo,$chome,'notime');
5063: }
5064: }
5065: }
5066: }
5067: return;
5068: }
5069:
1.461 www 5070: # -------------------------------------------------See if a user is privileged
5071:
5072: sub privileged {
1.1219 raeburn 5073: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5074: my $now = time;
1.1219 raeburn 5075: my $roles;
5076: if (ref($possroles) eq 'ARRAY') {
5077: $roles = $possroles;
5078: } else {
5079: $roles = ['dc','su'];
5080: }
5081: if (ref($possdomains) eq 'ARRAY') {
5082: my %privileged = &privileged_by_domain($possdomains,$roles);
5083: foreach my $dom (@{$possdomains}) {
5084: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5085: (ref($privileged{$dom}) eq 'HASH')) {
5086: foreach my $role (@{$roles}) {
5087: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5088: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5089: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5090: return 1 unless (($end && $end < $now) ||
5091: ($start && $start > $now));
5092: }
5093: }
5094: }
5095: }
5096: }
5097: } else {
5098: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5099: my $now = time;
1.1170 droeschl 5100:
1.1219 raeburn 5101: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5102: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5103: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5104: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5105: or ($tstart && $tstart > $now);
1.1170 droeschl 5106: }
1.1219 raeburn 5107: }
5108: }
5109: return 0;
5110: }
1.1170 droeschl 5111:
1.1219 raeburn 5112: sub privileged_by_domain {
5113: my ($domains,$roles) = @_;
5114: my %privileged = ();
5115: my $cachetime = 60*60*24;
5116: my $now = time;
5117: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5118: return %privileged;
5119: }
5120: foreach my $dom (@{$domains}) {
5121: next if (ref($privileged{$dom}) eq 'HASH');
5122: my $needroles;
5123: foreach my $role (@{$roles}) {
5124: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5125: if (defined($cached)) {
5126: if (ref($result) eq 'HASH') {
5127: $privileged{$dom}{$role} = $result;
5128: }
5129: } else {
5130: $needroles = 1;
5131: }
5132: }
5133: if ($needroles) {
5134: my %dompersonnel = &get_domain_roles($dom,$roles);
5135: $privileged{$dom} = {};
5136: foreach my $server (keys(%dompersonnel)) {
5137: if (ref($dompersonnel{$server}) eq 'HASH') {
5138: foreach my $item (keys(%{$dompersonnel{$server}})) {
5139: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5140: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5141: next if ($end && $end < $now);
5142: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5143: $dompersonnel{$server}{$item};
5144: }
5145: }
5146: }
5147: if (ref($privileged{$dom}) eq 'HASH') {
5148: foreach my $role (@{$roles}) {
5149: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5150: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5151: } else {
5152: my %hash = ();
5153: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5154: }
5155: }
5156: }
5157: }
5158: }
5159: return %privileged;
1.9 www 5160: }
1.1 albertel 5161:
1.103 harris41 5162: # -------------------------------------------------------- Get user privileges
1.11 www 5163:
5164: sub rolesinit {
1.1169 droeschl 5165: my ($domain, $username) = @_;
5166: my %userroles = ('user.login.time' => time);
5167: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5168:
5169: # firstaccess and timerinterval are related to timed maps/resources.
5170: # also, blocking can be triggered by an activating timer
5171: # it's saved in the user's %env.
5172: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5173: my %timerinterval = &dump('timerinterval', $domain, $username);
5174: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5175: %timerintchk, %timerintenv);
5176:
1.1162 raeburn 5177: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5178: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5179: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5180: }
1.1169 droeschl 5181:
1.1162 raeburn 5182: foreach my $key (keys(%timerinterval)) {
5183: my ($cid,$rest) = split(/\0/,$key);
5184: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5185: }
1.1169 droeschl 5186:
1.11 www 5187: my %allroles=();
1.1162 raeburn 5188: my %allgroups=();
1.11 www 5189:
1.1169 droeschl 5190: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5191: my $role = $rolesdump{$area};
5192: $area =~ s/\_\w\w$//;
5193:
5194: my ($trole, $tend, $tstart, $group_privs);
5195:
5196: if ($role =~ /^cr/) {
5197: # Custom role, defined by a user
5198: # e.g., user.role.cr/msu/smith/mynewrole
5199: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5200: $trole = $1;
5201: ($tend, $tstart) = split('_', $2);
5202: } else {
5203: $trole = $role;
5204: }
5205: } elsif ($role =~ m|^gr/|) {
5206: # Role of member in a group, defined within a course/community
5207: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5208: ($trole, $tend, $tstart) = split(/_/, $role);
5209: next if $tstart eq '-1';
5210: ($trole, $group_privs) = split(/\//, $trole);
5211: $group_privs = &unescape($group_privs);
5212: } else {
5213: # Just a normal role, defined in roles.tab
5214: ($trole, $tend, $tstart) = split(/_/,$role);
5215: }
5216:
5217: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5218: $username);
5219: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5220:
5221: # role expired or not available yet?
5222: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5223: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5224:
5225: next if $area eq '' or $trole eq '';
5226:
5227: my $spec = "$trole.$area";
5228: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5229:
5230: if ($trole =~ /^cr\//) {
5231: # Custom role, defined by a user
5232: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5233: } elsif ($trole eq 'gr') {
5234: # Role of a member in a group, defined within a course/community
5235: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5236: next;
5237: } else {
5238: # Normal role, defined in roles.tab
5239: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5240: }
5241:
5242: my $cid = $tdomain.'_'.$trest;
5243: unless ($firstaccchk{$cid}) {
5244: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5245: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5246: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5247: $coursetimerstarts{$cid}{$item};
5248: }
5249: }
5250: $firstaccchk{$cid} = 1;
5251: }
5252: unless ($timerintchk{$cid}) {
5253: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5254: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5255: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5256: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5257: }
1.12 www 5258: }
1.1169 droeschl 5259: $timerintchk{$cid} = 1;
1.191 harris41 5260: }
1.11 www 5261: }
1.1169 droeschl 5262:
5263: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5264: \%allroles, \%allgroups);
5265: $env{'user.adv'} = $userroles{'user.adv'};
5266:
1.1162 raeburn 5267: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5268: }
5269:
1.567 raeburn 5270: sub set_arearole {
1.1215 raeburn 5271: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5272: unless ($nolog) {
1.567 raeburn 5273: # log the associated role with the area
1.1215 raeburn 5274: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5275: }
1.743 albertel 5276: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5277: }
5278:
5279: sub custom_roleprivs {
5280: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5281: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5282: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5283: if (&hostname($homsvr) ne '') {
1.567 raeburn 5284: my ($rdummy,$roledef)=
5285: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5286: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5287: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5288: if (defined($syspriv)) {
1.1043 raeburn 5289: if ($trest =~ /^$match_community$/) {
5290: $syspriv =~ s/bre\&S//;
5291: }
1.567 raeburn 5292: $$allroles{'cm./'}.=':'.$syspriv;
5293: $$allroles{$spec.'./'}.=':'.$syspriv;
5294: }
5295: if ($tdomain ne '') {
5296: if (defined($dompriv)) {
5297: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5298: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5299: }
5300: if (($trest ne '') && (defined($coursepriv))) {
5301: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5302: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5303: }
5304: }
5305: }
5306: }
5307: }
5308:
1.678 raeburn 5309: sub group_roleprivs {
5310: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5311: my $access = 1;
5312: my $now = time;
5313: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5314: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5315: if ($access) {
1.811 albertel 5316: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5317: $$allgroups{$course}{$group} .=':'.$group_privs;
5318: }
5319: }
1.567 raeburn 5320:
5321: sub standard_roleprivs {
5322: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5323: if (defined($pr{$trole.':s'})) {
5324: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5325: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5326: }
5327: if ($tdomain ne '') {
5328: if (defined($pr{$trole.':d'})) {
5329: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5330: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5331: }
5332: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5333: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5334: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5335: }
5336: }
5337: }
5338:
5339: sub set_userprivs {
1.1064 raeburn 5340: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5341: my $author=0;
5342: my $adv=0;
1.678 raeburn 5343: my %grouproles = ();
5344: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5345: my @groupkeys;
1.1000 raeburn 5346: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5347: push(@groupkeys,$role);
5348: }
5349: if (ref($groups_roles) eq 'HASH') {
5350: foreach my $key (keys(%{$groups_roles})) {
5351: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5352: push(@groupkeys,$key);
5353: }
5354: }
5355: }
5356: if (@groupkeys > 0) {
5357: foreach my $role (@groupkeys) {
5358: my ($trole,$area,$sec,$extendedarea);
5359: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5360: $trole = $1;
5361: $area = $2;
5362: $sec = $3;
5363: $extendedarea = $area.$sec;
5364: if (exists($$allgroups{$area})) {
5365: foreach my $group (keys(%{$$allgroups{$area}})) {
5366: my $spec = $trole.'.'.$extendedarea;
5367: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5368: $$allgroups{$area}{$group};
1.1064 raeburn 5369: }
1.678 raeburn 5370: }
5371: }
5372: }
5373: }
5374: }
1.800 albertel 5375: foreach my $group (keys(%grouproles)) {
5376: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5377: }
1.800 albertel 5378: foreach my $role (keys(%{$allroles})) {
5379: my %thesepriv;
1.941 raeburn 5380: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5381: foreach my $item (split(/:/,$$allroles{$role})) {
5382: if ($item ne '') {
5383: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5384: if ($restrictions eq '') {
5385: $thesepriv{$privilege}='F';
5386: } elsif ($thesepriv{$privilege} ne 'F') {
5387: $thesepriv{$privilege}.=$restrictions;
5388: }
5389: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5390: }
5391: }
5392: my $thesestr='';
1.1104 raeburn 5393: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5394: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5395: }
5396: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5397: }
5398: return ($author,$adv);
5399: }
5400:
1.994 raeburn 5401: sub role_status {
1.1104 raeburn 5402: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5403: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5404: my ($one,$two) = split(m{\./},$rolekey,2);
5405: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5406: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5407: $$where = '/'.$two;
1.994 raeburn 5408: $$trolecode=$$role.'.'.$$where;
5409: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5410: $$tstatus='is';
1.1104 raeburn 5411: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5412: $$tstatus='future';
1.1034 raeburn 5413: if ($$tstart<$now) {
5414: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5415: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5416: my (%allroles,%allgroups,$group_privs,
5417: %groups_roles,@rolecodes);
1.1002 raeburn 5418: my %userroles = (
5419: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5420: );
1.1064 raeburn 5421: @rolecodes = ('cm');
1.1002 raeburn 5422: my $spec=$$role.'.'.$$where;
5423: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5424: if ($$role =~ /^cr\//) {
5425: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5426: push(@rolecodes,'cr');
1.1002 raeburn 5427: } elsif ($$role eq 'gr') {
1.1064 raeburn 5428: push(@rolecodes,$$role);
1.1002 raeburn 5429: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5430: $env{'user.name'});
1.1064 raeburn 5431: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5432: (undef,my $group_privs) = split(/\//,$trole);
5433: $group_privs = &unescape($group_privs);
5434: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5435: 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 5436: &get_groups_roles($tdomain,$trest,
5437: \%course_roles,\@rolecodes,
5438: \%groups_roles);
1.1002 raeburn 5439: } else {
1.1064 raeburn 5440: push(@rolecodes,$$role);
1.1002 raeburn 5441: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5442: }
1.1064 raeburn 5443: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5444: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5445: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5446: }
5447: }
1.1034 raeburn 5448: $$tstatus = 'is';
1.1002 raeburn 5449: }
1.994 raeburn 5450: }
5451: if ($$tend) {
1.1104 raeburn 5452: if ($$tend<$update) {
1.994 raeburn 5453: $$tstatus='expired';
5454: } elsif ($$tend<$now) {
5455: $$tstatus='will_not';
5456: }
5457: }
5458: }
5459: }
5460: }
5461:
1.1104 raeburn 5462: sub get_groups_roles {
5463: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5464: return unless((ref($cdom_courseroles) eq 'HASH') &&
5465: (ref($rolecodes) eq 'ARRAY') &&
5466: (ref($groups_roles) eq 'HASH'));
5467: if (keys(%{$cdom_courseroles}) > 0) {
5468: my ($cnum) = ($rest =~ /^($match_courseid)/);
5469: if ($cdom ne '' && $cnum ne '') {
5470: foreach my $key (keys(%{$cdom_courseroles})) {
5471: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5472: my $crsrole = $1;
5473: my $crssec = $2;
5474: if ($crsrole =~ /^cr/) {
5475: unless (grep(/^cr$/,@{$rolecodes})) {
5476: push(@{$rolecodes},'cr');
5477: }
5478: } else {
5479: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5480: push(@{$rolecodes},$crsrole);
5481: }
5482: }
5483: my $rolekey = "$crsrole./$cdom/$cnum";
5484: if ($crssec ne '') {
5485: $rolekey .= "/$crssec";
5486: }
5487: $rolekey .= './';
5488: $groups_roles->{$rolekey} = $rolecodes;
5489: }
5490: }
5491: }
5492: }
5493: return;
5494: }
5495:
5496: sub delete_env_groupprivs {
5497: my ($where,$courseroles,$possroles) = @_;
5498: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5499: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5500: unless (ref($courseroles->{$udom}) eq 'HASH') {
5501: %{$courseroles->{$udom}} =
5502: &get_my_roles('','','userroles',['active'],
5503: $possroles,[$udom],1);
5504: }
5505: if (ref($courseroles->{$udom}) eq 'HASH') {
5506: foreach my $item (keys(%{$courseroles->{$udom}})) {
5507: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5508: my $area = '/'.$cdom.'/'.$cnum;
5509: my $privkey = "user.priv.$crsrole.$area";
5510: if ($crssec ne '') {
5511: $privkey .= '/'.$crssec;
5512: }
5513: $privkey .= ".$area/$group";
5514: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5515: }
5516: }
5517: return;
5518: }
5519:
1.994 raeburn 5520: sub check_adhoc_privs {
1.1104 raeburn 5521: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5522: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5523: my $setprivs;
1.994 raeburn 5524: if ($env{$cckey}) {
5525: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5526: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5527: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5528: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5529: $setprivs = 1;
1.994 raeburn 5530: }
5531: } else {
1.1088 raeburn 5532: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5533: $setprivs = 1;
1.994 raeburn 5534: }
1.1185 raeburn 5535: return $setprivs;
1.994 raeburn 5536: }
5537:
5538: sub set_adhoc_privileges {
5539: # role can be cc or ca
1.1088 raeburn 5540: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5541: my $area = '/'.$dcdom.'/'.$pickedcourse;
5542: my $spec = $role.'.'.$area;
5543: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5544: $env{'user.name'},1);
1.994 raeburn 5545: my %ccrole = ();
5546: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5547: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5548: &appenv(\%userroles,[$role,'cm']);
5549: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5550: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5551: &appenv( {'request.role' => $spec,
5552: 'request.role.domain' => $dcdom,
5553: 'request.course.sec' => ''
5554: }
5555: );
5556: my $tadv=0;
5557: if (&allowed('adv') eq 'F') { $tadv=1; }
5558: &appenv({'request.role.adv' => $tadv});
5559: }
1.994 raeburn 5560: }
5561:
1.12 www 5562: # --------------------------------------------------------------- get interface
5563:
5564: sub get {
1.131 albertel 5565: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5566: my $items='';
1.800 albertel 5567: foreach my $item (@$storearr) {
5568: $items.=&escape($item).'&';
1.191 harris41 5569: }
1.12 www 5570: $items=~s/\&$//;
1.620 albertel 5571: if (!$udomain) { $udomain=$env{'user.domain'}; }
5572: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5573: my $uhome=&homeserver($uname,$udomain);
5574:
1.133 albertel 5575: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5576: my @pairs=split(/\&/,$rep);
1.273 albertel 5577: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5578: return @pairs;
5579: }
1.15 www 5580: my %returnhash=();
1.42 www 5581: my $i=0;
1.800 albertel 5582: foreach my $item (@$storearr) {
5583: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5584: $i++;
1.191 harris41 5585: }
1.15 www 5586: return %returnhash;
1.27 www 5587: }
5588:
5589: # --------------------------------------------------------------- del interface
5590:
5591: sub del {
1.133 albertel 5592: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5593: my $items='';
1.800 albertel 5594: foreach my $item (@$storearr) {
5595: $items.=&escape($item).'&';
1.191 harris41 5596: }
1.984 neumanie 5597:
1.27 www 5598: $items=~s/\&$//;
1.620 albertel 5599: if (!$udomain) { $udomain=$env{'user.domain'}; }
5600: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5601: my $uhome=&homeserver($uname,$udomain);
5602: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5603: }
5604:
5605: # -------------------------------------------------------------- dump interface
5606:
1.1180 droeschl 5607: sub unserialize {
5608: my ($rep, $escapedkeys) = @_;
5609:
5610: return {} if $rep =~ /^error/;
5611:
5612: my %returnhash=();
1.1252 raeburn 5613: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5614: my ($key, $value) = split(/=/, $item, 2);
5615: $key = unescape($key) unless $escapedkeys;
5616: next if $key =~ /^error: 2 /;
1.1252 raeburn 5617: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5618: }
5619: #return %returnhash;
5620: return \%returnhash;
5621: }
5622:
5623: # see Lond::dump_with_regexp
5624: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5625: sub dump {
1.1180 droeschl 5626: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5627: if (!$udomain) { $udomain=$env{'user.domain'}; }
5628: if (!$uname) { $uname=$env{'user.name'}; }
5629: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5630:
1.1180 droeschl 5631: my $reply;
5632: if (grep { $_ eq $uhome } current_machine_ids()) {
5633: # user is hosted on this machine
5634: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5635: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5636: return %{unserialize($reply, $escapedkeys)};
5637: }
1.755 albertel 5638: if ($regexp) {
5639: $regexp=&escape($regexp);
5640: } else {
5641: $regexp='.';
5642: }
1.1166 raeburn 5643: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5644: my @pairs=split(/\&/,$rep);
5645: my %returnhash=();
1.1098 foxr 5646: if (!($rep =~ /^error/ )) {
5647: foreach my $item (@pairs) {
5648: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5649: $key = unescape($key) unless $escapedkeys;
5650: #$key = &unescape($key);
1.1098 foxr 5651: next if ($key =~ /^error: 2 /);
5652: $returnhash{$key}=&thaw_unescape($value);
5653: }
1.755 albertel 5654: }
5655: return %returnhash;
1.407 www 5656: }
5657:
1.1098 foxr 5658:
1.717 albertel 5659: # --------------------------------------------------------- dumpstore interface
5660:
5661: sub dumpstore {
5662: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5663: # same as dump but keys must be escaped. They may contain colon separated
5664: # lists of values that may themself contain colons (e.g. symbs).
5665: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5666: }
5667:
1.407 www 5668: # -------------------------------------------------------------- keys interface
5669:
5670: sub getkeys {
5671: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5672: if (!$udomain) { $udomain=$env{'user.domain'}; }
5673: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5674: my $uhome=&homeserver($uname,$udomain);
5675: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5676: my @keyarray=();
1.800 albertel 5677: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5678: next if ($key =~ /^error: 2 /);
1.800 albertel 5679: push(@keyarray,&unescape($key));
1.407 www 5680: }
5681: return @keyarray;
1.318 matthew 5682: }
5683:
1.319 matthew 5684: # --------------------------------------------------------------- currentdump
5685: sub currentdump {
1.328 matthew 5686: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5687: $courseid = $env{'request.course.id'} if (! defined($courseid));
5688: $sdom = $env{'user.domain'} if (! defined($sdom));
5689: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5690: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5691: my $rep;
5692:
5693: if (grep { $_ eq $uhome } current_machine_ids()) {
5694: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5695: $courseid)));
5696: } else {
5697: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5698: }
5699:
1.318 matthew 5700: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5701: #
1.318 matthew 5702: my %returnhash=();
1.319 matthew 5703: #
5704: if ($rep eq "unknown_cmd") {
5705: # an old lond will not know currentdump
5706: # Do a dump and make it look like a currentdump
1.822 albertel 5707: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5708: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5709: my %hash = @tmp;
5710: @tmp=();
1.424 matthew 5711: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5712: } else {
5713: my @pairs=split(/\&/,$rep);
1.800 albertel 5714: foreach my $pair (@pairs) {
5715: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5716: my ($symb,$param) = split(/:/,$key);
5717: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5718: &thaw_unescape($value);
1.319 matthew 5719: }
1.191 harris41 5720: }
1.12 www 5721: return %returnhash;
1.424 matthew 5722: }
5723:
5724: sub convert_dump_to_currentdump{
5725: my %hash = %{shift()};
5726: my %returnhash;
5727: # Code ripped from lond, essentially. The only difference
5728: # here is the unescaping done by lonnet::dump(). Conceivably
5729: # we might run in to problems with parameter names =~ /^v\./
5730: while (my ($key,$value) = each(%hash)) {
5731: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5732: $symb = &unescape($symb);
5733: $param = &unescape($param);
1.424 matthew 5734: next if ($v eq 'version' || $symb eq 'keys');
5735: next if (exists($returnhash{$symb}) &&
5736: exists($returnhash{$symb}->{$param}) &&
5737: $returnhash{$symb}->{'v.'.$param} > $v);
5738: $returnhash{$symb}->{$param}=$value;
5739: $returnhash{$symb}->{'v.'.$param}=$v;
5740: }
5741: #
5742: # Remove all of the keys in the hashes which keep track of
5743: # the version of the parameter.
5744: while (my ($symb,$param_hash) = each(%returnhash)) {
5745: # use a foreach because we are going to delete from the hash.
5746: foreach my $key (keys(%$param_hash)) {
5747: delete($param_hash->{$key}) if ($key =~ /^v\./);
5748: }
5749: }
5750: return \%returnhash;
1.12 www 5751: }
5752:
1.627 albertel 5753: # ------------------------------------------------------ critical inc interface
5754:
5755: sub cinc {
5756: return &inc(@_,'critical');
5757: }
5758:
1.449 matthew 5759: # --------------------------------------------------------------- inc interface
5760:
5761: sub inc {
1.627 albertel 5762: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5763: if (!$udomain) { $udomain=$env{'user.domain'}; }
5764: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5765: my $uhome=&homeserver($uname,$udomain);
5766: my $items='';
5767: if (! ref($store)) {
5768: # got a single value, so use that instead
5769: $items = &escape($store).'=&';
5770: } elsif (ref($store) eq 'SCALAR') {
5771: $items = &escape($$store).'=&';
5772: } elsif (ref($store) eq 'ARRAY') {
5773: $items = join('=&',map {&escape($_);} @{$store});
5774: } elsif (ref($store) eq 'HASH') {
5775: while (my($key,$value) = each(%{$store})) {
5776: $items.= &escape($key).'='.&escape($value).'&';
5777: }
5778: }
5779: $items=~s/\&$//;
1.627 albertel 5780: if ($critical) {
5781: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5782: } else {
5783: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5784: }
1.449 matthew 5785: }
5786:
1.12 www 5787: # --------------------------------------------------------------- put interface
5788:
5789: sub put {
1.134 albertel 5790: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5791: if (!$udomain) { $udomain=$env{'user.domain'}; }
5792: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5793: my $uhome=&homeserver($uname,$udomain);
1.12 www 5794: my $items='';
1.800 albertel 5795: foreach my $item (keys(%$storehash)) {
5796: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5797: }
1.12 www 5798: $items=~s/\&$//;
1.134 albertel 5799: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5800: }
5801:
1.631 albertel 5802: # ------------------------------------------------------------ newput interface
5803:
5804: sub newput {
5805: my ($namespace,$storehash,$udomain,$uname)=@_;
5806: if (!$udomain) { $udomain=$env{'user.domain'}; }
5807: if (!$uname) { $uname=$env{'user.name'}; }
5808: my $uhome=&homeserver($uname,$udomain);
5809: my $items='';
5810: foreach my $key (keys(%$storehash)) {
5811: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5812: }
5813: $items=~s/\&$//;
5814: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5815: }
5816:
5817: # --------------------------------------------------------- putstore interface
5818:
1.524 raeburn 5819: sub putstore {
1.715 albertel 5820: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5821: if (!$udomain) { $udomain=$env{'user.domain'}; }
5822: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5823: my $uhome=&homeserver($uname,$udomain);
5824: my $items='';
1.715 albertel 5825: foreach my $key (keys(%$storehash)) {
5826: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5827: }
1.715 albertel 5828: $items=~s/\&$//;
1.716 albertel 5829: my $esc_symb=&escape($symb);
5830: my $esc_v=&escape($version);
1.715 albertel 5831: my $reply =
1.716 albertel 5832: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5833: $uhome);
5834: if ($reply eq 'unknown_cmd') {
1.716 albertel 5835: # gfall back to way things use to be done
1.715 albertel 5836: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5837: $uname);
1.524 raeburn 5838: }
1.715 albertel 5839: return $reply;
5840: }
5841:
5842: sub old_putstore {
1.716 albertel 5843: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5844: if (!$udomain) { $udomain=$env{'user.domain'}; }
5845: if (!$uname) { $uname=$env{'user.name'}; }
5846: my $uhome=&homeserver($uname,$udomain);
5847: my %newstorehash;
1.800 albertel 5848: foreach my $item (keys(%$storehash)) {
5849: my $key = $version.':'.&escape($symb).':'.$item;
5850: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5851: }
5852: my $items='';
5853: my %allitems = ();
1.800 albertel 5854: foreach my $item (keys(%newstorehash)) {
5855: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5856: my $key = $1.':keys:'.$2;
5857: $allitems{$key} .= $3.':';
5858: }
1.800 albertel 5859: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5860: }
1.800 albertel 5861: foreach my $item (keys(%allitems)) {
5862: $allitems{$item} =~ s/\:$//;
5863: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5864: }
5865: $items=~s/\&$//;
5866: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5867: }
5868:
1.47 www 5869: # ------------------------------------------------------ critical put interface
5870:
5871: sub cput {
1.134 albertel 5872: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5873: if (!$udomain) { $udomain=$env{'user.domain'}; }
5874: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5875: my $uhome=&homeserver($uname,$udomain);
1.47 www 5876: my $items='';
1.800 albertel 5877: foreach my $item (keys(%$storehash)) {
5878: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5879: }
1.47 www 5880: $items=~s/\&$//;
1.134 albertel 5881: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5882: }
5883:
5884: # -------------------------------------------------------------- eget interface
5885:
5886: sub eget {
1.133 albertel 5887: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5888: my $items='';
1.800 albertel 5889: foreach my $item (@$storearr) {
5890: $items.=&escape($item).'&';
1.191 harris41 5891: }
1.12 www 5892: $items=~s/\&$//;
1.620 albertel 5893: if (!$udomain) { $udomain=$env{'user.domain'}; }
5894: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5895: my $uhome=&homeserver($uname,$udomain);
5896: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5897: my @pairs=split(/\&/,$rep);
5898: my %returnhash=();
1.42 www 5899: my $i=0;
1.800 albertel 5900: foreach my $item (@$storearr) {
5901: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5902: $i++;
1.191 harris41 5903: }
1.12 www 5904: return %returnhash;
5905: }
5906:
1.667 albertel 5907: # ------------------------------------------------------------ tmpput interface
5908: sub tmpput {
1.802 raeburn 5909: my ($storehash,$server,$context)=@_;
1.667 albertel 5910: my $items='';
1.800 albertel 5911: foreach my $item (keys(%$storehash)) {
5912: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5913: }
5914: $items=~s/\&$//;
1.802 raeburn 5915: if (defined($context)) {
5916: $items .= ':'.&escape($context);
5917: }
1.667 albertel 5918: return &reply("tmpput:$items",$server);
5919: }
5920:
5921: # ------------------------------------------------------------ tmpget interface
5922: sub tmpget {
1.688 albertel 5923: my ($token,$server)=@_;
5924: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5925: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5926: my %returnhash;
5927: foreach my $item (split(/\&/,$rep)) {
5928: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5929: next if ($key =~ /^error: 2 /);
1.667 albertel 5930: $returnhash{&unescape($key)}=&thaw_unescape($value);
5931: }
5932: return %returnhash;
5933: }
5934:
1.1113 raeburn 5935: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5936: sub tmpdel {
5937: my ($token,$server)=@_;
5938: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5939: return &reply("tmpdel:$token",$server);
5940: }
5941:
1.1198 raeburn 5942: # ------------------------------------------------------------ get_timebased_id
5943:
5944: sub get_timebased_id {
5945: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5946: $maxtries) = @_;
5947: my ($newid,$error,$dellock);
5948: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5949: return ('','ok','invalid call to get suffix');
5950: }
5951:
5952: # set defaults for any optional args for which values were not supplied
5953: if ($who eq '') {
5954: $who = $env{'user.name'}.':'.$env{'user.domain'};
5955: }
5956: if (!$locktries) {
5957: $locktries = 3;
5958: }
5959: if (!$maxtries) {
5960: $maxtries = 10;
5961: }
5962:
5963: if (($cdom eq '') || ($cnum eq '')) {
5964: if ($env{'request.course.id'}) {
5965: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5966: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5967: }
5968: if (($cdom eq '') || ($cnum eq '')) {
5969: return ('','ok','call to get suffix not in course context');
5970: }
5971: }
5972:
5973: # construct locking item
5974: my $lockhash = {
5975: $prefix."\0".'locked_'.$keyid => $who,
5976: };
5977: my $tries = 0;
5978:
5979: # attempt to get lock on nohist_$namespace file
5980: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5981: while (($gotlock ne 'ok') && $tries <$locktries) {
5982: $tries ++;
5983: sleep 1;
5984: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5985: }
5986:
5987: # attempt to get unique identifier, based on current timestamp
5988: if ($gotlock eq 'ok') {
5989: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5990: my $id = time;
5991: $newid = $id;
5992: my $idtries = 0;
5993: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5994: if ($idtype eq 'concat') {
5995: $newid = $id.$idtries;
5996: } else {
5997: $newid ++;
5998: }
5999: $idtries ++;
6000: }
6001: if (!exists($inuse{$prefix."\0".$newid})) {
6002: my %new_item = (
6003: $prefix."\0".$newid => $who,
6004: );
6005: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6006: $cdom,$cnum);
6007: if ($putresult ne 'ok') {
6008: undef($newid);
6009: $error = 'error saving new item: '.$putresult;
6010: }
6011: } else {
6012: $error = ('error: no unique suffix available for the new item ');
6013: }
6014: # remove lock
6015: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6016: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6017: } else {
6018: $error = "error: could not obtain lockfile\n";
6019: $dellock = 'ok';
6020: }
6021: return ($newid,$dellock,$error);
6022: }
6023:
1.765 albertel 6024: # -------------------------------------------------- portfolio access checking
6025:
6026: sub portfolio_access {
1.766 albertel 6027: my ($requrl) = @_;
1.765 albertel 6028: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6029: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6030: if ($result) {
6031: my %setters;
6032: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6033: my ($startblock,$endblock) =
6034: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6035: if ($startblock && $endblock) {
6036: return 'B';
6037: }
6038: } else {
6039: my ($startblock,$endblock) =
6040: &Apache::loncommon::blockcheck(\%setters,'port');
6041: if ($startblock && $endblock) {
6042: return 'B';
6043: }
6044: }
6045: }
1.765 albertel 6046: if ($result eq 'ok') {
1.766 albertel 6047: return 'F';
1.765 albertel 6048: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6049: return 'A';
1.765 albertel 6050: }
1.766 albertel 6051: return '';
1.765 albertel 6052: }
6053:
6054: sub get_portfolio_access {
1.767 albertel 6055: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6056:
6057: if (!ref($access_hash)) {
6058: my $current_perms = &get_portfile_permissions($udom,$unum);
6059: my %access_controls = &get_access_controls($current_perms,$group,
6060: $file_name);
6061: $access_hash = $access_controls{$file_name};
6062: }
6063:
1.765 albertel 6064: my ($public,$guest,@domains,@users,@courses,@groups);
6065: my $now = time;
6066: if (ref($access_hash) eq 'HASH') {
6067: foreach my $key (keys(%{$access_hash})) {
6068: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6069: if ($start > $now) {
6070: next;
6071: }
6072: if ($end && $end<$now) {
6073: next;
6074: }
6075: if ($scope eq 'public') {
6076: $public = $key;
6077: last;
6078: } elsif ($scope eq 'guest') {
6079: $guest = $key;
6080: } elsif ($scope eq 'domains') {
6081: push(@domains,$key);
6082: } elsif ($scope eq 'users') {
6083: push(@users,$key);
6084: } elsif ($scope eq 'course') {
6085: push(@courses,$key);
6086: } elsif ($scope eq 'group') {
6087: push(@groups,$key);
6088: }
6089: }
6090: if ($public) {
6091: return 'ok';
6092: }
6093: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6094: if ($guest) {
6095: return $guest;
6096: }
6097: } else {
6098: if (@domains > 0) {
6099: foreach my $domkey (@domains) {
6100: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6101: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6102: return 'ok';
6103: }
6104: }
6105: }
6106: }
6107: if (@users > 0) {
6108: foreach my $userkey (@users) {
1.865 raeburn 6109: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6110: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6111: if (ref($item) eq 'HASH') {
6112: if (($item->{'uname'} eq $env{'user.name'}) &&
6113: ($item->{'udom'} eq $env{'user.domain'})) {
6114: return 'ok';
6115: }
6116: }
6117: }
6118: }
1.765 albertel 6119: }
6120: }
6121: my %roleshash;
6122: my @courses_and_groups = @courses;
6123: push(@courses_and_groups,@groups);
6124: if (@courses_and_groups > 0) {
6125: my (%allgroups,%allroles);
6126: my ($start,$end,$role,$sec,$group);
6127: foreach my $envkey (%env) {
1.1060 raeburn 6128: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6129: my $cid = $2.'_'.$3;
6130: if ($1 eq 'gr') {
6131: $group = $4;
6132: $allgroups{$cid}{$group} = $env{$envkey};
6133: } else {
6134: if ($4 eq '') {
6135: $sec = 'none';
6136: } else {
6137: $sec = $4;
6138: }
6139: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6140: }
1.811 albertel 6141: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6142: my $cid = $2.'_'.$3;
6143: if ($4 eq '') {
6144: $sec = 'none';
6145: } else {
6146: $sec = $4;
6147: }
6148: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6149: }
6150: }
6151: if (keys(%allroles) == 0) {
6152: return;
6153: }
6154: foreach my $key (@courses_and_groups) {
6155: my %content = %{$$access_hash{$key}};
6156: my $cnum = $content{'number'};
6157: my $cdom = $content{'domain'};
6158: my $cid = $cdom.'_'.$cnum;
6159: if (!exists($allroles{$cid})) {
6160: next;
6161: }
6162: foreach my $role_id (keys(%{$content{'roles'}})) {
6163: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6164: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6165: my @status = @{$content{'roles'}{$role_id}{'access'}};
6166: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6167: foreach my $role (keys(%{$allroles{$cid}})) {
6168: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6169: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6170: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6171: if (grep/^all$/,@sections) {
6172: return 'ok';
6173: } else {
6174: if (grep/^$sec$/,@sections) {
6175: return 'ok';
6176: }
6177: }
6178: }
6179: }
6180: if (keys(%{$allgroups{$cid}}) == 0) {
6181: if (grep/^none$/,@groups) {
6182: return 'ok';
6183: }
6184: } else {
6185: if (grep/^all$/,@groups) {
6186: return 'ok';
6187: }
6188: foreach my $group (keys(%{$allgroups{$cid}})) {
6189: if (grep/^$group$/,@groups) {
6190: return 'ok';
6191: }
6192: }
6193: }
6194: }
6195: }
6196: }
6197: }
6198: }
6199: if ($guest) {
6200: return $guest;
6201: }
6202: }
6203: }
6204: return;
6205: }
6206:
6207: sub course_group_datechecker {
6208: my ($dates,$now,$status) = @_;
6209: my ($start,$end) = split(/\./,$dates);
6210: if (!$start && !$end) {
6211: return 'ok';
6212: }
6213: if (grep/^active$/,@{$status}) {
6214: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6215: return 'ok';
6216: }
6217: }
6218: if (grep/^previous$/,@{$status}) {
6219: if ($end > $now ) {
6220: return 'ok';
6221: }
6222: }
6223: if (grep/^future$/,@{$status}) {
6224: if ($start > $now) {
6225: return 'ok';
6226: }
6227: }
6228: return;
6229: }
6230:
6231: sub parse_portfolio_url {
6232: my ($url) = @_;
6233:
6234: my ($type,$udom,$unum,$group,$file_name);
6235:
1.823 albertel 6236: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6237: $type = 1;
6238: $udom = $1;
6239: $unum = $2;
6240: $file_name = $3;
1.823 albertel 6241: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6242: $type = 2;
6243: $udom = $1;
6244: $unum = $2;
6245: $group = $3;
6246: $file_name = $3.'/'.$4;
6247: }
6248: if (wantarray) {
6249: return ($type,$udom,$unum,$file_name,$group);
6250: }
6251: return $type;
6252: }
6253:
6254: sub is_portfolio_url {
6255: my ($url) = @_;
6256: return scalar(&parse_portfolio_url($url));
6257: }
6258:
1.798 raeburn 6259: sub is_portfolio_file {
6260: my ($file) = @_;
1.820 raeburn 6261: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6262: return 1;
6263: }
6264: return;
6265: }
6266:
1.976 raeburn 6267: sub usertools_access {
1.1084 raeburn 6268: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6269: my ($access,%tools);
6270: if ($context eq '') {
6271: $context = 'tools';
6272: }
6273: if ($context eq 'requestcourses') {
6274: %tools = (
6275: official => 1,
6276: unofficial => 1,
1.1006 raeburn 6277: community => 1,
1.1246 raeburn 6278: textbook => 1,
1.985 raeburn 6279: );
1.1183 raeburn 6280: } elsif ($context eq 'requestauthor') {
6281: %tools = (
6282: requestauthor => 1,
6283: );
1.985 raeburn 6284: } else {
6285: %tools = (
6286: aboutme => 1,
6287: blog => 1,
1.1177 raeburn 6288: webdav => 1,
1.985 raeburn 6289: portfolio => 1,
6290: );
6291: }
1.976 raeburn 6292: return if (!defined($tools{$tool}));
6293:
1.1242 raeburn 6294: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6295: $udom = $env{'user.domain'};
6296: $uname = $env{'user.name'};
6297: }
6298:
1.978 raeburn 6299: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6300: if ($action ne 'reload') {
1.985 raeburn 6301: if ($context eq 'requestcourses') {
6302: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6303: } elsif ($context eq 'requestauthor') {
6304: return $env{'environment.canrequest.author'};
1.985 raeburn 6305: } else {
6306: return $env{'environment.availabletools.'.$tool};
6307: }
6308: }
1.976 raeburn 6309: }
6310:
1.1183 raeburn 6311: my ($toolstatus,$inststatus,$envkey);
6312: if ($context eq 'requestauthor') {
6313: $envkey = $context;
6314: } else {
6315: $envkey = $context.'.'.$tool;
6316: }
1.976 raeburn 6317:
1.985 raeburn 6318: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6319: ($action ne 'reload')) {
1.1183 raeburn 6320: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6321: $inststatus = $env{'environment.inststatus'};
6322: } else {
1.1084 raeburn 6323: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6324: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6325: $inststatus = $userenvref->{'inststatus'};
6326: } else {
1.1183 raeburn 6327: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6328: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6329: $inststatus = $userenv{'inststatus'};
6330: }
1.976 raeburn 6331: }
6332:
6333: if ($toolstatus ne '') {
6334: if ($toolstatus) {
6335: $access = 1;
6336: } else {
6337: $access = 0;
6338: }
6339: return $access;
6340: }
6341:
1.1084 raeburn 6342: my ($is_adv,%domdef);
6343: if (ref($is_advref) eq 'HASH') {
6344: $is_adv = $is_advref->{'is_adv'};
6345: } else {
6346: $is_adv = &is_advanced_user($udom,$uname);
6347: }
6348: if (ref($domdefref) eq 'HASH') {
6349: %domdef = %{$domdefref};
6350: } else {
6351: %domdef = &get_domain_defaults($udom);
6352: }
1.976 raeburn 6353: if (ref($domdef{$tool}) eq 'HASH') {
6354: if ($is_adv) {
6355: if ($domdef{$tool}{'_LC_adv'} ne '') {
6356: if ($domdef{$tool}{'_LC_adv'}) {
6357: $access = 1;
6358: } else {
6359: $access = 0;
6360: }
6361: return $access;
6362: }
6363: }
6364: if ($inststatus ne '') {
6365: my ($hasaccess,$hasnoaccess);
6366: foreach my $affiliation (split(/:/,$inststatus)) {
6367: if ($domdef{$tool}{$affiliation} ne '') {
6368: if ($domdef{$tool}{$affiliation}) {
6369: $hasaccess = 1;
6370: } else {
6371: $hasnoaccess = 1;
6372: }
6373: }
6374: }
6375: if ($hasaccess || $hasnoaccess) {
6376: if ($hasaccess) {
6377: $access = 1;
6378: } elsif ($hasnoaccess) {
6379: $access = 0;
6380: }
6381: return $access;
6382: }
6383: } else {
6384: if ($domdef{$tool}{'default'} ne '') {
6385: if ($domdef{$tool}{'default'}) {
6386: $access = 1;
6387: } elsif ($domdef{$tool}{'default'} == 0) {
6388: $access = 0;
6389: }
6390: return $access;
6391: }
6392: }
6393: } else {
1.1177 raeburn 6394: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6395: $access = 1;
6396: } else {
6397: $access = 0;
6398: }
1.976 raeburn 6399: return $access;
6400: }
6401: }
6402:
1.1050 raeburn 6403: sub is_course_owner {
6404: my ($cdom,$cnum,$udom,$uname) = @_;
6405: if (($udom eq '') || ($uname eq '')) {
6406: $udom = $env{'user.domain'};
6407: $uname = $env{'user.name'};
6408: }
6409: unless (($udom eq '') || ($uname eq '')) {
6410: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6411: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6412: return 1;
6413: } else {
6414: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6415: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6416: return 1;
6417: }
6418: }
6419: }
6420: }
6421: return;
6422: }
6423:
1.976 raeburn 6424: sub is_advanced_user {
6425: my ($udom,$uname) = @_;
1.1085 raeburn 6426: if ($udom ne '' && $uname ne '') {
6427: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6428: if (wantarray) {
6429: return ($env{'user.adv'},$env{'user.author'});
6430: } else {
6431: return $env{'user.adv'};
6432: }
1.1085 raeburn 6433: }
6434: }
1.976 raeburn 6435: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6436: my %allroles;
1.1128 raeburn 6437: my ($is_adv,$is_author);
1.976 raeburn 6438: foreach my $role (keys(%roleshash)) {
6439: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6440: my $area = '/'.$tdomain.'/'.$trest;
6441: if ($sec ne '') {
6442: $area .= '/'.$sec;
6443: }
6444: if (($area ne '') && ($trole ne '')) {
6445: my $spec=$trole.'.'.$area;
6446: if ($trole =~ /^cr\//) {
6447: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6448: } elsif ($trole ne 'gr') {
6449: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6450: }
1.1128 raeburn 6451: if ($trole eq 'au') {
6452: $is_author = 1;
6453: }
1.976 raeburn 6454: }
6455: }
6456: foreach my $role (keys(%allroles)) {
6457: last if ($is_adv);
6458: foreach my $item (split(/:/,$allroles{$role})) {
6459: if ($item ne '') {
6460: my ($privilege,$restrictions)=split(/&/,$item);
6461: if ($privilege eq 'adv') {
6462: $is_adv = 1;
6463: last;
6464: }
6465: }
6466: }
6467: }
1.1128 raeburn 6468: if (wantarray) {
6469: return ($is_adv,$is_author);
6470: }
1.976 raeburn 6471: return $is_adv;
6472: }
1.798 raeburn 6473:
1.1035 raeburn 6474: sub check_can_request {
1.1036 raeburn 6475: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6476: my $canreq = 0;
6477: my ($types,$typename) = &Apache::loncommon::course_types();
6478: my @options = ('approval','validate','autolimit');
6479: my $optregex = join('|',@options);
6480: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6481: foreach my $type (@{$types}) {
6482: if (&usertools_access($env{'user.name'},
6483: $env{'user.domain'},
6484: $type,undef,'requestcourses')) {
6485: $canreq ++;
1.1036 raeburn 6486: if (ref($request_domains) eq 'HASH') {
6487: push(@{$request_domains->{$type}},$env{'user.domain'});
6488: }
1.1035 raeburn 6489: if ($dom eq $env{'user.domain'}) {
6490: $can_request->{$type} = 1;
6491: }
6492: }
6493: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6494: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6495: if (@curr > 0) {
1.1036 raeburn 6496: foreach my $item (@curr) {
6497: if (ref($request_domains) eq 'HASH') {
6498: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6499: if ($otherdom ne '') {
6500: if (ref($request_domains->{$type}) eq 'ARRAY') {
6501: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6502: push(@{$request_domains->{$type}},$otherdom);
6503: }
6504: } else {
6505: push(@{$request_domains->{$type}},$otherdom);
6506: }
6507: }
6508: }
6509: }
6510: unless($dom eq $env{'user.domain'}) {
6511: $canreq ++;
1.1035 raeburn 6512: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6513: $can_request->{$type} = 1;
6514: }
6515: }
6516: }
6517: }
6518: }
6519: }
6520: return $canreq;
6521: }
6522:
1.341 www 6523: # ---------------------------------------------- Custom access rule evaluation
6524:
6525: sub customaccess {
6526: my ($priv,$uri)=@_;
1.807 albertel 6527: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6528: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6529: $udom = &LONCAPA::clean_domain($udom);
6530: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6531: my $access=0;
1.800 albertel 6532: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6533: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6534: if ($type eq 'user') {
6535: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6536: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6537: if ($tdom) {
6538: if ($tdom ne $env{'user.domain'}) { next; }
6539: }
1.896 albertel 6540: if ($tuname) {
6541: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6542: }
6543: $access=($effect eq 'allow');
6544: last;
6545: }
6546: } else {
6547: if ($role) {
6548: if ($role ne $urole) { next; }
6549: }
6550: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6551: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6552: if ($tdom) {
6553: if ($tdom ne $udom) { next; }
6554: }
6555: if ($tcrs) {
6556: if ($tcrs ne $ucrs) { next; }
6557: }
6558: if ($tsec) {
6559: if ($tsec ne $usec) { next; }
6560: }
6561: $access=($effect eq 'allow');
6562: last;
6563: }
6564: if ($realm eq '' && $role eq '') {
6565: $access=($effect eq 'allow');
6566: }
1.402 bowersj2 6567: }
1.341 www 6568: }
6569: return $access;
6570: }
6571:
1.103 harris41 6572: # ------------------------------------------------- Check for a user privilege
1.12 www 6573:
6574: sub allowed {
1.810 raeburn 6575: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6576: my $ver_orguri=$uri;
1.439 www 6577: $uri=&deversion($uri);
1.152 www 6578: my $orguri=$uri;
1.52 www 6579: $uri=&declutter($uri);
1.809 raeburn 6580:
1.810 raeburn 6581: if ($priv eq 'evb') {
6582: # Evade communication block restrictions for specified role in a course
6583: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6584: return $1;
6585: } else {
6586: return;
6587: }
6588: }
6589:
1.620 albertel 6590: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6591: # Free bre access to adm and meta resources
1.775 albertel 6592: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6593: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6594: && ($priv eq 'bre')) {
1.14 www 6595: return 'F';
1.159 www 6596: }
6597:
1.545 banghart 6598: # Free bre access to user's own portfolio contents
1.714 raeburn 6599: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6600: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6601: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6602: my %setters;
6603: my ($startblock,$endblock) =
6604: &Apache::loncommon::blockcheck(\%setters,'port');
6605: if ($startblock && $endblock) {
6606: return 'B';
6607: } else {
6608: return 'F';
6609: }
1.545 banghart 6610: }
6611:
1.762 raeburn 6612: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6613: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6614: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6615: if (exists($env{'request.course.id'})) {
6616: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6617: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6618: if (($domain eq $cdom) && ($name eq $cnum)) {
6619: my $courseprivid=$env{'request.course.id'};
6620: $courseprivid=~s/\_/\//;
6621: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6622: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6623: return $1;
1.762 raeburn 6624: } else {
6625: if ($env{'request.course.sec'}) {
6626: $courseprivid.='/'.$env{'request.course.sec'};
6627: }
6628: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6629: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6630: return $2;
6631: }
1.714 raeburn 6632: }
6633: }
6634: }
6635: }
6636:
1.159 www 6637: # Free bre to public access
6638:
6639: if ($priv eq 'bre') {
1.238 www 6640: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6641: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6642: return 'F';
6643: }
1.238 www 6644: if ($copyright eq 'priv') {
6645: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6646: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6647: return '';
6648: }
6649: }
6650: if ($copyright eq 'domain') {
6651: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6652: unless (($env{'user.domain'} eq $1) ||
6653: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6654: return '';
6655: }
1.262 matthew 6656: }
1.620 albertel 6657: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6658: # Library role, so allow browsing of resources in this domain.
6659: return 'F';
1.238 www 6660: }
1.341 www 6661: if ($copyright eq 'custom') {
6662: unless (&customaccess($priv,$uri)) { return ''; }
6663: }
1.14 www 6664: }
1.264 matthew 6665: # Domain coordinator is trying to create a course
1.620 albertel 6666: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6667: # uri is the requested domain in this case.
6668: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6669: # a role of dc for the domain in question.
1.620 albertel 6670: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6671: }
1.29 www 6672:
1.52 www 6673: my $thisallowed='';
6674: my $statecond=0;
6675: my $courseprivid='';
6676:
1.1039 raeburn 6677: my $ownaccess;
1.1043 raeburn 6678: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6679: if (($priv eq 'bro') && ($env{'user.author'})) {
6680: if ($uri eq '') {
6681: $ownaccess = 1;
6682: } else {
6683: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6684: my $udom = $env{'user.domain'};
6685: my $uname = $env{'user.name'};
6686: if ($uri =~ m{^\Q$udom\E/?$}) {
6687: $ownaccess = 1;
1.1040 raeburn 6688: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6689: unless ($uri =~ m{\.\./}) {
6690: $ownaccess = 1;
6691: }
6692: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6693: my $now = time;
6694: if ($uri =~ m{^([^/]+)/?$}) {
6695: my $adom = $1;
6696: foreach my $key (keys(%env)) {
1.1042 raeburn 6697: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6698: my ($start,$end) = split('.',$env{$key});
6699: if (($now >= $start) && (!$end || $end < $now)) {
6700: $ownaccess = 1;
6701: last;
6702: }
6703: }
6704: }
6705: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6706: my $adom = $1;
6707: my $aname = $2;
1.1042 raeburn 6708: foreach my $role ('ca','aa') {
6709: if ($env{"user.role.$role./$adom/$aname"}) {
6710: my ($start,$end) =
6711: split('.',$env{"user.role.$role./$adom/$aname"});
6712: if (($now >= $start) && (!$end || $end < $now)) {
6713: $ownaccess = 1;
6714: last;
6715: }
1.1039 raeburn 6716: }
6717: }
6718: }
6719: }
6720: }
6721: }
6722: }
6723:
1.52 www 6724: # Course
6725:
1.620 albertel 6726: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6727: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6728: $thisallowed.=$1;
6729: }
1.52 www 6730: }
1.29 www 6731:
1.52 www 6732: # Domain
6733:
1.620 albertel 6734: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6735: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6736: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6737: $thisallowed.=$1;
6738: }
1.12 www 6739: }
1.52 www 6740:
1.1141 raeburn 6741: # User who is not author or co-author might still be able to edit
6742: # resource of an author in the domain (e.g., if Domain Coordinator).
6743: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6744: (&allowed('mdc',$env{'request.course.id'}))) {
6745: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6746: $thisallowed.=$1;
6747: }
6748: }
6749:
1.52 www 6750: # Course: uri itself is a course
1.66 www 6751: my $courseuri=$uri;
6752: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6753: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6754:
1.620 albertel 6755: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6756: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6757: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6758: $thisallowed.=$1;
6759: }
1.12 www 6760: }
1.29 www 6761:
1.665 albertel 6762: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6763: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6764: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6765: $thisallowed='';
1.671 raeburn 6766: my ($match)=&is_on_map($uri);
6767: if ($match) {
6768: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6769: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6770: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6771: if (@blockers > 0) {
6772: $thisallowed = 'B';
6773: } else {
6774: $thisallowed.=$1;
6775: }
1.671 raeburn 6776: }
6777: } else {
1.705 albertel 6778: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6779: if ($refuri) {
6780: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6781: $thisallowed='F';
1.671 raeburn 6782: } else {
6783: $refuri=&declutter($refuri);
6784: my ($match) = &is_on_map($refuri);
6785: if ($match) {
1.1162 raeburn 6786: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6787: if (@blockers > 0) {
6788: $thisallowed = 'B';
6789: } else {
6790: $thisallowed='F';
6791: }
1.671 raeburn 6792: }
1.669 raeburn 6793: }
1.671 raeburn 6794: }
6795: }
1.314 www 6796: }
1.492 albertel 6797:
1.766 albertel 6798: if ($priv eq 'bre'
6799: && $thisallowed ne 'F'
6800: && $thisallowed ne '2'
6801: && &is_portfolio_url($uri)) {
6802: $thisallowed = &portfolio_access($uri);
6803: }
1.1250 raeburn 6804:
1.52 www 6805: # Full access at system, domain or course-wide level? Exit.
1.29 www 6806: if ($thisallowed=~/F/) {
6807: return 'F';
6808: }
6809:
1.52 www 6810: # If this is generating or modifying users, exit with special codes
1.29 www 6811:
1.643 www 6812: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6813: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6814: my ($audom,$auname)=split('/',$uri);
1.643 www 6815: # no author name given, so this just checks on the general right to make a co-author in this domain
6816: unless ($auname) { return $thisallowed; }
6817: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6818: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6819: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6820: ($audom ne $env{'request.role.domain'}))) { return ''; }
6821: }
1.52 www 6822: return $thisallowed;
6823: }
6824: #
1.103 harris41 6825: # Gathered so far: system, domain and course wide privileges
1.52 www 6826: #
6827: # Course: See if uri or referer is an individual resource that is part of
6828: # the course
6829:
1.620 albertel 6830: if ($env{'request.course.id'}) {
1.232 www 6831:
1.620 albertel 6832: $courseprivid=$env{'request.course.id'};
6833: if ($env{'request.course.sec'}) {
6834: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6835: }
6836: $courseprivid=~s/\_/\//;
6837: my $checkreferer=1;
1.232 www 6838: my ($match,$cond)=&is_on_map($uri);
6839: if ($match) {
6840: $statecond=$cond;
1.620 albertel 6841: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6842: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6843: my $value = $1;
6844: if ($priv eq 'bre') {
6845: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6846: if (@blockers > 0) {
6847: $thisallowed = 'B';
6848: } else {
6849: $thisallowed.=$value;
6850: }
6851: } else {
6852: $thisallowed.=$value;
6853: }
1.52 www 6854: $checkreferer=0;
6855: }
1.29 www 6856: }
1.83 www 6857:
1.148 www 6858: if ($checkreferer) {
1.620 albertel 6859: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6860: unless ($refuri) {
1.800 albertel 6861: foreach my $key (keys(%env)) {
6862: if ($key=~/^httpref\..*\*/) {
6863: my $pattern=$key;
1.156 www 6864: $pattern=~s/^httpref\.\/res\///;
1.148 www 6865: $pattern=~s/\*/\[\^\/\]\+/g;
6866: $pattern=~s/\//\\\//g;
1.152 www 6867: if ($orguri=~/$pattern/) {
1.800 albertel 6868: $refuri=$env{$key};
1.148 www 6869: }
6870: }
1.191 harris41 6871: }
1.148 www 6872: }
1.232 www 6873:
1.148 www 6874: if ($refuri) {
1.152 www 6875: $refuri=&declutter($refuri);
1.232 www 6876: my ($match,$cond)=&is_on_map($refuri);
6877: if ($match) {
6878: my $refstatecond=$cond;
1.620 albertel 6879: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6880: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6881: my $value = $1;
6882: if ($priv eq 'bre') {
6883: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6884: if (@blockers > 0) {
6885: $thisallowed = 'B';
6886: } else {
6887: $thisallowed.=$value;
6888: }
6889: } else {
6890: $thisallowed.=$value;
6891: }
1.53 www 6892: $uri=$refuri;
6893: $statecond=$refstatecond;
1.52 www 6894: }
6895: }
1.148 www 6896: }
1.29 www 6897: }
1.52 www 6898: }
1.29 www 6899:
1.52 www 6900: #
1.103 harris41 6901: # Gathered now: all privileges that could apply, and condition number
1.52 www 6902: #
6903: #
6904: # Full or no access?
6905: #
1.29 www 6906:
1.52 www 6907: if ($thisallowed=~/F/) {
6908: return 'F';
6909: }
1.29 www 6910:
1.52 www 6911: unless ($thisallowed) {
6912: return '';
6913: }
1.29 www 6914:
1.52 www 6915: # Restrictions exist, deal with them
6916: #
6917: # C:according to course preferences
6918: # R:according to resource settings
6919: # L:unless locked
6920: # X:according to user session state
6921: #
6922:
6923: # Possibly locked functionality, check all courses
1.54 www 6924: # Locks might take effect only after 10 minutes cache expiration for other
6925: # courses, and 2 minutes for current course
1.52 www 6926:
6927: my $envkey;
6928: if ($thisallowed=~/L/) {
1.1000 raeburn 6929: foreach $envkey (keys(%env)) {
1.54 www 6930: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6931: my $courseid=$2;
6932: my $roleid=$1.'.'.$2;
1.92 www 6933: $courseid=~s/^\///;
1.54 www 6934: my $expiretime=600;
1.620 albertel 6935: if ($env{'request.role'} eq $roleid) {
1.54 www 6936: $expiretime=120;
6937: }
6938: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6939: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6940: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6941: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6942: }
1.620 albertel 6943: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6944: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6945: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6946: &log($env{'user.domain'},$env{'user.name'},
6947: $env{'user.home'},
1.57 www 6948: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6949: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6950: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6951: return '';
6952: }
6953: }
1.620 albertel 6954: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6955: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6956: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6957: &log($env{'user.domain'},$env{'user.name'},
6958: $env{'user.home'},
1.57 www 6959: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6960: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6961: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6962: return '';
6963: }
6964: }
6965: }
1.29 www 6966: }
1.52 www 6967: }
6968:
6969: #
6970: # Rest of the restrictions depend on selected course
6971: #
6972:
1.620 albertel 6973: unless ($env{'request.course.id'}) {
1.766 albertel 6974: if ($thisallowed eq 'A') {
6975: return 'A';
1.814 raeburn 6976: } elsif ($thisallowed eq 'B') {
6977: return 'B';
1.766 albertel 6978: } else {
6979: return '1';
6980: }
1.52 www 6981: }
1.29 www 6982:
1.52 www 6983: #
6984: # Now user is definitely in a course
6985: #
1.53 www 6986:
6987:
6988: # Course preferences
6989:
6990: if ($thisallowed=~/C/) {
1.620 albertel 6991: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6992: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6993: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6994: =~/\Q$rolecode\E/) {
1.1103 raeburn 6995: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6996: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6997: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6998: $env{'request.course.id'});
6999: }
1.237 www 7000: return '';
7001: }
7002:
1.620 albertel 7003: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7004: =~/\Q$unamedom\E/) {
1.1103 raeburn 7005: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7006: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7007: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7008: $env{'request.course.id'});
7009: }
1.54 www 7010: return '';
7011: }
1.53 www 7012: }
7013:
7014: # Resource preferences
7015:
7016: if ($thisallowed=~/R/) {
1.620 albertel 7017: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7018: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7019: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7020: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7021: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7022: }
7023: return '';
1.54 www 7024: }
1.53 www 7025: }
1.30 www 7026:
1.246 www 7027: # Restricted by state or randomout?
1.30 www 7028:
1.52 www 7029: if ($thisallowed=~/X/) {
1.620 albertel 7030: if ($env{'acc.randomout'}) {
1.579 albertel 7031: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7032: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7033: return '';
7034: }
1.247 www 7035: }
7036: if (&condval($statecond)) {
1.52 www 7037: return '2';
7038: } else {
7039: return '';
7040: }
7041: }
1.30 www 7042:
1.766 albertel 7043: if ($thisallowed eq 'A') {
7044: return 'A';
1.814 raeburn 7045: } elsif ($thisallowed eq 'B') {
7046: return 'B';
1.766 albertel 7047: }
1.52 www 7048: return 'F';
1.232 www 7049: }
1.1162 raeburn 7050:
1.1192 raeburn 7051: # ------------------------------------------- Check construction space access
7052:
7053: sub constructaccess {
7054: my ($url,$setpriv)=@_;
7055:
7056: # We do not allow editing of previous versions of files
7057: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7058:
7059: # Get username and domain from URL
7060: my ($ownername,$ownerdomain,$ownerhome);
7061:
7062: ($ownerdomain,$ownername) =
7063: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7064:
7065: # The URL does not really point to any authorspace, forget it
7066: unless (($ownername) && ($ownerdomain)) { return ''; }
7067:
7068: # Now we need to see if the user has access to the authorspace of
7069: # $ownername at $ownerdomain
7070:
7071: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7072: # Real author for this?
7073: $ownerhome = $env{'user.home'};
7074: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7075: return ($ownername,$ownerdomain,$ownerhome);
7076: }
7077: } else {
7078: # Co-author for this?
7079: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7080: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7081: $ownerhome = &homeserver($ownername,$ownerdomain);
7082: return ($ownername,$ownerdomain,$ownerhome);
7083: }
7084: }
7085:
7086: # We don't have any access right now. If we are not possibly going to do anything about this,
7087: # we might as well leave
7088: unless ($setpriv) { return ''; }
7089:
7090: # Backdoor access?
7091: my $allowed=&allowed('eco',$ownerdomain);
7092: # Nope
7093: unless ($allowed) { return ''; }
7094: # Looks like we may have access, but could be locked by the owner of the construction space
7095: if ($allowed eq 'U') {
7096: my %blocked=&get('environment',['domcoord.author'],
7097: $ownerdomain,$ownername);
7098: # Is blocked by owner
7099: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7100: }
7101: if (($allowed eq 'F') || ($allowed eq 'U')) {
7102: # Grant temporary access
7103: my $then=$env{'user.login.time'};
1.1209 raeburn 7104: my $update=$env{'user.update.time'};
1.1192 raeburn 7105: if (!$update) { $update = $then; }
7106: my $refresh=$env{'user.refresh.time'};
7107: if (!$refresh) { $refresh = $update; }
7108: my $now = time;
7109: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7110: $now,'ca','constructaccess');
7111: $ownerhome = &homeserver($ownername,$ownerdomain);
7112: return($ownername,$ownerdomain,$ownerhome);
7113: }
7114: # No business here
7115: return '';
7116: }
7117:
1.1162 raeburn 7118: sub get_comm_blocks {
7119: my ($cdom,$cnum) = @_;
7120: if ($cdom eq '' || $cnum eq '') {
7121: return unless ($env{'request.course.id'});
7122: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7123: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7124: }
7125: my %commblocks;
7126: my $hashid=$cdom.'_'.$cnum;
7127: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7128: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7129: %commblocks = %{$blocksref};
7130: } else {
7131: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7132: my $cachetime = 600;
7133: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7134: }
7135: return %commblocks;
7136: }
7137:
7138: sub has_comm_blocking {
7139: my ($priv,$symb,$uri,$blocks) = @_;
7140: return unless ($env{'request.course.id'});
7141: return unless ($priv eq 'bre');
7142: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7143: my %commblocks;
7144: if (ref($blocks) eq 'HASH') {
7145: %commblocks = %{$blocks};
7146: } else {
7147: %commblocks = &get_comm_blocks();
7148: }
7149: return unless (keys(%commblocks) > 0);
7150: if (!$symb) { $symb=&symbread($uri,1); }
7151: my ($map,$resid,undef)=&decode_symb($symb);
7152: my %tocheck = (
7153: maps => $map,
7154: resources => $symb,
7155: );
7156: my @blockers;
7157: my $now = time;
1.1163 raeburn 7158: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7159: foreach my $block (keys(%commblocks)) {
7160: if ($block =~ /^(\d+)____(\d+)$/) {
7161: my ($start,$end) = ($1,$2);
7162: if ($start <= $now && $end >= $now) {
7163: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7164: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7165: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7166: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7167: unless (grep(/^\Q$block\E$/,@blockers)) {
7168: push(@blockers,$block);
7169: }
7170: }
7171: }
7172: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7173: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7174: unless (grep(/^\Q$block\E$/,@blockers)) {
7175: push(@blockers,$block);
7176: }
7177: }
7178: }
7179: }
7180: }
7181: }
7182: } elsif ($block =~ /^firstaccess____(.+)$/) {
7183: my $item = $1;
1.1163 raeburn 7184: my @to_test;
1.1162 raeburn 7185: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7186: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7187: my $check_interval;
7188: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7189: my @interval;
7190: my $type = 'map';
7191: if ($item eq 'course') {
7192: $type = 'course';
7193: @interval=&EXT("resource.0.interval");
7194: } else {
7195: if ($item =~ /___\d+___/) {
7196: $type = 'resource';
7197: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7198: if (ref($navmap)) {
7199: my $res = $navmap->getBySymb($item);
7200: push(@to_test,$res);
7201: }
1.1162 raeburn 7202: } else {
7203: my $mapsymb = &symbread($item,1);
7204: if ($mapsymb) {
7205: if (ref($navmap)) {
7206: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7207: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7208: foreach my $res (@to_test) {
1.1162 raeburn 7209: my $symb = $res->symb();
7210: next if ($symb eq $mapsymb);
7211: if ($symb ne '') {
7212: @interval=&EXT("resource.0.interval",$symb);
7213: last;
7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220: if ($interval[0] =~ /\d+/) {
7221: my $first_access;
7222: if ($type eq 'resource') {
7223: $first_access=&get_first_access($interval[1],$item);
7224: } elsif ($type eq 'map') {
7225: $first_access=&get_first_access($interval[1],undef,$item);
7226: } else {
7227: $first_access=&get_first_access($interval[1]);
7228: }
7229: if ($first_access) {
7230: my $timesup = $first_access+$interval[0];
7231: if ($timesup > $now) {
1.1163 raeburn 7232: foreach my $res (@to_test) {
7233: if ($res->is_problem()) {
7234: if ($res->completable()) {
7235: unless (grep(/^\Q$block\E$/,@blockers)) {
7236: push(@blockers,$block);
7237: }
7238: last;
7239: }
7240: }
1.1162 raeburn 7241: }
7242: }
7243: }
7244: }
7245: }
7246: }
7247: }
7248: }
7249: }
7250: return @blockers;
7251: }
7252:
7253: sub check_docs_block {
7254: my ($docsblock,$tocheck) =@_;
7255: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7256: return;
7257: }
7258: if (ref($docsblock->{'maps'}) eq 'HASH') {
7259: if ($tocheck->{'maps'}) {
7260: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7261: return 1;
7262: }
7263: }
7264: }
7265: if (ref($docsblock->{'resources'}) eq 'HASH') {
7266: if ($tocheck->{'resources'}) {
7267: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7268: return 1;
7269: }
7270: }
7271: }
7272: return;
7273: }
7274:
1.1133 foxr 7275: #
7276: # Removes the versino from a URI and
7277: # splits it in to its filename and path to the filename.
7278: # Seems like File::Basename could have done this more clearly.
7279: # Parameters:
7280: # $uri - input URI
7281: # Returns:
7282: # Two element list consisting of
7283: # $pathname - the URI up to and excluding the trailing /
7284: # $filename - The part of the URI following the last /
7285: # NOTE:
7286: # Another realization of this is simply:
7287: # use File::Basename;
7288: # ...
7289: # $uri = shift;
7290: # $filename = basename($uri);
7291: # $path = dirname($uri);
7292: # return ($filename, $path);
7293: #
7294: # The implementation below is probably faster however.
7295: #
1.710 albertel 7296: sub split_uri_for_cond {
7297: my $uri=&deversion(&declutter(shift));
7298: my @uriparts=split(/\//,$uri);
7299: my $filename=pop(@uriparts);
7300: my $pathname=join('/',@uriparts);
7301: return ($pathname,$filename);
7302: }
1.232 www 7303: # --------------------------------------------------- Is a resource on the map?
7304:
7305: sub is_on_map {
1.710 albertel 7306: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7307: #Trying to find the conditional for the file
1.620 albertel 7308: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7309: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7310: if ($match) {
1.289 bowersj2 7311: return (1,$1);
7312: } else {
1.434 www 7313: return (0,0);
1.289 bowersj2 7314: }
1.12 www 7315: }
7316:
1.427 www 7317: # --------------------------------------------------------- Get symb from alias
7318:
7319: sub get_symb_from_alias {
7320: my $symb=shift;
7321: my ($map,$resid,$url)=&decode_symb($symb);
7322: # Already is a symb
7323: if ($url) { return $symb; }
7324: # Must be an alias
7325: my $aliassymb='';
7326: my %bighash;
1.620 albertel 7327: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7328: &GDBM_READER(),0640)) {
7329: my $rid=$bighash{'mapalias_'.$symb};
7330: if ($rid) {
7331: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7332: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7333: $resid,$bighash{'src_'.$rid});
1.427 www 7334: }
7335: untie %bighash;
7336: }
7337: return $aliassymb;
7338: }
7339:
1.12 www 7340: # ----------------------------------------------------------------- Define Role
7341:
7342: sub definerole {
7343: if (allowed('mcr','/')) {
7344: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7345: foreach my $role (split(':',$sysrole)) {
7346: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7347: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7348: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7349: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7350: return "refused:s:$crole&$cqual";
7351: }
7352: }
1.191 harris41 7353: }
1.800 albertel 7354: foreach my $role (split(':',$domrole)) {
7355: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7356: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7357: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7358: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7359: return "refused:d:$crole&$cqual";
7360: }
7361: }
1.191 harris41 7362: }
1.800 albertel 7363: foreach my $role (split(':',$courole)) {
7364: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7365: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7366: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7367: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7368: return "refused:c:$crole&$cqual";
7369: }
7370: }
1.191 harris41 7371: }
1.620 albertel 7372: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7373: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7374: "rolesdef_$rolename=".
7375: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7376: return reply($command,$env{'user.home'});
1.12 www 7377: } else {
7378: return 'refused';
7379: }
1.105 harris41 7380: }
7381:
7382: # ---------------- Make a metadata query against the network of library servers
7383:
7384: sub metadata_query {
1.1237 raeburn 7385: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7386: my %rhash;
1.845 albertel 7387: my %libserv = &all_library();
1.244 matthew 7388: my @server_list = (defined($server_array) ? @$server_array
7389: : keys(%libserv) );
7390: for my $server (@server_list) {
1.1237 raeburn 7391: my $domains = '';
7392: if (ref($domains_hash) eq 'HASH') {
7393: $domains = $domains_hash->{$server};
7394: }
1.118 harris41 7395: unless ($custom or $customshow) {
1.1237 raeburn 7396: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7397: $rhash{$server}=$reply;
7398: }
7399: else {
7400: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7401: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7402: $server);
7403: $rhash{$server}=$reply;
7404: }
1.112 harris41 7405: }
1.118 harris41 7406: return \%rhash;
1.240 www 7407: }
7408:
7409: # ----------------------------------------- Send log queries and wait for reply
7410:
7411: sub log_query {
7412: my ($uname,$udom,$query,%filters)=@_;
7413: my $uhome=&homeserver($uname,$udom);
7414: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7415: my $uhost=&hostname($uhome);
1.800 albertel 7416: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7417: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7418: $uhome);
1.479 albertel 7419: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7420: return get_query_reply($queryid);
7421: }
7422:
1.818 raeburn 7423: # -------------------------- Update MySQL table for portfolio file
7424:
7425: sub update_portfolio_table {
1.821 raeburn 7426: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7427: if ($group ne '') {
7428: $file_name =~s /^\Q$group\E//;
7429: }
1.818 raeburn 7430: my $homeserver = &homeserver($uname,$udom);
7431: my $queryid=
1.821 raeburn 7432: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7433: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7434: my $reply = &get_query_reply($queryid);
7435: return $reply;
7436: }
7437:
1.899 raeburn 7438: # -------------------------- Update MySQL allusers table
7439:
7440: sub update_allusers_table {
7441: my ($uname,$udom,$names) = @_;
7442: my $homeserver = &homeserver($uname,$udom);
7443: my $queryid=
7444: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7445: 'lastname='.&escape($names->{'lastname'}).'%%'.
7446: 'firstname='.&escape($names->{'firstname'}).'%%'.
7447: 'middlename='.&escape($names->{'middlename'}).'%%'.
7448: 'generation='.&escape($names->{'generation'}).'%%'.
7449: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7450: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7451: return;
1.899 raeburn 7452: }
7453:
1.508 raeburn 7454: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7455:
7456: sub fetch_enrollment_query {
1.511 raeburn 7457: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7458: my $homeserver;
1.547 raeburn 7459: my $maxtries = 1;
1.508 raeburn 7460: if ($context eq 'automated') {
7461: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7462: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7463: } else {
7464: $homeserver = &homeserver($cnum,$dom);
7465: }
1.838 albertel 7466: my $host=&hostname($homeserver);
1.506 raeburn 7467: my $cmd = '';
1.1000 raeburn 7468: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7469: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7470: }
7471: $cmd =~ s/%%$//;
7472: $cmd = &escape($cmd);
7473: my $query = 'fetchenrollment';
1.620 albertel 7474: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7475: unless ($queryid=~/^\Q$host\E\_/) {
7476: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7477: return 'error: '.$queryid;
7478: }
1.506 raeburn 7479: my $reply = &get_query_reply($queryid);
1.547 raeburn 7480: my $tries = 1;
7481: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7482: $reply = &get_query_reply($queryid);
7483: $tries ++;
7484: }
1.526 raeburn 7485: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7486: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7487: } else {
1.901 albertel 7488: my @responses = split(/:/,$reply);
1.515 raeburn 7489: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7490: foreach my $line (@responses) {
7491: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7492: $$replyref{$key} = $value;
7493: }
7494: } else {
1.1117 foxr 7495: my $pathname = LONCAPA::tempdir();
1.800 albertel 7496: foreach my $line (@responses) {
7497: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7498: $$replyref{$key} = $value;
7499: if ($value > 0) {
1.800 albertel 7500: foreach my $item (@{$$affiliatesref{$key}}) {
7501: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7502: my $destname = $pathname.'/'.$filename;
7503: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7504: if ($xml_classlist =~ /^error/) {
7505: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7506: } else {
1.506 raeburn 7507: if ( open(FILE,">$destname") ) {
7508: print FILE &unescape($xml_classlist);
7509: close(FILE);
1.526 raeburn 7510: } else {
7511: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7512: }
7513: }
7514: }
7515: }
7516: }
7517: }
7518: return 'ok';
7519: }
7520: return 'error';
7521: }
7522:
1.242 www 7523: sub get_query_reply {
7524: my $queryid=shift;
1.1117 foxr 7525: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7526: my $reply='';
7527: for (1..100) {
7528: sleep 2;
7529: if (-e $replyfile.'.end') {
1.448 albertel 7530: if (open(my $fh,$replyfile)) {
1.904 albertel 7531: $reply = join('',<$fh>);
7532: close($fh);
1.240 www 7533: } else { return 'error: reply_file_error'; }
1.242 www 7534: return &unescape($reply);
7535: }
1.240 www 7536: }
1.242 www 7537: return 'timeout:'.$queryid;
1.240 www 7538: }
7539:
7540: sub courselog_query {
1.241 www 7541: #
7542: # possible filters:
7543: # url: url or symb
7544: # username
7545: # domain
7546: # action: view, submit, grade
7547: # start: timestamp
7548: # end: timestamp
7549: #
1.240 www 7550: my (%filters)=@_;
1.620 albertel 7551: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7552: if ($filters{'url'}) {
7553: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7554: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7555: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7556: }
1.620 albertel 7557: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7558: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7559: return &log_query($cname,$cdom,'courselog',%filters);
7560: }
7561:
7562: sub userlog_query {
1.858 raeburn 7563: #
7564: # possible filters:
7565: # action: log check role
7566: # start: timestamp
7567: # end: timestamp
7568: #
1.240 www 7569: my ($uname,$udom,%filters)=@_;
7570: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7571: }
7572:
1.506 raeburn 7573: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7574:
7575: sub auto_run {
1.508 raeburn 7576: my ($cnum,$cdom) = @_;
1.876 raeburn 7577: my $response = 0;
7578: my $settings;
7579: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7580: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7581: $settings = $domconfig{'autoenroll'};
7582: if ($settings->{'run'} eq '1') {
7583: $response = 1;
7584: }
7585: } else {
1.934 raeburn 7586: my $homeserver;
7587: if (&is_course($cdom,$cnum)) {
7588: $homeserver = &homeserver($cnum,$cdom);
7589: } else {
7590: $homeserver = &domain($cdom,'primary');
7591: }
7592: if ($homeserver ne 'no_host') {
7593: $response = &reply('autorun:'.$cdom,$homeserver);
7594: }
1.876 raeburn 7595: }
1.506 raeburn 7596: return $response;
7597: }
1.776 albertel 7598:
1.506 raeburn 7599: sub auto_get_sections {
1.508 raeburn 7600: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7601: my $homeserver;
7602: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7603: $homeserver = &homeserver($cnum,$cdom);
7604: }
7605: if (!defined($homeserver)) {
7606: if ($cdom =~ /^$match_domain$/) {
7607: $homeserver = &domain($cdom,'primary');
7608: }
7609: }
7610: my @secs;
7611: if (defined($homeserver)) {
7612: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7613: unless ($response eq 'refused') {
7614: @secs = split(/:/,$response);
7615: }
1.506 raeburn 7616: }
7617: return @secs;
7618: }
1.776 albertel 7619:
1.506 raeburn 7620: sub auto_new_course {
1.1099 raeburn 7621: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7622: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7623: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7624: return $response;
7625: }
1.776 albertel 7626:
1.506 raeburn 7627: sub auto_validate_courseID {
1.508 raeburn 7628: my ($cnum,$cdom,$inst_course_id) = @_;
7629: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7630: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7631: return $response;
7632: }
1.776 albertel 7633:
1.1007 raeburn 7634: sub auto_validate_instcode {
1.1020 raeburn 7635: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7636: my ($homeserver,$response);
7637: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7638: $homeserver = &homeserver($cnum,$cdom);
7639: }
7640: if (!defined($homeserver)) {
7641: if ($cdom =~ /^$match_domain$/) {
7642: $homeserver = &domain($cdom,'primary');
7643: }
7644: }
1.1065 raeburn 7645: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7646: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7647: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7648: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7649: }
7650:
1.506 raeburn 7651: sub auto_create_password {
1.873 raeburn 7652: my ($cnum,$cdom,$authparam,$udom) = @_;
7653: my ($homeserver,$response);
1.506 raeburn 7654: my $create_passwd = 0;
7655: my $authchk = '';
1.873 raeburn 7656: if ($udom =~ /^$match_domain$/) {
7657: $homeserver = &domain($udom,'primary');
7658: }
7659: if ($homeserver eq '') {
7660: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7661: $homeserver = &homeserver($cnum,$cdom);
7662: }
7663: }
7664: if ($homeserver eq '') {
7665: $authchk = 'nodomain';
1.506 raeburn 7666: } else {
1.873 raeburn 7667: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7668: if ($response eq 'refused') {
7669: $authchk = 'refused';
7670: } else {
1.901 albertel 7671: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7672: }
1.506 raeburn 7673: }
7674: return ($authparam,$create_passwd,$authchk);
7675: }
7676:
1.706 raeburn 7677: sub auto_photo_permission {
7678: my ($cnum,$cdom,$students) = @_;
7679: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7680: my ($outcome,$perm_reqd,$conditions) =
7681: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7682: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7683: return (undef,undef);
7684: }
1.706 raeburn 7685: return ($outcome,$perm_reqd,$conditions);
7686: }
7687:
7688: sub auto_checkphotos {
7689: my ($uname,$udom,$pid) = @_;
7690: my $homeserver = &homeserver($uname,$udom);
7691: my ($result,$resulttype);
7692: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7693: &escape($uname).':'.&escape($pid),
7694: $homeserver));
1.709 albertel 7695: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7696: return (undef,undef);
7697: }
1.706 raeburn 7698: if ($outcome) {
7699: ($result,$resulttype) = split(/:/,$outcome);
7700: }
7701: return ($result,$resulttype);
7702: }
7703:
7704: sub auto_photochoice {
7705: my ($cnum,$cdom) = @_;
7706: my $homeserver = &homeserver($cnum,$cdom);
7707: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7708: &escape($cdom),
7709: $homeserver)));
1.709 albertel 7710: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7711: return (undef,undef);
7712: }
1.706 raeburn 7713: return ($update,$comment);
7714: }
7715:
7716: sub auto_photoupdate {
7717: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7718: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7719: my $host=&hostname($homeserver);
1.706 raeburn 7720: my $cmd = '';
7721: my $maxtries = 1;
1.800 albertel 7722: foreach my $affiliate (keys(%{$affiliatesref})) {
7723: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7724: }
7725: $cmd =~ s/%%$//;
7726: $cmd = &escape($cmd);
7727: my $query = 'institutionalphotos';
7728: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7729: unless ($queryid=~/^\Q$host\E\_/) {
7730: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7731: return 'error: '.$queryid;
7732: }
7733: my $reply = &get_query_reply($queryid);
7734: my $tries = 1;
7735: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7736: $reply = &get_query_reply($queryid);
7737: $tries ++;
7738: }
7739: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7740: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7741: } else {
7742: my @responses = split(/:/,$reply);
7743: my $outcome = shift(@responses);
7744: foreach my $item (@responses) {
7745: my ($key,$value) = split(/=/,$item);
7746: $$photo{$key} = $value;
7747: }
7748: return $outcome;
7749: }
7750: return 'error';
7751: }
7752:
1.521 raeburn 7753: sub auto_instcode_format {
1.793 albertel 7754: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7755: $cat_order) = @_;
1.521 raeburn 7756: my $courses = '';
1.772 raeburn 7757: my @homeservers;
1.521 raeburn 7758: if ($caller eq 'global') {
1.841 albertel 7759: my %servers = &get_servers($codedom,'library');
7760: foreach my $tryserver (keys(%servers)) {
7761: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7762: push(@homeservers,$tryserver);
7763: }
1.584 raeburn 7764: }
1.1022 raeburn 7765: } elsif ($caller eq 'requests') {
7766: if ($codedom =~ /^$match_domain$/) {
7767: my $chome = &domain($codedom,'primary');
7768: unless ($chome eq 'no_host') {
7769: push(@homeservers,$chome);
7770: }
7771: }
1.521 raeburn 7772: } else {
1.772 raeburn 7773: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7774: }
1.793 albertel 7775: foreach my $code (keys(%{$instcodes})) {
7776: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7777: }
7778: chop($courses);
1.772 raeburn 7779: my $ok_response = 0;
7780: my $response;
7781: while (@homeservers > 0 && $ok_response == 0) {
7782: my $server = shift(@homeservers);
7783: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7784: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7785: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7786: split(/:/,$response);
1.772 raeburn 7787: %{$codes} = (%{$codes},&str2hash($codes_str));
7788: push(@{$codetitles},&str2array($codetitles_str));
7789: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7790: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7791: $ok_response = 1;
7792: }
7793: }
7794: if ($ok_response) {
1.521 raeburn 7795: return 'ok';
1.772 raeburn 7796: } else {
7797: return $response;
1.521 raeburn 7798: }
7799: }
7800:
1.792 raeburn 7801: sub auto_instcode_defaults {
7802: my ($domain,$returnhash,$code_order) = @_;
7803: my @homeservers;
1.841 albertel 7804:
7805: my %servers = &get_servers($domain,'library');
7806: foreach my $tryserver (keys(%servers)) {
7807: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7808: push(@homeservers,$tryserver);
7809: }
1.792 raeburn 7810: }
1.841 albertel 7811:
1.792 raeburn 7812: my $response;
1.841 albertel 7813: foreach my $server (@homeservers) {
1.792 raeburn 7814: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7815: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7816:
7817: foreach my $pair (split(/\&/,$response)) {
7818: my ($name,$value)=split(/\=/,$pair);
7819: if ($name eq 'code_order') {
7820: @{$code_order} = split(/\&/,&unescape($value));
7821: } else {
7822: $returnhash->{&unescape($name)}=&unescape($value);
7823: }
7824: }
7825: return 'ok';
1.792 raeburn 7826: }
1.841 albertel 7827:
7828: return $response;
1.1003 raeburn 7829: }
7830:
7831: sub auto_possible_instcodes {
1.1007 raeburn 7832: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7833: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7834: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7835: return;
7836: }
1.1003 raeburn 7837: my (@homeservers,$uhome);
7838: if (defined(&domain($domain,'primary'))) {
7839: $uhome=&domain($domain,'primary');
7840: push(@homeservers,&domain($domain,'primary'));
7841: } else {
7842: my %servers = &get_servers($domain,'library');
7843: foreach my $tryserver (keys(%servers)) {
7844: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7845: push(@homeservers,$tryserver);
7846: }
7847: }
7848: }
7849: my $response;
7850: foreach my $server (@homeservers) {
7851: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7852: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7853: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7854: split(':',$response);
7855: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7856: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7857: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7858: my ($name,$value)=split('=',$item);
7859: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7860: }
7861: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7862: my ($name,$value)=split('=',$item);
7863: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7864: }
7865: return 'ok';
7866: }
7867: return $response;
7868: }
1.792 raeburn 7869:
1.1010 raeburn 7870: sub auto_courserequest_checks {
7871: my ($dom) = @_;
1.1020 raeburn 7872: my ($homeserver,%validations);
7873: if ($dom =~ /^$match_domain$/) {
7874: $homeserver = &domain($dom,'primary');
7875: }
7876: unless ($homeserver eq 'no_host') {
7877: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7878: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7879: my @items = split(/&/,$response);
7880: foreach my $item (@items) {
7881: my ($key,$value) = split('=',$item);
7882: $validations{&unescape($key)} = &thaw_unescape($value);
7883: }
7884: }
7885: }
1.1010 raeburn 7886: return %validations;
7887: }
7888:
1.1020 raeburn 7889: sub auto_courserequest_validation {
1.1255 raeburn 7890: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7891: my ($homeserver,$response);
7892: if ($dom =~ /^$match_domain$/) {
7893: $homeserver = &domain($dom,'primary');
7894: }
1.1255 raeburn 7895: unless ($homeserver eq 'no_host') {
7896: my $customdata;
7897: if (ref($custominfo) eq 'HASH') {
7898: $customdata = &freeze_escape($custominfo);
7899: }
1.1020 raeburn 7900: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7901: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7902: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7903: $customdata,$homeserver));
1.1020 raeburn 7904: }
7905: return $response;
7906: }
7907:
1.777 albertel 7908: sub auto_validate_class_sec {
1.918 raeburn 7909: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7910: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7911: my $ownerlist;
7912: if (ref($owners) eq 'ARRAY') {
7913: $ownerlist = join(',',@{$owners});
7914: } else {
7915: $ownerlist = $owners;
7916: }
1.773 raeburn 7917: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7918: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7919: return $response;
7920: }
7921:
1.1248 raeburn 7922: sub auto_crsreq_update {
7923: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 7924: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 7925: my ($homeserver,%crsreqresponse);
7926: if ($cdom =~ /^$match_domain$/) {
7927: $homeserver = &domain($cdom,'primary');
7928: }
7929: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7930: my $info;
7931: if (ref($inbound) eq 'HASH') {
7932: $info = &freeze_escape($inbound);
7933: }
7934: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7935: ':'.&escape($action).':'.&escape($ownername).':'.
7936: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 7937: &escape($title).':'.&escape($code).':'.
7938: &escape($accessstart).':'.&escape($accessend).':'.$info,
7939: $homeserver);
1.1248 raeburn 7940: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7941: my @items = split(/&/,$response);
7942: foreach my $item (@items) {
7943: my ($key,$value) = split('=',$item);
7944: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7945: }
7946: }
7947: }
7948: return \%crsreqresponse;
7949: }
7950:
1.679 raeburn 7951: # ------------------------------------------------------- Course Group routines
7952:
7953: sub get_coursegroups {
1.809 raeburn 7954: my ($cdom,$cnum,$group,$namespace) = @_;
7955: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7956: }
7957:
1.679 raeburn 7958: sub modify_coursegroup {
7959: my ($cdom,$cnum,$groupsettings) = @_;
7960: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7961: }
7962:
1.809 raeburn 7963: sub toggle_coursegroup_status {
7964: my ($cdom,$cnum,$group,$action) = @_;
7965: my ($from_namespace,$to_namespace);
7966: if ($action eq 'delete') {
7967: $from_namespace = 'coursegroups';
7968: $to_namespace = 'deleted_groups';
7969: } else {
7970: $from_namespace = 'deleted_groups';
7971: $to_namespace = 'coursegroups';
7972: }
7973: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7974: if (my $tmp = &error(%curr_group)) {
7975: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7976: return ('read error',$tmp);
7977: } else {
7978: my %savedsettings = %curr_group;
1.809 raeburn 7979: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7980: my $deloutcome;
7981: if ($result eq 'ok') {
1.809 raeburn 7982: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7983: } else {
7984: return ('write error',$result);
7985: }
7986: if ($deloutcome eq 'ok') {
7987: return 'ok';
7988: } else {
7989: return ('delete error',$deloutcome);
7990: }
7991: }
7992: }
7993:
1.679 raeburn 7994: sub modify_group_roles {
1.957 raeburn 7995: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7996: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7997: my $role = 'gr/'.&escape($userprivs);
7998: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7999: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8000: if ($result eq 'ok') {
8001: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8002: }
1.679 raeburn 8003: return $result;
8004: }
8005:
8006: sub modify_coursegroup_membership {
8007: my ($cdom,$cnum,$membership) = @_;
8008: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8009: return $result;
8010: }
8011:
1.682 raeburn 8012: sub get_active_groups {
8013: my ($udom,$uname,$cdom,$cnum) = @_;
8014: my $now = time;
8015: my %groups = ();
8016: foreach my $key (keys(%env)) {
1.811 albertel 8017: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8018: my ($start,$end) = split(/\./,$env{$key});
8019: if (($end!=0) && ($end<$now)) { next; }
8020: if (($start!=0) && ($start>$now)) { next; }
8021: if ($1 eq $cdom && $2 eq $cnum) {
8022: $groups{$3} = $env{$key} ;
8023: }
8024: }
8025: }
8026: return %groups;
8027: }
8028:
1.683 raeburn 8029: sub get_group_membership {
8030: my ($cdom,$cnum,$group) = @_;
8031: return(&dump('groupmembership',$cdom,$cnum,$group));
8032: }
8033:
8034: sub get_users_groups {
8035: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8036: my @usersgroups;
1.683 raeburn 8037: my $cachetime=1800;
8038:
8039: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8040: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8041: if (defined($cached)) {
1.734 albertel 8042: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8043: } else {
8044: $grouplist = '';
1.816 raeburn 8045: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8046: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8047: my $access_end = $env{'course.'.$courseid.
8048: '.default_enrollment_end_date'};
8049: my $now = time;
8050: foreach my $key (keys(%roleshash)) {
8051: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8052: my $group = $1;
8053: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8054: my $start = $2;
8055: my $end = $1;
8056: if ($start == -1) { next; } # deleted from group
8057: if (($start!=0) && ($start>$now)) { next; }
8058: if (($end!=0) && ($end<$now)) {
8059: if ($access_end && $access_end < $now) {
8060: if ($access_end - $end < 86400) {
8061: push(@usersgroups,$group);
1.733 raeburn 8062: }
8063: }
1.817 raeburn 8064: next;
1.733 raeburn 8065: }
1.817 raeburn 8066: push(@usersgroups,$group);
1.683 raeburn 8067: }
8068: }
8069: }
1.817 raeburn 8070: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8071: $grouplist = join(':',@usersgroups);
8072: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8073: }
1.733 raeburn 8074: return @usersgroups;
1.683 raeburn 8075: }
8076:
8077: sub devalidate_getgroups_cache {
8078: my ($udom,$uname,$cdom,$cnum)=@_;
8079: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8080:
1.683 raeburn 8081: my $hashid="$udom:$uname:$courseid";
8082: &devalidate_cache_new('getgroups',$hashid);
8083: }
8084:
1.12 www 8085: # ------------------------------------------------------------------ Plain Text
8086:
8087: sub plaintext {
1.988 raeburn 8088: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8089: if ($short =~ m{^cr/}) {
1.758 albertel 8090: return (split('/',$short))[-1];
8091: }
1.742 raeburn 8092: if (!defined($cid)) {
8093: $cid = $env{'request.course.id'};
8094: }
8095: my %rolenames = (
1.1008 raeburn 8096: Course => 'std',
8097: Community => 'alt1',
1.742 raeburn 8098: );
1.1037 raeburn 8099: if ($cid ne '') {
8100: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8101: unless ($forcedefault) {
8102: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8103: &Apache::lonlocal::mt_escape(\$roletext);
8104: return &Apache::lonlocal::mt($roletext);
8105: }
8106: }
8107: }
8108: if ((defined($type)) && (defined($rolenames{$type})) &&
8109: (defined($rolenames{$type})) &&
8110: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8111: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8112: } elsif ($cid ne '') {
8113: my $crstype = $env{'course.'.$cid.'.type'};
8114: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8115: (defined($prp{$short}{$rolenames{$crstype}}))) {
8116: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8117: }
1.742 raeburn 8118: }
1.1037 raeburn 8119: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8120: }
8121:
8122: # ----------------------------------------------------------------- Assign Role
8123:
8124: sub assignrole {
1.957 raeburn 8125: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8126: $context)=@_;
1.21 www 8127: my $mrole;
8128: if ($role =~ /^cr\//) {
1.393 www 8129: my $cwosec=$url;
1.811 albertel 8130: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8131: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8132: my $refused = 1;
8133: if ($context eq 'requestcourses') {
8134: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8135: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8136: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8137: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8138: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8139: if ($crsenv{'internal.courseowner'} eq
8140: $env{'user.name'}.':'.$env{'user.domain'}) {
8141: $refused = '';
8142: }
8143: }
8144: }
8145: }
8146: }
8147: if ($refused) {
8148: &logthis('Refused custom assignrole: '.
8149: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8150: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8151: return 'refused';
8152: }
1.104 www 8153: }
1.21 www 8154: $mrole='cr';
1.678 raeburn 8155: } elsif ($role =~ /^gr\//) {
8156: my $cwogrp=$url;
1.811 albertel 8157: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8158: unless (&allowed('mdg',$cwogrp)) {
8159: &logthis('Refused group assignrole: '.
8160: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8161: $env{'user.name'}.' at '.$env{'user.domain'});
8162: return 'refused';
8163: }
8164: $mrole='gr';
1.21 www 8165: } else {
1.82 www 8166: my $cwosec=$url;
1.811 albertel 8167: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8168: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8169: my $refused;
8170: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8171: if (!(&allowed('c'.$role,$url))) {
8172: $refused = 1;
8173: }
8174: } else {
8175: $refused = 1;
8176: }
1.947 raeburn 8177: if ($refused) {
1.1045 raeburn 8178: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8179: if (!$selfenroll && $context eq 'course') {
8180: my %crsenv;
8181: if ($role eq 'cc' || $role eq 'co') {
8182: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8183: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8184: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8185: if ($crsenv{'internal.courseowner'} eq
8186: $env{'user.name'}.':'.$env{'user.domain'}) {
8187: $refused = '';
8188: }
8189: }
8190: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8191: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8192: if ($crsenv{'internal.courseowner'} eq
8193: $env{'user.name'}.':'.$env{'user.domain'}) {
8194: $refused = '';
8195: }
8196: }
8197: }
8198: }
8199: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8200: $refused = '';
1.1017 raeburn 8201: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8202: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8203: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8204: my $wrongcc;
8205: if ($cnum =~ /^$match_community$/) {
8206: $wrongcc = 1 if ($role eq 'cc');
8207: } else {
8208: $wrongcc = 1 if ($role eq 'co');
8209: }
8210: unless ($wrongcc) {
8211: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8212: if ($crsenv{'internal.courseowner'} eq
8213: $env{'user.name'}.':'.$env{'user.domain'}) {
8214: $refused = '';
8215: }
1.1017 raeburn 8216: }
8217: }
1.1183 raeburn 8218: } elsif ($context eq 'requestauthor') {
8219: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8220: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8221: if ($env{'environment.requestauthor'} eq 'automatic') {
8222: $refused = '';
8223: } else {
8224: my %domdefaults = &get_domain_defaults($udom);
8225: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8226: my $checkbystatus;
8227: if ($env{'user.adv'}) {
8228: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8229: if ($disposition eq 'automatic') {
8230: $refused = '';
8231: } elsif ($disposition eq '') {
8232: $checkbystatus = 1;
8233: }
8234: } else {
8235: $checkbystatus = 1;
8236: }
8237: if ($checkbystatus) {
8238: if ($env{'environment.inststatus'}) {
8239: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8240: foreach my $type (@inststatuses) {
8241: if (($type ne '') &&
8242: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8243: $refused = '';
8244: }
8245: }
8246: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8247: $refused = '';
8248: }
8249: }
8250: }
8251: }
8252: }
1.1017 raeburn 8253: }
8254: if ($refused) {
1.947 raeburn 8255: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8256: ' '.$role.' '.$end.' '.$start.' by '.
8257: $env{'user.name'}.' at '.$env{'user.domain'});
8258: return 'refused';
8259: }
1.932 raeburn 8260: }
1.1131 raeburn 8261: } elsif ($role eq 'au') {
8262: if ($url ne '/'.$udom.'/') {
8263: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8264: ' to assign author role for '.$uname.':'.$udom.
8265: ' in domain: '.$url.' refused (wrong domain).');
8266: return 'refused';
8267: }
1.104 www 8268: }
1.21 www 8269: $mrole=$role;
8270: }
1.620 albertel 8271: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8272: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8273: if ($end) { $command.='_'.$end; }
1.21 www 8274: if ($start) {
8275: if ($end) {
1.81 www 8276: $command.='_'.$start;
1.21 www 8277: } else {
1.81 www 8278: $command.='_0_'.$start;
1.21 www 8279: }
8280: }
1.739 raeburn 8281: my $origstart = $start;
8282: my $origend = $end;
1.957 raeburn 8283: my $delflag;
1.357 www 8284: # actually delete
8285: if ($deleteflag) {
1.373 www 8286: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8287: # modify command to delete the role
1.620 albertel 8288: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8289: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8290: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8291: # set start and finish to negative values for userrolelog
8292: $start=-1;
8293: $end=-1;
1.957 raeburn 8294: $delflag = 1;
1.357 www 8295: }
8296: }
8297: # send command
1.349 www 8298: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8299: # log new user role if status is ok
1.349 www 8300: if ($answer eq 'ok') {
1.663 raeburn 8301: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8302: if (($role eq 'cc') || ($role eq 'in') ||
8303: ($role eq 'ep') || ($role eq 'ad') ||
8304: ($role eq 'ta') || ($role eq 'st') ||
8305: ($role=~/^cr/) || ($role eq 'gr') ||
8306: ($role eq 'co')) {
1.1200 raeburn 8307: # for course roles, perform group memberships changes triggered by role change.
8308: unless ($role =~ /^gr/) {
8309: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8310: $origstart,$selfenroll,$context);
8311: }
1.1184 raeburn 8312: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8313: $selfenroll,$context);
8314: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8315: ($role eq 'au') || ($role eq 'dc')) {
8316: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8317: $context);
8318: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8319: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8320: $context);
8321: }
1.1053 raeburn 8322: if ($role eq 'cc') {
8323: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8324: }
1.349 www 8325: }
8326: return $answer;
1.169 harris41 8327: }
8328:
1.1053 raeburn 8329: sub autoupdate_coowners {
8330: my ($url,$end,$start,$uname,$udom) = @_;
8331: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8332: if (($cdom ne '') && ($cnum ne '')) {
8333: my $now = time;
8334: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8335: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8336: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8337: my $instcode = $coursehash{'internal.coursecode'};
8338: if ($instcode ne '') {
1.1056 raeburn 8339: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8340: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8341: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8342: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8343: if ($result eq 'valid') {
8344: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8345: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8346: push(@newcoowners,$coowner);
8347: }
8348: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8349: push(@newcoowners,$uname.':'.$udom);
8350: }
8351: @newcoowners = sort(@newcoowners);
8352: } else {
8353: push(@newcoowners,$uname.':'.$udom);
8354: }
8355: } else {
8356: if ($coursehash{'internal.co-owners'}) {
8357: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8358: unless ($coowner eq $uname.':'.$udom) {
8359: push(@newcoowners,$coowner);
8360: }
8361: }
8362: unless (@newcoowners > 0) {
8363: $delcoowners = 1;
8364: $coowners = '';
8365: }
8366: }
8367: }
8368: if (@newcoowners || $delcoowners) {
8369: &store_coowners($cdom,$cnum,$coursehash{'home'},
8370: $delcoowners,@newcoowners);
8371: }
8372: }
8373: }
8374: }
8375: }
8376: }
8377: }
8378:
8379: sub store_coowners {
8380: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8381: my $cid = $cdom.'_'.$cnum;
8382: my ($coowners,$delresult,$putresult);
8383: if (@newcoowners) {
8384: $coowners = join(',',@newcoowners);
8385: my %coownershash = (
8386: 'internal.co-owners' => $coowners,
8387: );
8388: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8389: if ($putresult eq 'ok') {
8390: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8391: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8392: }
8393: }
8394: }
8395: if ($delcoowners) {
8396: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8397: if ($delresult eq 'ok') {
8398: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8399: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8400: }
8401: }
8402: }
8403: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8404: my %crsinfo =
8405: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8406: if (ref($crsinfo{$cid}) eq 'HASH') {
8407: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8408: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8409: }
8410: }
8411: }
8412:
1.169 harris41 8413: # -------------------------------------------------- Modify user authentication
1.197 www 8414: # Overrides without validation
8415:
1.169 harris41 8416: sub modifyuserauth {
8417: my ($udom,$uname,$umode,$upass)=@_;
8418: my $uhome=&homeserver($uname,$udom);
1.197 www 8419: unless (&allowed('mau',$udom)) { return 'refused'; }
8420: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8421: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8422: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8423: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8424: &escape($upass),$uhome);
1.620 albertel 8425: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8426: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8427: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8428: &log($udom,,$uname,$uhome,
1.620 albertel 8429: 'Authentication changed by '.$env{'user.domain'}.', '.
8430: $env{'user.name'}.', '.$umode.
1.197 www 8431: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8432: unless ($reply eq 'ok') {
1.197 www 8433: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8434: return 'error: '.$reply;
8435: }
1.170 harris41 8436: return 'ok';
1.80 www 8437: }
8438:
1.81 www 8439: # --------------------------------------------------------------- Modify a user
1.80 www 8440:
1.81 www 8441: sub modifyuser {
1.206 matthew 8442: my ($udom, $uname, $uid,
8443: $umode, $upass, $first,
8444: $middle, $last, $gene,
1.1058 raeburn 8445: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8446: $udom= &LONCAPA::clean_domain($udom);
8447: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8448: my $showcandelete = 'none';
8449: if (ref($candelete) eq 'ARRAY') {
8450: if (@{$candelete} > 0) {
8451: $showcandelete = join(', ',@{$candelete});
8452: }
8453: }
1.81 www 8454: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8455: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8456: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8457: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8458: ' desiredhome not specified').
1.620 albertel 8459: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8460: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8461: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8462: my $newuser;
8463: if ($uhome eq 'no_host') {
8464: $newuser = 1;
8465: }
1.80 www 8466: # ----------------------------------------------------------------- Create User
1.406 albertel 8467: if (($uhome eq 'no_host') &&
8468: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8469: my $unhome='';
1.844 albertel 8470: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8471: $unhome = $desiredhome;
1.620 albertel 8472: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8473: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8474: } else { # load balancing routine for determining $unhome
1.81 www 8475: my $loadm=10000000;
1.841 albertel 8476: my %servers = &get_servers($udom,'library');
8477: foreach my $tryserver (keys(%servers)) {
8478: my $answer=reply('load',$tryserver);
8479: if (($answer=~/\d+/) && ($answer<$loadm)) {
8480: $loadm=$answer;
8481: $unhome=$tryserver;
8482: }
1.80 www 8483: }
8484: }
8485: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8486: return 'error: unable to find a home server for '.$uname.
8487: ' in domain '.$udom;
1.80 www 8488: }
8489: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8490: &escape($upass),$unhome);
8491: unless ($reply eq 'ok') {
8492: return 'error: '.$reply;
8493: }
1.230 stredwic 8494: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8495: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8496: return 'error: unable verify users home machine.';
1.80 www 8497: }
1.209 matthew 8498: } # End of creation of new user
1.80 www 8499: # ---------------------------------------------------------------------- Add ID
8500: if ($uid) {
8501: $uid=~tr/A-Z/a-z/;
8502: my %uidhash=&idrget($udom,$uname);
1.196 www 8503: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8504: && (!$forceid)) {
1.80 www 8505: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8506: return 'error: user id "'.$uid.'" does not match '.
8507: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8508: }
8509: } else {
8510: &idput($udom,($uname => $uid));
8511: }
8512: }
8513: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8514: my @tmp=&get('environment',
1.899 raeburn 8515: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8516: 'permanentemail','inststatus'],
1.134 albertel 8517: $udom,$uname);
1.1075 raeburn 8518: my (%names,%oldnames);
1.313 matthew 8519: if ($tmp[0] =~ m/^error:.*/) {
8520: %names=();
8521: } else {
8522: %names = @tmp;
1.1075 raeburn 8523: %oldnames = %names;
1.313 matthew 8524: }
1.388 www 8525: #
1.1058 raeburn 8526: # If name, email and/or uid are blank (e.g., because an uploaded file
8527: # of users did not contain them), do not overwrite existing values
8528: # unless field is in $candelete array ref.
8529: #
8530:
8531: my @fields = ('firstname','middlename','lastname','generation',
8532: 'permanentemail','id');
8533: my %newvalues;
8534: if (ref($candelete) eq 'ARRAY') {
8535: foreach my $field (@fields) {
8536: if (grep(/^\Q$field\E$/,@{$candelete})) {
8537: if ($field eq 'firstname') {
8538: $names{$field} = $first;
8539: } elsif ($field eq 'middlename') {
8540: $names{$field} = $middle;
8541: } elsif ($field eq 'lastname') {
8542: $names{$field} = $last;
8543: } elsif ($field eq 'generation') {
8544: $names{$field} = $gene;
8545: } elsif ($field eq 'permanentemail') {
8546: $names{$field} = $email;
8547: } elsif ($field eq 'id') {
8548: $names{$field} = $uid;
8549: }
8550: }
8551: }
8552: }
1.388 www 8553: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8554: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8555: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8556: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8557: if ($email) {
8558: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8559: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8560: }
1.899 raeburn 8561: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8562: if (defined($inststatus)) {
8563: $names{'inststatus'} = '';
8564: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8565: if (ref($usertypes) eq 'HASH') {
8566: my @okstatuses;
8567: foreach my $item (split(/:/,$inststatus)) {
8568: if (defined($usertypes->{$item})) {
8569: push(@okstatuses,$item);
8570: }
8571: }
8572: if (@okstatuses) {
8573: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8574: }
8575: }
8576: }
1.1075 raeburn 8577: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8578: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8579: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8580: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8581: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8582: } else {
8583: $logmsg .= ' during self creation';
8584: }
1.1075 raeburn 8585: my $changed;
8586: if ($newuser) {
8587: $changed = 1;
8588: } else {
8589: foreach my $field (@fields) {
8590: if ($names{$field} ne $oldnames{$field}) {
8591: $changed = 1;
8592: last;
8593: }
8594: }
8595: }
8596: unless ($changed) {
8597: $logmsg = 'No changes in user information needed for: '.$logmsg;
8598: &logthis($logmsg);
8599: return 'ok';
8600: }
8601: my $reply = &put('environment', \%names, $udom,$uname);
8602: if ($reply ne 'ok') {
8603: return 'error: '.$reply;
8604: }
1.1087 raeburn 8605: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8606: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8607: }
1.1075 raeburn 8608: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8609: &devalidate_cache_new('namescache',$uname.':'.$udom);
8610: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8611: &logthis($logmsg);
1.134 albertel 8612: return 'ok';
1.80 www 8613: }
8614:
1.81 www 8615: # -------------------------------------------------------------- Modify student
1.80 www 8616:
1.81 www 8617: sub modifystudent {
8618: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8619: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8620: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8621: if (!$cid) {
1.620 albertel 8622: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8623: return 'not_in_class';
8624: }
1.80 www 8625: }
8626: # --------------------------------------------------------------- Make the user
1.81 www 8627: my $reply=&modifyuser
1.209 matthew 8628: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8629: $desiredhome,$email,$inststatus);
1.80 www 8630: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8631: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8632: # student's environment
1.297 matthew 8633: $uid = undef if (!$forceid);
1.455 albertel 8634: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8635: $gene,$usec,$end,$start,$type,$locktype,
8636: $cid,$selfenroll,$context,$credits);
1.297 matthew 8637: return $reply;
8638: }
8639:
8640: sub modify_student_enrollment {
1.1216 raeburn 8641: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8642: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8643: my ($cdom,$cnum,$chome);
8644: if (!$cid) {
1.620 albertel 8645: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8646: return 'not_in_class';
8647: }
1.620 albertel 8648: $cdom=$env{'course.'.$cid.'.domain'};
8649: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8650: } else {
8651: ($cdom,$cnum)=split(/_/,$cid);
8652: }
1.620 albertel 8653: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8654: if (!$chome) {
1.457 raeburn 8655: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8656: }
1.455 albertel 8657: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8658: # Make sure the user exists
1.81 www 8659: my $uhome=&homeserver($uname,$udom);
8660: if (($uhome eq '') || ($uhome eq 'no_host')) {
8661: return 'error: no such user';
8662: }
1.297 matthew 8663: # Get student data if we were not given enough information
8664: if (!defined($first) || $first eq '' ||
8665: !defined($last) || $last eq '' ||
8666: !defined($uid) || $uid eq '' ||
8667: !defined($middle) || $middle eq '' ||
8668: !defined($gene) || $gene eq '') {
1.294 matthew 8669: # They did not supply us with enough data to enroll the student, so
8670: # we need to pick up more information.
1.297 matthew 8671: my %tmp = &get('environment',
1.294 matthew 8672: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8673: ,$udom,$uname);
8674:
1.800 albertel 8675: #foreach my $key (keys(%tmp)) {
8676: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8677: #}
1.294 matthew 8678: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8679: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8680: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8681: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8682: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8683: }
1.556 albertel 8684: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8685: my $user = "$uname:$udom";
8686: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8687: my $reply=cput('classlist',
1.1148 raeburn 8688: {$user =>
1.1216 raeburn 8689: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8690: $cdom,$cnum);
1.1148 raeburn 8691: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8692: &devalidate_getsection_cache($udom,$uname,$cid);
8693: } else {
1.81 www 8694: return 'error: '.$reply;
8695: }
1.297 matthew 8696: # Add student role to user
1.83 www 8697: my $uurl='/'.$cid;
1.81 www 8698: $uurl=~s/\_/\//g;
8699: if ($usec) {
8700: $uurl.='/'.$usec;
8701: }
1.1148 raeburn 8702: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8703: $selfenroll,$context);
8704: if ($result ne 'ok') {
8705: if ($old_entry{$user} ne '') {
8706: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8707: } else {
8708: $reply = &del('classlist',[$user],$cdom,$cnum);
8709: }
8710: }
8711: return $result;
1.21 www 8712: }
8713:
1.556 albertel 8714: sub format_name {
8715: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8716: my $name;
8717: if ($first ne 'lastname') {
8718: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8719: } else {
8720: if ($lastname=~/\S/) {
8721: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8722: $name=~s/\s+,/,/;
8723: } else {
8724: $name.= $firstname.' '.$middlename.' '.$generation;
8725: }
8726: }
8727: $name=~s/^\s+//;
8728: $name=~s/\s+$//;
8729: $name=~s/\s+/ /g;
8730: return $name;
8731: }
8732:
1.84 www 8733: # ------------------------------------------------- Write to course preferences
8734:
8735: sub writecoursepref {
8736: my ($courseid,%prefs)=@_;
8737: $courseid=~s/^\///;
8738: $courseid=~s/\_/\//g;
8739: my ($cdomain,$cnum)=split(/\//,$courseid);
8740: my $chome=homeserver($cnum,$cdomain);
8741: if (($chome eq '') || ($chome eq 'no_host')) {
8742: return 'error: no such course';
8743: }
8744: my $cstring='';
1.800 albertel 8745: foreach my $pref (keys(%prefs)) {
8746: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8747: }
1.84 www 8748: $cstring=~s/\&$//;
8749: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8750: }
8751:
8752: # ---------------------------------------------------------- Make/modify course
8753:
8754: sub createcourse {
1.741 raeburn 8755: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8756: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8757: $url=&declutter($url);
8758: my $cid='';
1.1028 raeburn 8759: if ($context eq 'requestcourses') {
8760: my $can_create = 0;
8761: my ($ownername,$ownerdom) = split(':',$course_owner);
8762: if ($udom eq $ownerdom) {
8763: if (&usertools_access($ownername,$ownerdom,$category,undef,
8764: $context)) {
8765: $can_create = 1;
8766: }
8767: } else {
8768: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8769: $category);
8770: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8771: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8772: if (@curr > 0) {
8773: my @options = qw(approval validate autolimit);
8774: my $optregex = join('|',@options);
8775: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8776: $can_create = 1;
8777: }
8778: }
8779: }
8780: }
8781: if ($can_create) {
8782: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8783: unless (&allowed('ccc',$udom)) {
8784: return 'refused';
8785: }
1.1017 raeburn 8786: }
8787: } else {
8788: return 'refused';
8789: }
1.1028 raeburn 8790: } elsif (!&allowed('ccc',$udom)) {
8791: return 'refused';
1.84 www 8792: }
1.1011 raeburn 8793: # --------------------------------------------------------------- Get Unique ID
8794: my $uname;
8795: if ($cnum =~ /^$match_courseid$/) {
8796: my $chome=&homeserver($cnum,$udom,'true');
8797: if (($chome eq '') || ($chome eq 'no_host')) {
8798: $uname = $cnum;
8799: } else {
1.1038 raeburn 8800: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8801: }
8802: } else {
1.1038 raeburn 8803: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8804: }
8805: return $uname if ($uname =~ /^error/);
8806: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8807: if (!defined($course_server)) {
8808: if (defined(&domain($udom,'primary'))) {
8809: $course_server = &domain($udom,'primary');
8810: } else {
8811: $course_server = $env{'user.home'};
8812: }
8813: }
8814: my %host_servers =
8815: &Apache::lonnet::get_servers($udom,'library');
8816: unless ($host_servers{$course_server}) {
8817: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8818: }
1.84 www 8819: # ------------------------------------------------------------- Make the course
8820: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8821: $course_server);
1.84 www 8822: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8823: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8824: if (($uhome eq '') || ($uhome eq 'no_host')) {
8825: return 'error: no such course';
8826: }
1.271 www 8827: # ----------------------------------------------------------------- Course made
1.516 raeburn 8828: # log existence
1.1029 raeburn 8829: my $now = time;
1.918 raeburn 8830: my $newcourse = {
8831: $udom.'_'.$uname => {
1.921 raeburn 8832: description => $description,
8833: inst_code => $inst_code,
8834: owner => $course_owner,
8835: type => $crstype,
1.1029 raeburn 8836: creator => $env{'user.name'}.':'.
8837: $env{'user.domain'},
8838: created => $now,
8839: context => $context,
1.918 raeburn 8840: },
8841: };
1.921 raeburn 8842: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8843: # set toplevel url
1.271 www 8844: my $topurl=$url;
8845: unless ($nonstandard) {
8846: # ------------------------------------------ For standard courses, make top url
8847: my $mapurl=&clutter($url);
1.278 www 8848: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8849: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8850: <map>
8851: <resource id="1" type="start"></resource>
8852: <resource id="2" src="$mapurl"></resource>
8853: <resource id="3" type="finish"></resource>
8854: <link index="1" from="1" to="2"></link>
8855: <link index="2" from="2" to="3"></link>
8856: </map>
8857: ENDINITMAP
8858: $topurl=&declutter(
1.638 albertel 8859: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8860: );
8861: }
8862: # ----------------------------------------------------------- Write preferences
1.84 www 8863: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8864: ('description' => $description,
8865: 'url' => $topurl,
8866: 'internal.creator' => $env{'user.name'}.':'.
8867: $env{'user.domain'},
8868: 'internal.created' => $now,
8869: 'internal.creationcontext' => $context)
8870: );
1.84 www 8871: return '/'.$udom.'/'.$uname;
8872: }
8873:
1.1011 raeburn 8874: # ------------------------------------------------------------------- Create ID
8875: sub generate_coursenum {
1.1038 raeburn 8876: my ($udom,$crstype) = @_;
1.1011 raeburn 8877: my $domdesc = &domain($udom);
8878: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8879: my $first;
8880: if ($crstype eq 'Community') {
8881: $first = '0';
8882: } else {
8883: $first = int(1+rand(9));
8884: }
8885: my $uname=$first.
1.1011 raeburn 8886: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8887: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8888: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8889: # ----------------------------------------------- Make sure that does not exist
8890: my $uhome=&homeserver($uname,$udom,'true');
8891: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8892: if ($crstype eq 'Community') {
8893: $first = '0';
8894: } else {
8895: $first = int(1+rand(9));
8896: }
8897: $uname=$first.
1.1011 raeburn 8898: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8899: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8900: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8901: $uhome=&homeserver($uname,$udom,'true');
8902: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8903: return 'error: unable to generate unique course-ID';
8904: }
8905: }
8906: return $uname;
8907: }
8908:
1.813 albertel 8909: sub is_course {
1.1167 droeschl 8910: my ($cdom, $cnum) = scalar(@_) == 1 ?
8911: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8912:
8913: return unless $cdom and $cnum;
8914:
8915: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8916: '.');
8917:
1.1219 raeburn 8918: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8919: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8920: }
8921:
1.1015 raeburn 8922: sub store_userdata {
8923: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8924: my $result;
1.1016 raeburn 8925: if ($datakey ne '') {
1.1013 raeburn 8926: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8927: if ($udom eq '' || $uname eq '') {
8928: $udom = $env{'user.domain'};
8929: $uname = $env{'user.name'};
8930: }
8931: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8932: if (($uhome eq '') || ($uhome eq 'no_host')) {
8933: $result = 'error: no_host';
8934: } else {
8935: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8936: $storehash->{'host'} = $perlvar{'lonHostID'};
8937:
8938: my $namevalue='';
8939: foreach my $key (keys(%{$storehash})) {
8940: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8941: }
8942: $namevalue=~s/\&$//;
1.1224 raeburn 8943: unless ($namespace eq 'courserequests') {
8944: $datakey = &escape($datakey);
8945: }
1.1105 raeburn 8946: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8947: $namevalue,$uhome);
1.1013 raeburn 8948: }
8949: } else {
8950: $result = 'error: data to store was not a hash reference';
8951: }
8952: } else {
8953: $result= 'error: invalid requestkey';
8954: }
8955: return $result;
8956: }
8957:
1.21 www 8958: # ---------------------------------------------------------- Assign Custom Role
8959:
8960: sub assigncustomrole {
1.957 raeburn 8961: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8962: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8963: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8964: }
8965:
8966: # ----------------------------------------------------------------- Revoke Role
8967:
8968: sub revokerole {
1.957 raeburn 8969: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8970: my $now=time;
1.965 raeburn 8971: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8972: }
8973:
8974: # ---------------------------------------------------------- Revoke Custom Role
8975:
8976: sub revokecustomrole {
1.957 raeburn 8977: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8978: my $now=time;
1.357 www 8979: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8980: $deleteflag,$selfenroll,$context);
1.17 www 8981: }
8982:
1.533 banghart 8983: # ------------------------------------------------------------ Disk usage
1.535 albertel 8984: sub diskusage {
1.955 raeburn 8985: my ($udom,$uname,$directorypath,$getpropath)=@_;
8986: $directorypath =~ s/\/$//;
8987: my $listing=&reply('du2:'.&escape($directorypath).':'
8988: .&escape($getpropath).':'.&escape($uname).':'
8989: .&escape($udom),homeserver($uname,$udom));
8990: if ($listing eq 'unknown_cmd') {
8991: if ($getpropath) {
8992: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8993: }
8994: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8995: }
1.514 albertel 8996: return $listing;
1.512 banghart 8997: }
8998:
1.566 banghart 8999: sub is_locked {
1.1096 raeburn 9000: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9001: my @check;
9002: my $is_locked;
1.1093 raeburn 9003: push (@check,$file_name);
1.613 albertel 9004: my %locked = &get('file_permissions',\@check,
1.620 albertel 9005: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9006: my ($tmp)=keys(%locked);
9007: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9008:
1.566 banghart 9009: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9010: $is_locked = 'false';
9011: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9012: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9013: $is_locked = 'true';
1.1096 raeburn 9014: if (ref($which) eq 'ARRAY') {
9015: push(@{$which},$entry);
9016: } else {
9017: last;
9018: }
1.745 raeburn 9019: }
9020: }
1.566 banghart 9021: } else {
9022: $is_locked = 'false';
9023: }
1.1093 raeburn 9024: return $is_locked;
1.566 banghart 9025: }
9026:
1.759 albertel 9027: sub declutter_portfile {
9028: my ($file) = @_;
1.833 albertel 9029: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9030: return $file;
9031: }
9032:
1.559 banghart 9033: # ------------------------------------------------------------- Mark as Read Only
9034:
9035: sub mark_as_readonly {
9036: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9037: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9038: my ($tmp)=keys(%current_permissions);
9039: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9040: foreach my $file (@{$files}) {
1.759 albertel 9041: $file = &declutter_portfile($file);
1.561 banghart 9042: push(@{$current_permissions{$file}},$what);
1.559 banghart 9043: }
1.613 albertel 9044: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9045: return;
9046: }
9047:
1.572 banghart 9048: # ------------------------------------------------------------Save Selected Files
9049:
9050: sub save_selected_files {
9051: my ($user, $path, @files) = @_;
9052: my $filename = $user."savedfiles";
1.573 banghart 9053: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9054: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9055: foreach my $file (@files) {
1.620 albertel 9056: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9057: }
9058: foreach my $file (@other_files) {
1.574 banghart 9059: print (OUT $file."\n");
1.572 banghart 9060: }
1.574 banghart 9061: close (OUT);
1.572 banghart 9062: return 'ok';
9063: }
9064:
1.574 banghart 9065: sub clear_selected_files {
9066: my ($user) = @_;
9067: my $filename = $user."savedfiles";
1.1117 foxr 9068: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9069: print (OUT undef);
9070: close (OUT);
9071: return ("ok");
9072: }
9073:
1.572 banghart 9074: sub files_in_path {
9075: my ($user, $path) = @_;
9076: my $filename = $user."savedfiles";
9077: my %return_files;
1.1117 foxr 9078: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9079: while (my $line_in = <IN>) {
1.574 banghart 9080: chomp ($line_in);
9081: my @paths_and_file = split (m!/!, $line_in);
9082: my $file_part = pop (@paths_and_file);
9083: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9084: $path_part.='/';
9085: my $path_and_file = $path_part.$file_part;
9086: if ($path_part eq $path) {
9087: $return_files{$file_part}= 'selected';
9088: }
9089: }
1.574 banghart 9090: close (IN);
9091: return (\%return_files);
1.572 banghart 9092: }
9093:
9094: # called in portfolio select mode, to show files selected NOT in current directory
9095: sub files_not_in_path {
9096: my ($user, $path) = @_;
9097: my $filename = $user."savedfiles";
9098: my @return_files;
9099: my $path_part;
1.1117 foxr 9100: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9101: while (my $line = <IN>) {
1.572 banghart 9102: #ok, I know it's clunky, but I want it to work
1.800 albertel 9103: my @paths_and_file = split(m|/|, $line);
9104: my $file_part = pop(@paths_and_file);
9105: chomp($file_part);
9106: my $path_part = join('/', @paths_and_file);
1.572 banghart 9107: $path_part .= '/';
9108: my $path_and_file = $path_part.$file_part;
9109: if ($path_part ne $path) {
1.800 albertel 9110: push(@return_files, ($path_and_file));
1.572 banghart 9111: }
9112: }
1.800 albertel 9113: close(OUT);
1.574 banghart 9114: return (@return_files);
1.572 banghart 9115: }
9116:
1.745 raeburn 9117: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9118:
1.745 raeburn 9119: sub get_portfile_permissions {
9120: my ($domain,$user) = @_;
1.613 albertel 9121: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9122: my ($tmp)=keys(%current_permissions);
9123: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9124: return \%current_permissions;
9125: }
9126:
9127: #---------------------------------------------Get portfolio file access controls
9128:
1.749 raeburn 9129: sub get_access_controls {
1.745 raeburn 9130: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9131: my %access;
9132: my $real_file = $file;
9133: $file =~ s/\.meta$//;
1.745 raeburn 9134: if (defined($file)) {
1.749 raeburn 9135: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9136: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9137: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9138: }
9139: }
1.745 raeburn 9140: } else {
1.749 raeburn 9141: foreach my $key (keys(%{$current_permissions})) {
9142: if ($key =~ /\0accesscontrol$/) {
9143: if (defined($group)) {
9144: if ($key !~ m-^\Q$group\E/-) {
9145: next;
9146: }
9147: }
9148: my ($fullpath) = split(/\0/,$key);
9149: if (ref($$current_permissions{$key}) eq 'HASH') {
9150: foreach my $control (keys(%{$$current_permissions{$key}})) {
9151: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9152: }
9153: }
9154: }
9155: }
9156: }
9157: return %access;
9158: }
9159:
9160: sub modify_access_controls {
9161: my ($file_name,$changes,$domain,$user)=@_;
9162: my ($outcome,$deloutcome);
9163: my %store_permissions;
9164: my %new_values;
9165: my %new_control;
9166: my %translation;
9167: my @deletions = ();
9168: my $now = time;
9169: if (exists($$changes{'activate'})) {
9170: if (ref($$changes{'activate'}) eq 'HASH') {
9171: my @newitems = sort(keys(%{$$changes{'activate'}}));
9172: my $numnew = scalar(@newitems);
9173: for (my $i=0; $i<$numnew; $i++) {
9174: my $newkey = $newitems[$i];
9175: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9176: if ($newkey =~ /^\d+:/) {
9177: $newkey =~ s/^(\d+)/$newid/;
9178: $translation{$1} = $newid;
9179: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9180: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9181: $translation{$1} = $newid;
9182: }
1.749 raeburn 9183: $new_values{$file_name."\0".$newkey} =
9184: $$changes{'activate'}{$newitems[$i]};
9185: $new_control{$newkey} = $now;
9186: }
9187: }
9188: }
9189: my %todelete;
9190: my %changed_items;
9191: foreach my $action ('delete','update') {
9192: if (exists($$changes{$action})) {
9193: if (ref($$changes{$action}) eq 'HASH') {
9194: foreach my $key (keys(%{$$changes{$action}})) {
9195: my ($itemnum) = ($key =~ /^([^:]+):/);
9196: if ($action eq 'delete') {
9197: $todelete{$itemnum} = 1;
9198: } else {
9199: $changed_items{$itemnum} = $key;
9200: }
9201: }
1.745 raeburn 9202: }
9203: }
1.749 raeburn 9204: }
9205: # get lock on access controls for file.
9206: my $lockhash = {
9207: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9208: ':'.$env{'user.domain'},
9209: };
9210: my $tries = 0;
9211: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9212:
9213: while (($gotlock ne 'ok') && $tries <3) {
9214: $tries ++;
9215: sleep 1;
9216: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9217: }
9218: if ($gotlock eq 'ok') {
9219: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9220: my ($tmp)=keys(%curr_permissions);
9221: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9222: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9223: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9224: if (ref($curr_controls) eq 'HASH') {
9225: foreach my $control_item (keys(%{$curr_controls})) {
9226: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9227: if (defined($todelete{$itemnum})) {
9228: push(@deletions,$file_name."\0".$control_item);
9229: } else {
9230: if (defined($changed_items{$itemnum})) {
9231: $new_control{$changed_items{$itemnum}} = $now;
9232: push(@deletions,$file_name."\0".$control_item);
9233: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9234: } else {
9235: $new_control{$control_item} = $$curr_controls{$control_item};
9236: }
9237: }
1.745 raeburn 9238: }
9239: }
9240: }
1.970 raeburn 9241: my ($group);
9242: if (&is_course($domain,$user)) {
9243: ($group,my $file) = split(/\//,$file_name,2);
9244: }
1.749 raeburn 9245: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9246: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9247: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9248: # remove lock
9249: my @del_lock = ($file_name."\0".'locked_access_records');
9250: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9251: my $sqlresult =
1.970 raeburn 9252: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9253: $group);
1.749 raeburn 9254: } else {
9255: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9256: }
1.749 raeburn 9257: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9258: }
9259:
1.827 raeburn 9260: sub make_public_indefinitely {
9261: my ($requrl) = @_;
9262: my $now = time;
9263: my $action = 'activate';
9264: my $aclnum = 0;
9265: if (&is_portfolio_url($requrl)) {
9266: my (undef,$udom,$unum,$file_name,$group) =
9267: &parse_portfolio_url($requrl);
9268: my $current_perms = &get_portfile_permissions($udom,$unum);
9269: my %access_controls = &get_access_controls($current_perms,
9270: $group,$file_name);
9271: foreach my $key (keys(%{$access_controls{$file_name}})) {
9272: my ($num,$scope,$end,$start) =
9273: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9274: if ($scope eq 'public') {
9275: if ($start <= $now && $end == 0) {
9276: $action = 'none';
9277: } else {
9278: $action = 'update';
9279: $aclnum = $num;
9280: }
9281: last;
9282: }
9283: }
9284: if ($action eq 'none') {
9285: return 'ok';
9286: } else {
9287: my %changes;
9288: my $newend = 0;
9289: my $newstart = $now;
9290: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9291: $changes{$action}{$newkey} = {
9292: type => 'public',
9293: time => {
9294: start => $newstart,
9295: end => $newend,
9296: },
9297: };
9298: my ($outcome,$deloutcome,$new_values,$translation) =
9299: &modify_access_controls($file_name,\%changes,$udom,$unum);
9300: return $outcome;
9301: }
9302: } else {
9303: return 'invalid';
9304: }
9305: }
9306:
1.745 raeburn 9307: #------------------------------------------------------Get Marked as Read Only
9308:
9309: sub get_marked_as_readonly {
9310: my ($domain,$user,$what,$group) = @_;
9311: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9312: my @readonly_files;
1.629 banghart 9313: my $cmp1=$what;
9314: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9315: while (my ($file_name,$value) = each(%{$current_permissions})) {
9316: if (defined($group)) {
9317: if ($file_name !~ m-^\Q$group\E/-) {
9318: next;
9319: }
9320: }
1.561 banghart 9321: if (ref($value) eq "ARRAY"){
9322: foreach my $stored_what (@{$value}) {
1.629 banghart 9323: my $cmp2=$stored_what;
1.759 albertel 9324: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9325: $cmp2=join('',@{$stored_what});
1.745 raeburn 9326: }
1.629 banghart 9327: if ($cmp1 eq $cmp2) {
1.561 banghart 9328: push(@readonly_files, $file_name);
1.745 raeburn 9329: last;
1.563 banghart 9330: } elsif (!defined($what)) {
9331: push(@readonly_files, $file_name);
1.745 raeburn 9332: last;
1.561 banghart 9333: }
9334: }
1.745 raeburn 9335: }
1.561 banghart 9336: }
9337: return @readonly_files;
9338: }
1.577 banghart 9339: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9340:
1.577 banghart 9341: sub get_marked_as_readonly_hash {
1.745 raeburn 9342: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9343: my %readonly_files;
1.745 raeburn 9344: while (my ($file_name,$value) = each(%{$current_permissions})) {
9345: if (defined($group)) {
9346: if ($file_name !~ m-^\Q$group\E/-) {
9347: next;
9348: }
9349: }
1.577 banghart 9350: if (ref($value) eq "ARRAY"){
9351: foreach my $stored_what (@{$value}) {
1.745 raeburn 9352: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9353: foreach my $lock_descriptor(@{$stored_what}) {
9354: if ($lock_descriptor eq 'graded') {
9355: $readonly_files{$file_name} = 'graded';
9356: } elsif ($lock_descriptor eq 'handback') {
9357: $readonly_files{$file_name} = 'handback';
9358: } else {
9359: if (!exists($readonly_files{$file_name})) {
9360: $readonly_files{$file_name} = 'locked';
9361: }
9362: }
1.745 raeburn 9363: }
1.750 banghart 9364: }
1.577 banghart 9365: }
9366: }
9367: }
9368: return %readonly_files;
9369: }
1.559 banghart 9370: # ------------------------------------------------------------ Unmark as Read Only
9371:
9372: sub unmark_as_readonly {
1.629 banghart 9373: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9374: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9375: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9376: $file_name = &declutter_portfile($file_name);
1.634 albertel 9377: my $symb_crs = $what;
9378: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9379: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9380: my ($tmp)=keys(%current_permissions);
9381: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9382: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9383: foreach my $file (@readonly_files) {
1.759 albertel 9384: my $clean_file = &declutter_portfile($file);
9385: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9386: my $current_locks = $current_permissions{$file};
1.563 banghart 9387: my @new_locks;
9388: my @del_keys;
9389: if (ref($current_locks) eq "ARRAY"){
9390: foreach my $locker (@{$current_locks}) {
1.632 albertel 9391: my $compare=$locker;
1.749 raeburn 9392: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9393: $compare=join('',@{$locker});
1.746 raeburn 9394: if ($compare ne $symb_crs) {
9395: push(@new_locks, $locker);
9396: }
1.563 banghart 9397: }
9398: }
1.650 albertel 9399: if (scalar(@new_locks) > 0) {
1.563 banghart 9400: $current_permissions{$file} = \@new_locks;
9401: } else {
9402: push(@del_keys, $file);
1.613 albertel 9403: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9404: delete($current_permissions{$file});
1.563 banghart 9405: }
9406: }
1.561 banghart 9407: }
1.613 albertel 9408: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9409: return;
9410: }
1.512 banghart 9411:
1.17 www 9412: # ------------------------------------------------------------ Directory lister
9413:
9414: sub dirlist {
1.955 raeburn 9415: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9416: $uri=~s/^\///;
9417: $uri=~s/\/$//;
1.253 stredwic 9418: my ($udom, $uname);
1.955 raeburn 9419: if ($getuserdir) {
1.253 stredwic 9420: $udom = $userdomain;
9421: $uname = $username;
1.955 raeburn 9422: } else {
9423: (undef,$udom,$uname)=split(/\//,$uri);
9424: if(defined($userdomain)) {
9425: $udom = $userdomain;
9426: }
9427: if(defined($username)) {
9428: $uname = $username;
9429: }
1.253 stredwic 9430: }
1.955 raeburn 9431: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9432:
1.955 raeburn 9433: $dirRoot = $perlvar{'lonDocRoot'};
9434: if (defined($getpropath)) {
9435: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9436: $dirRoot =~ s/\/$//;
1.955 raeburn 9437: } elsif (defined($getuserdir)) {
9438: my $subdir=$uname.'__';
9439: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9440: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9441: ."/$udom/$subdir/$uname";
9442: } elsif (defined($alternateRoot)) {
9443: $dirRoot = $alternateRoot;
1.751 banghart 9444: }
1.253 stredwic 9445:
9446: if($udom) {
9447: if($uname) {
1.1135 raeburn 9448: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9449: if ($uhome eq 'no_host') {
9450: return ([],'no_host');
9451: }
1.955 raeburn 9452: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9453: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9454: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9455: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9456: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9457: } else {
9458: @listing_results = map { &unescape($_); } split(/:/,$listing);
9459: }
1.605 matthew 9460: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9461: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9462: @listing_results = split(/:/,$listing);
9463: } else {
9464: @listing_results = map { &unescape($_); } split(/:/,$listing);
9465: }
1.1135 raeburn 9466: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9467: ($listing eq 'rejected') || ($listing eq 'refused') ||
9468: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9469: return ([],$listing);
9470: } else {
9471: return (\@listing_results);
1.1135 raeburn 9472: }
1.955 raeburn 9473: } elsif(!$alternateRoot) {
1.1136 raeburn 9474: my (%allusers,%listerror);
1.841 albertel 9475: my %servers = &get_servers($udom,'library');
1.955 raeburn 9476: foreach my $tryserver (keys(%servers)) {
9477: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9478: &escape($udom),$tryserver);
9479: if ($listing eq 'unknown_cmd') {
9480: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9481: $udom, $tryserver);
9482: } else {
9483: @listing_results = map { &unescape($_); } split(/:/,$listing);
9484: }
1.841 albertel 9485: if ($listing eq 'unknown_cmd') {
9486: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9487: $udom, $tryserver);
9488: @listing_results = split(/:/,$listing);
9489: } else {
9490: @listing_results =
9491: map { &unescape($_); } split(/:/,$listing);
9492: }
1.1136 raeburn 9493: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9494: ($listing eq 'rejected') || ($listing eq 'refused') ||
9495: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9496: $listerror{$tryserver} = $listing;
9497: } else {
1.841 albertel 9498: foreach my $line (@listing_results) {
9499: my ($entry) = split(/&/,$line,2);
9500: $allusers{$entry} = 1;
9501: }
9502: }
1.253 stredwic 9503: }
1.1136 raeburn 9504: my @alluserslist=();
1.800 albertel 9505: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9506: push(@alluserslist,$user.'&user');
1.253 stredwic 9507: }
1.1136 raeburn 9508: return (\@alluserslist);
1.253 stredwic 9509: } else {
1.1136 raeburn 9510: return ([],'missing username');
1.253 stredwic 9511: }
1.955 raeburn 9512: } elsif(!defined($getpropath)) {
1.1136 raeburn 9513: my $path = $perlvar{'lonDocRoot'}.'/res/';
9514: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9515: return (\@all_domains);
1.955 raeburn 9516: } else {
1.1136 raeburn 9517: return ([],'missing domain');
1.275 stredwic 9518: }
9519: }
9520:
9521: # --------------------------------------------- GetFileTimestamp
9522: # This function utilizes dirlist and returns the date stamp for
9523: # when it was last modified. It will also return an error of -1
9524: # if an error occurs
9525:
9526: sub GetFileTimestamp {
1.955 raeburn 9527: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9528: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9529: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9530: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9531: undef,$getuserdir);
9532: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9533: return -1;
9534: }
9535: if (ref($fileref) eq 'ARRAY') {
9536: my @stats = split('&',$fileref->[0]);
1.375 matthew 9537: # @stats contains first the filename, then the stat output
9538: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9539: } else {
9540: return -1;
1.253 stredwic 9541: }
1.26 www 9542: }
9543:
1.712 albertel 9544: sub stat_file {
9545: my ($uri) = @_;
1.787 albertel 9546: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9547:
1.955 raeburn 9548: my ($udom,$uname,$file);
1.712 albertel 9549: if ($uri =~ m-^/(uploaded|editupload)/-) {
9550: ($udom,$uname,$file) =
1.811 albertel 9551: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9552: $file = 'userfiles/'.$file;
9553: }
9554: if ($uri =~ m-^/res/-) {
9555: ($udom,$uname) =
1.807 albertel 9556: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9557: $file = $uri;
9558: }
9559:
9560: if (!$udom || !$uname || !$file) {
9561: # unable to handle the uri
9562: return ();
9563: }
1.956 raeburn 9564: my $getpropath;
9565: if ($file =~ /^userfiles\//) {
9566: $getpropath = 1;
9567: }
1.1136 raeburn 9568: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9569: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9570: return ();
9571: } else {
9572: if (ref($listref) eq 'ARRAY') {
9573: my @stats = split('&',$listref->[0]);
9574: shift(@stats); #filename is first
9575: return @stats;
9576: }
1.712 albertel 9577: }
9578: return ();
9579: }
9580:
1.26 www 9581: # -------------------------------------------------------- Value of a Condition
9582:
1.713 albertel 9583: # gets the value of a specific preevaluated condition
9584: # stored in the string $env{user.state.<cid>}
9585: # or looks up a condition reference in the bighash and if if hasn't
9586: # already been evaluated recurses into docondval to get the value of
9587: # the condition, then memoizing it to
9588: # $env{user.state.<cid>.<condition>}
1.40 www 9589: sub directcondval {
9590: my $number=shift;
1.620 albertel 9591: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9592: &Apache::lonuserstate::evalstate();
9593: }
1.713 albertel 9594: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9595: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9596: } elsif ($number =~ /^_/) {
9597: my $sub_condition;
9598: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9599: &GDBM_READER(),0640)) {
9600: $sub_condition=$bighash{'conditions'.$number};
9601: untie(%bighash);
9602: }
9603: my $value = &docondval($sub_condition);
1.949 raeburn 9604: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9605: return $value;
9606: }
1.620 albertel 9607: if ($env{'user.state.'.$env{'request.course.id'}}) {
9608: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9609: } else {
9610: return 2;
9611: }
9612: }
9613:
1.713 albertel 9614: # get the collection of conditions for this resource
1.26 www 9615: sub condval {
9616: my $condidx=shift;
1.54 www 9617: my $allpathcond='';
1.713 albertel 9618: foreach my $cond (split(/\|/,$condidx)) {
9619: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9620: $allpathcond.=
9621: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9622: }
1.191 harris41 9623: }
1.54 www 9624: $allpathcond=~s/\|$//;
1.713 albertel 9625: return &docondval($allpathcond);
9626: }
9627:
9628: #evaluates an expression of conditions
9629: sub docondval {
9630: my ($allpathcond) = @_;
9631: my $result=0;
9632: if ($env{'request.course.id'}
9633: && defined($allpathcond)) {
9634: my $operand='|';
9635: my @stack;
9636: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9637: if ($chunk eq '(') {
9638: push @stack,($operand,$result);
9639: } elsif ($chunk eq ')') {
9640: my $before=pop @stack;
9641: if (pop @stack eq '&') {
9642: $result=$result>$before?$before:$result;
9643: } else {
9644: $result=$result>$before?$result:$before;
9645: }
9646: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9647: $operand=$chunk;
9648: } else {
9649: my $new=directcondval($chunk);
9650: if ($operand eq '&') {
9651: $result=$result>$new?$new:$result;
9652: } else {
9653: $result=$result>$new?$result:$new;
9654: }
9655: }
9656: }
1.26 www 9657: }
9658: return $result;
1.421 albertel 9659: }
9660:
9661: # ---------------------------------------------------- Devalidate courseresdata
9662:
9663: sub devalidatecourseresdata {
9664: my ($coursenum,$coursedomain)=@_;
9665: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9666: &devalidate_cache_new('courseres',$hashid);
1.28 www 9667: }
9668:
1.763 www 9669:
1.200 www 9670: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9671: #
9672: # Parameters:
9673: # $coursenum - Number of the course.
9674: # $coursedomain - Domain at which the course was created.
9675: # Returns:
9676: # A hash of the course parameters along (I think) with timestamps
9677: # and version info.
1.877 foxr 9678:
1.624 albertel 9679: sub get_courseresdata {
9680: my ($coursenum,$coursedomain)=@_;
1.200 www 9681: my $coursehom=&homeserver($coursenum,$coursedomain);
9682: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9683: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9684: my %dumpreply;
1.417 albertel 9685: unless (defined($cached)) {
1.624 albertel 9686: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9687: $result=\%dumpreply;
1.251 albertel 9688: my ($tmp) = keys(%dumpreply);
9689: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9690: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9691: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9692: return $tmp;
1.416 albertel 9693: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9694: $result=undef;
1.599 albertel 9695: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9696: }
9697: }
1.624 albertel 9698: return $result;
9699: }
9700:
1.633 albertel 9701: sub devalidateuserresdata {
9702: my ($uname,$udom)=@_;
9703: my $hashid="$udom:$uname";
9704: &devalidate_cache_new('userres',$hashid);
9705: }
9706:
1.624 albertel 9707: sub get_userresdata {
9708: my ($uname,$udom)=@_;
9709: #most student don\'t have any data set, check if there is some data
9710: if (&EXT_cache_status($udom,$uname)) { return undef; }
9711:
9712: my $hashid="$udom:$uname";
9713: my ($result,$cached)=&is_cached_new('userres',$hashid);
9714: if (!defined($cached)) {
9715: my %resourcedata=&dump('resourcedata',$udom,$uname);
9716: $result=\%resourcedata;
9717: &do_cache_new('userres',$hashid,$result,600);
9718: }
9719: my ($tmp)=keys(%$result);
9720: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9721: return $result;
9722: }
9723: #error 2 occurs when the .db doesn't exist
9724: if ($tmp!~/error: 2 /) {
1.672 albertel 9725: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9726: " Trying to get resource data for ".
9727: $uname." at ".$udom.": ".
9728: $tmp."</font>");
9729: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9730: #&EXT_cache_set($udom,$uname);
9731: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9732: undef($tmp); # not really an error so don't send it back
1.624 albertel 9733: }
9734: return $tmp;
9735: }
1.879 foxr 9736: #----------------------------------------------- resdata - return resource data
9737: # Purpose:
9738: # Return resource data for either users or for a course.
9739: # Parameters:
9740: # $name - Course/user name.
9741: # $domain - Name of the domain the user/course is registered on.
9742: # $type - Type of thing $name is (must be 'course' or 'user'
9743: # @which - Array of names of resources desired.
9744: # Returns:
9745: # The value of the first reasource in @which that is found in the
9746: # resource hash.
9747: # Exceptional Conditions:
9748: # If the $type passed in is not valid (not the string 'course' or
9749: # 'user', an undefined reference is returned.
9750: # If none of the resources are found, an undef is returned
1.624 albertel 9751: sub resdata {
9752: my ($name,$domain,$type,@which)=@_;
9753: my $result;
9754: if ($type eq 'course') {
9755: $result=&get_courseresdata($name,$domain);
9756: } elsif ($type eq 'user') {
9757: $result=&get_userresdata($name,$domain);
9758: }
9759: if (!ref($result)) { return $result; }
1.251 albertel 9760: foreach my $item (@which) {
1.927 albertel 9761: if (defined($result->{$item->[0]})) {
9762: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9763: }
1.250 albertel 9764: }
1.291 albertel 9765: return undef;
1.200 www 9766: }
9767:
1.1236 raeburn 9768: sub get_numsuppfiles {
9769: my ($cnum,$cdom,$ignorecache)=@_;
9770: my $hashid=$cnum.':'.$cdom;
9771: my ($suppcount,$cached);
9772: unless ($ignorecache) {
9773: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9774: }
9775: unless (defined($cached)) {
9776: my $chome=&homeserver($cnum,$cdom);
9777: unless ($chome eq 'no_host') {
9778: ($suppcount,my $errors) = (0,0);
9779: my $suppmap = 'supplemental.sequence';
9780: ($suppcount,$errors) =
9781: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9782: }
9783: &do_cache_new('suppcount',$hashid,$suppcount,600);
9784: }
9785: return $suppcount;
9786: }
9787:
1.379 matthew 9788: #
9789: # EXT resource caching routines
9790: #
9791:
9792: sub clear_EXT_cache_status {
1.383 albertel 9793: &delenv('cache.EXT.');
1.379 matthew 9794: }
9795:
9796: sub EXT_cache_status {
9797: my ($target_domain,$target_user) = @_;
1.383 albertel 9798: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9799: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9800: # We know already the user has no data
9801: return 1;
9802: } else {
9803: return 0;
9804: }
9805: }
9806:
9807: sub EXT_cache_set {
9808: my ($target_domain,$target_user) = @_;
1.383 albertel 9809: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9810: #&appenv({$cachename => time});
1.379 matthew 9811: }
9812:
1.28 www 9813: # --------------------------------------------------------- Value of a Variable
1.58 www 9814: sub EXT {
1.715 albertel 9815:
1.1228 raeburn 9816: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9817: unless ($varname) { return ''; }
1.218 albertel 9818: #get real user name/domain, courseid and symb
9819: my $courseid;
1.359 albertel 9820: my $publicuser;
1.427 www 9821: if ($symbparm) {
9822: $symbparm=&get_symb_from_alias($symbparm);
9823: }
1.218 albertel 9824: if (!($uname && $udom)) {
1.790 albertel 9825: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9826: if (!$symbparm) { $symbparm=$cursymb; }
9827: } else {
1.620 albertel 9828: $courseid=$env{'request.course.id'};
1.218 albertel 9829: }
1.48 www 9830: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9831: my $rest;
1.320 albertel 9832: if (defined($therest[0])) {
1.48 www 9833: $rest=join('.',@therest);
9834: } else {
9835: $rest='';
9836: }
1.320 albertel 9837:
1.57 www 9838: my $qualifierrest=$qualifier;
9839: if ($rest) { $qualifierrest.='.'.$rest; }
9840: my $spacequalifierrest=$space;
9841: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9842: if ($realm eq 'user') {
1.48 www 9843: # --------------------------------------------------------------- user.resource
9844: if ($space eq 'resource') {
1.651 albertel 9845: if ( (defined($Apache::lonhomework::parsing_a_problem)
9846: || defined($Apache::lonhomework::parsing_a_task))
9847: &&
1.744 albertel 9848: ($symbparm eq &symbread()) ) {
9849: # if we are in the middle of processing the resource the
9850: # get the value we are planning on committing
9851: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9852: return $Apache::lonhomework::results{$qualifierrest};
9853: } else {
9854: return $Apache::lonhomework::history{$qualifierrest};
9855: }
1.335 albertel 9856: } else {
1.359 albertel 9857: my %restored;
1.620 albertel 9858: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9859: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9860: } else {
9861: %restored=&restore($symbparm,$courseid,$udom,$uname);
9862: }
1.335 albertel 9863: return $restored{$qualifierrest};
9864: }
1.48 www 9865: # ----------------------------------------------------------------- user.access
9866: } elsif ($space eq 'access') {
1.218 albertel 9867: # FIXME - not supporting calls for a specific user
1.48 www 9868: return &allowed($qualifier,$rest);
9869: # ------------------------------------------ user.preferences, user.environment
9870: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9871: if (($uname eq $env{'user.name'}) &&
9872: ($udom eq $env{'user.domain'})) {
9873: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9874: } else {
1.359 albertel 9875: my %returnhash;
9876: if (!$publicuser) {
9877: %returnhash=&userenvironment($udom,$uname,
9878: $qualifierrest);
9879: }
1.218 albertel 9880: return $returnhash{$qualifierrest};
9881: }
1.48 www 9882: # ----------------------------------------------------------------- user.course
9883: } elsif ($space eq 'course') {
1.218 albertel 9884: # FIXME - not supporting calls for a specific user
1.620 albertel 9885: return $env{join('.',('request.course',$qualifier))};
1.48 www 9886: # ------------------------------------------------------------------- user.role
9887: } elsif ($space eq 'role') {
1.218 albertel 9888: # FIXME - not supporting calls for a specific user
1.620 albertel 9889: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9890: if ($qualifier eq 'value') {
9891: return $role;
9892: } elsif ($qualifier eq 'extent') {
9893: return $where;
9894: }
9895: # ----------------------------------------------------------------- user.domain
9896: } elsif ($space eq 'domain') {
1.218 albertel 9897: return $udom;
1.48 www 9898: # ------------------------------------------------------------------- user.name
9899: } elsif ($space eq 'name') {
1.218 albertel 9900: return $uname;
1.48 www 9901: # ---------------------------------------------------- Any other user namespace
1.29 www 9902: } else {
1.359 albertel 9903: my %reply;
9904: if (!$publicuser) {
9905: %reply=&get($space,[$qualifierrest],$udom,$uname);
9906: }
9907: return $reply{$qualifierrest};
1.48 www 9908: }
1.236 www 9909: } elsif ($realm eq 'query') {
9910: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9911: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9912: [$spacequalifierrest]);
1.620 albertel 9913: return $env{'form.'.$spacequalifierrest};
1.236 www 9914: } elsif ($realm eq 'request') {
1.48 www 9915: # ------------------------------------------------------------- request.browser
9916: if ($space eq 'browser') {
1.1145 bisitz 9917: return $env{'browser.'.$qualifier};
1.57 www 9918: # ------------------------------------------------------------ request.filename
9919: } else {
1.620 albertel 9920: return $env{'request.'.$spacequalifierrest};
1.29 www 9921: }
1.28 www 9922: } elsif ($realm eq 'course') {
1.48 www 9923: # ---------------------------------------------------------- course.description
1.620 albertel 9924: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9925: } elsif ($realm eq 'resource') {
1.165 www 9926:
1.620 albertel 9927: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9928: if (!$symbparm) { $symbparm=&symbread(); }
9929: }
1.693 albertel 9930:
1.1232 raeburn 9931: if ($qualifier eq '') {
9932: if ($space eq 'title') {
9933: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9934: return &gettitle($symbparm);
9935: }
1.693 albertel 9936:
1.1232 raeburn 9937: if ($space eq 'map') {
9938: my ($map) = &decode_symb($symbparm);
9939: return &symbread($map);
9940: }
9941: if ($space eq 'maptitle') {
9942: my ($map) = &decode_symb($symbparm);
9943: return &gettitle($map);
9944: }
9945: if ($space eq 'filename') {
9946: if ($symbparm) {
9947: return &clutter((&decode_symb($symbparm))[2]);
9948: }
9949: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9950: }
1.1232 raeburn 9951:
1.1233 raeburn 9952: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9953: if ($space eq 'visibleparts') {
9954: my $navmap = Apache::lonnavmaps::navmap->new();
9955: my $item;
9956: if (ref($navmap)) {
9957: my $res = $navmap->getBySymb($symbparm);
9958: my $parts = $res->parts();
9959: if (ref($parts) eq 'ARRAY') {
9960: $item = join(',',@{$parts});
9961: }
9962: undef($navmap);
1.1232 raeburn 9963: }
1.1233 raeburn 9964: return $item;
1.1232 raeburn 9965: }
9966: }
9967: }
1.693 albertel 9968:
9969: my ($section, $group, @groups);
1.593 albertel 9970: my ($courselevelm,$courselevel);
1.1228 raeburn 9971: if (($courseid eq '') && ($cid)) {
9972: $courseid = $cid;
9973: }
9974: if (($symbparm && $courseid) &&
9975: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9976:
1.218 albertel 9977: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9978:
1.60 www 9979: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9980: my $symbp=$symbparm;
1.735 albertel 9981: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9982:
9983: my $symbparm=$symbp.'.'.$spacequalifierrest;
9984: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9985:
1.620 albertel 9986: if (($env{'user.name'} eq $uname) &&
9987: ($env{'user.domain'} eq $udom)) {
9988: $section=$env{'request.course.sec'};
1.733 raeburn 9989: @groups = split(/:/,$env{'request.course.groups'});
9990: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9991: } else {
1.539 albertel 9992: if (! defined($usection)) {
1.551 albertel 9993: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9994: } else {
9995: $section = $usection;
9996: }
1.733 raeburn 9997: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9998: }
9999:
10000: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10001: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10002: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10003:
1.593 albertel 10004: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10005: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10006: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10007:
1.60 www 10008: # ----------------------------------------------------------- first, check user
1.624 albertel 10009:
10010: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10011: ([$courselevelr,'resource'],
10012: [$courselevelm,'map' ],
10013: [$courselevel, 'course' ]));
1.931 albertel 10014: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10015:
1.594 albertel 10016: # ------------------------------------------------ second, check some of course
1.684 raeburn 10017: my $coursereply;
1.691 raeburn 10018: if (@groups > 0) {
10019: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10020: $mapparm,$spacequalifierrest);
1.927 albertel 10021: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10022: }
1.96 www 10023:
1.684 raeburn 10024: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10025: $env{'course.'.$courseid.'.domain'},
10026: 'course',
10027: ([$seclevelr, 'resource'],
10028: [$seclevelm, 'map' ],
10029: [$seclevel, 'course' ],
10030: [$courselevelr,'resource']));
10031: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10032:
1.60 www 10033: # ------------------------------------------------------ third, check map parms
1.218 albertel 10034: my %parmhash=();
10035: my $thisparm='';
10036: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10037: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10038: &GDBM_READER(),0640)) {
1.218 albertel 10039: $thisparm=$parmhash{$symbparm};
10040: untie(%parmhash);
10041: }
1.927 albertel 10042: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10043: }
1.594 albertel 10044: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10045:
1.218 albertel 10046: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10047: my $filename;
10048: if (!$symbparm) { $symbparm=&symbread(); }
10049: if ($symbparm) {
1.409 www 10050: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10051: } else {
1.620 albertel 10052: $filename=$env{'request.filename'};
1.282 albertel 10053: }
10054: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10055: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10056: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10057: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10058:
1.927 albertel 10059: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10060: if ($symbparm && defined($courseid) &&
1.620 albertel 10061: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10062: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10063: $env{'course.'.$courseid.'.domain'},
10064: 'course',
1.927 albertel 10065: ([$courselevelm,'map' ],
10066: [$courselevel, 'course']));
10067: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10068: }
1.145 www 10069: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10070: unless ($space eq '0') {
1.336 albertel 10071: my @parts=split(/_/,$space);
10072: my $id=pop(@parts);
10073: my $part=join('_',@parts);
10074: if ($part eq '') { $part='0'; }
1.927 albertel 10075: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10076: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10077: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10078: }
1.395 albertel 10079: if ($recurse) { return undef; }
10080: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10081: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10082: # ---------------------------------------------------- Any other user namespace
10083: } elsif ($realm eq 'environment') {
10084: # ----------------------------------------------------------------- environment
1.620 albertel 10085: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10086: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10087: } else {
1.770 albertel 10088: if ($uname eq 'anonymous' && $udom eq '') {
10089: return '';
10090: }
1.219 albertel 10091: my %returnhash=&userenvironment($udom,$uname,
10092: $spacequalifierrest);
10093: return $returnhash{$spacequalifierrest};
10094: }
1.28 www 10095: } elsif ($realm eq 'system') {
1.48 www 10096: # ----------------------------------------------------------------- system.time
10097: if ($space eq 'time') {
10098: return time;
10099: }
1.696 albertel 10100: } elsif ($realm eq 'server') {
10101: # ----------------------------------------------------------------- system.time
10102: if ($space eq 'name') {
10103: return $ENV{'SERVER_NAME'};
10104: }
1.28 www 10105: }
1.48 www 10106: return '';
1.61 www 10107: }
10108:
1.927 albertel 10109: sub get_reply {
10110: my ($reply_value) = @_;
1.940 raeburn 10111: if (ref($reply_value) eq 'ARRAY') {
10112: if (wantarray) {
10113: return @$reply_value;
10114: }
10115: return $reply_value->[0];
10116: } else {
10117: return $reply_value;
1.927 albertel 10118: }
10119: }
10120:
1.691 raeburn 10121: sub check_group_parms {
10122: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10123: my @groupitems = ();
10124: my $resultitem;
1.927 albertel 10125: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10126: foreach my $group (@{$groups}) {
10127: foreach my $level (@levels) {
1.927 albertel 10128: my $item = $courseid.'.['.$group.'].'.$level->[0];
10129: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10130: }
10131: }
10132: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10133: $env{'course.'.$courseid.'.domain'},
10134: 'course',@groupitems);
10135: return $coursereply;
10136: }
10137:
10138: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10139: my ($courseid,@groups) = @_;
10140: @groups = sort(@groups);
1.691 raeburn 10141: return @groups;
10142: }
10143:
1.395 albertel 10144: sub packages_tab_default {
10145: my ($uri,$varname)=@_;
10146: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10147:
10148: my (@extension,@specifics,$do_default);
10149: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10150: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10151: if ($pack_type eq 'default') {
10152: $do_default=1;
10153: } elsif ($pack_type eq 'extension') {
10154: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10155: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10156: # only look at packages defaults for packages that this id is
1.738 albertel 10157: push(@specifics,[$package,$pack_type,$pack_part]);
10158: }
10159: }
10160: # first look for a package that matches the requested part id
10161: foreach my $package (@specifics) {
10162: my (undef,$pack_type,$pack_part)=@{$package};
10163: next if ($pack_part ne $part);
10164: if (defined($packagetab{"$pack_type&$name&default"})) {
10165: return $packagetab{"$pack_type&$name&default"};
10166: }
10167: }
10168: # look for any possible matching non extension_ package
10169: foreach my $package (@specifics) {
10170: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10171: if (defined($packagetab{"$pack_type&$name&default"})) {
10172: return $packagetab{"$pack_type&$name&default"};
10173: }
1.585 albertel 10174: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10175: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10176: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10177: }
10178: }
1.738 albertel 10179: # look for any posible extension_ match
10180: foreach my $package (@extension) {
10181: my ($package,$pack_type)=@{$package};
10182: if (defined($packagetab{"$pack_type&$name&default"})) {
10183: return $packagetab{"$pack_type&$name&default"};
10184: }
10185: if (defined($packagetab{$package."&$name&default"})) {
10186: return $packagetab{$package."&$name&default"};
10187: }
10188: }
10189: # look for a global default setting
10190: if ($do_default && defined($packagetab{"default&$name&default"})) {
10191: return $packagetab{"default&$name&default"};
10192: }
1.395 albertel 10193: return undef;
10194: }
10195:
1.334 albertel 10196: sub add_prefix_and_part {
10197: my ($prefix,$part)=@_;
10198: my $keyroot;
10199: if (defined($prefix) && $prefix !~ /^__/) {
10200: # prefix that has a part already
10201: $keyroot=$prefix;
10202: } elsif (defined($prefix)) {
10203: # prefix that is missing a part
10204: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10205: } else {
10206: # no prefix at all
10207: if (defined($part)) { $keyroot='_'.$part; }
10208: }
10209: return $keyroot;
10210: }
10211:
1.71 www 10212: # ---------------------------------------------------------------- Get metadata
10213:
1.599 albertel 10214: my %metaentry;
1.1070 www 10215: my %importedpartids;
1.71 www 10216: sub metadata {
1.176 www 10217: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10218: $uri=&declutter($uri);
1.288 albertel 10219: # if it is a non metadata possible uri return quickly
1.529 albertel 10220: if (($uri eq '') ||
10221: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10222: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10223: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10224: return undef;
10225: }
1.1140 www 10226: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10227: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10228: return undef;
1.288 albertel 10229: }
1.73 www 10230: my $filename=$uri;
10231: $uri=~s/\.meta$//;
1.172 www 10232: #
10233: # Is the metadata already cached?
1.177 www 10234: # Look at timestamp of caching
1.172 www 10235: # Everything is cached by the main uri, libraries are never directly cached
10236: #
1.428 albertel 10237: if (!defined($liburi)) {
1.599 albertel 10238: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10239: if (defined($cached)) { return $result->{':'.$what}; }
10240: }
10241: {
1.1069 www 10242: # Imported parts would go here
1.1070 www 10243: my %importedids=();
10244: my @origfileimportpartids=();
1.1069 www 10245: my $importedparts=0;
1.172 www 10246: #
10247: # Is this a recursive call for a library?
10248: #
1.599 albertel 10249: # if (! exists($metacache{$uri})) {
10250: # $metacache{$uri}={};
10251: # }
1.924 albertel 10252: my $cachetime = 60*60;
1.171 www 10253: if ($liburi) {
10254: $liburi=&declutter($liburi);
10255: $filename=$liburi;
1.401 bowersj2 10256: } else {
1.599 albertel 10257: &devalidate_cache_new('meta',$uri);
10258: undef(%metaentry);
1.401 bowersj2 10259: }
1.140 www 10260: my %metathesekeys=();
1.73 www 10261: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10262: my $metastring;
1.1140 www 10263: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10264: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10265: $metastring =
1.929 albertel 10266: &Apache::lonnet::ssi_body($which,
1.924 albertel 10267: ('grade_target' => 'meta'));
10268: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10269: } elsif (($uri !~ m -^(editupload)/-) &&
10270: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10271: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10272: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10273: $metastring=&getfile($file);
1.489 albertel 10274: }
1.208 albertel 10275: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10276: my $token;
1.140 www 10277: undef %metathesekeys;
1.71 www 10278: while ($token=$parser->get_token) {
1.339 albertel 10279: if ($token->[0] eq 'S') {
10280: if (defined($token->[2]->{'package'})) {
1.172 www 10281: #
10282: # This is a package - get package info
10283: #
1.339 albertel 10284: my $package=$token->[2]->{'package'};
10285: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10286: if (defined($token->[2]->{'id'})) {
10287: $keyroot.='_'.$token->[2]->{'id'};
10288: }
1.599 albertel 10289: if ($metaentry{':packages'}) {
10290: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10291: } else {
1.599 albertel 10292: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10293: }
1.736 albertel 10294: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10295: my $part=$keyroot;
10296: $part=~s/^\_//;
1.736 albertel 10297: if ($pack_entry=~/^\Q$package\E\&/ ||
10298: $pack_entry=~/^\Q$package\E_0\&/) {
10299: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10300: # ignore package.tab specified default values
10301: # here &package_tab_default() will fetch those
10302: if ($subp eq 'default') { next; }
1.736 albertel 10303: my $value=$packagetab{$pack_entry};
1.432 albertel 10304: my $unikey;
10305: if ($pack =~ /_0$/) {
10306: $unikey='parameter_0_'.$name;
10307: $part=0;
10308: } else {
10309: $unikey='parameter'.$keyroot.'_'.$name;
10310: }
1.339 albertel 10311: if ($subp eq 'display') {
10312: $value.=' [Part: '.$part.']';
10313: }
1.599 albertel 10314: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10315: $metathesekeys{$unikey}=1;
1.599 albertel 10316: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10317: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10318: }
1.599 albertel 10319: if (defined($metaentry{':'.$unikey.'.default'})) {
10320: $metaentry{':'.$unikey}=
10321: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10322: }
1.339 albertel 10323: }
10324: }
10325: } else {
1.172 www 10326: #
10327: # This is not a package - some other kind of start tag
1.339 albertel 10328: #
10329: my $entry=$token->[1];
1.1068 www 10330: my $unikey='';
1.175 www 10331:
1.339 albertel 10332: if ($entry eq 'import') {
1.175 www 10333: #
10334: # Importing a library here
1.339 albertel 10335: #
1.1067 www 10336: my $location=$parser->get_text('/import');
10337: my $dir=$filename;
10338: $dir=~s|[^/]*$||;
10339: $location=&filelocation($dir,$location);
1.1069 www 10340:
1.1068 www 10341: my $importmode=$token->[2]->{'importmode'};
10342: if ($importmode eq 'problem') {
1.1069 www 10343: # Import as problem/response
1.1068 www 10344: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10345: } elsif ($importmode eq 'part') {
10346: # Import as part(s)
1.1069 www 10347: $importedparts=1;
10348: # We need to get the original file and the imported file to get the part order correct
10349: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10350: # Load and inspect original file
1.1070 www 10351: if ($#origfileimportpartids<0) {
10352: undef(%importedpartids);
10353: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10354: my $origfile=&getfile($origfilelocation);
10355: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10356: }
10357:
1.1069 www 10358: # Load and inspect imported file
10359: my $impfile=&getfile($location);
10360: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10361: if ($#impfilepartids>=0) {
10362: # This problem had parts
1.1070 www 10363: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10364: } else {
10365: # Importing by turning a single problem into a problem part
10366: # It gets the import-tags ID as part-ID
10367: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10368: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10369: }
1.1068 www 10370: } else {
10371: # Normal import
10372: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10373: if (defined($token->[2]->{'id'})) {
10374: $unikey.='_'.$token->[2]->{'id'};
10375: }
1.1067 www 10376: }
10377:
1.339 albertel 10378: if ($depthcount<20) {
1.736 albertel 10379: my $metadata =
10380: &metadata($uri,'keys', $location,$unikey,
10381: $depthcount+1);
10382: foreach my $meta (split(',',$metadata)) {
10383: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10384: $metathesekeys{$meta}=1;
1.339 albertel 10385: }
1.1068 www 10386:
10387: }
1.1067 www 10388: } else {
10389: #
10390: # Not importing, some other kind of non-package, non-library start tag
10391: #
10392: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10393: if (defined($token->[2]->{'id'})) {
10394: $unikey.='_'.$token->[2]->{'id'};
10395: }
1.339 albertel 10396: if (defined($token->[2]->{'name'})) {
10397: $unikey.='_'.$token->[2]->{'name'};
10398: }
10399: $metathesekeys{$unikey}=1;
1.736 albertel 10400: foreach my $param (@{$token->[3]}) {
10401: $metaentry{':'.$unikey.'.'.$param} =
10402: $token->[2]->{$param};
1.339 albertel 10403: }
10404: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10405: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10406: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10407: # only ws inside the tag, and not in default, so use default
10408: # as value
1.599 albertel 10409: $metaentry{':'.$unikey}=$default;
1.908 albertel 10410: } elsif ( $internaltext =~ /\S/ ) {
10411: # something interesting inside the tag
10412: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10413: } else {
1.908 albertel 10414: # no interesting values, don't set a default
1.339 albertel 10415: }
1.172 www 10416: # end of not-a-package not-a-library import
1.339 albertel 10417: }
1.172 www 10418: # end of not-a-package start tag
1.339 albertel 10419: }
1.172 www 10420: # the next is the end of "start tag"
1.339 albertel 10421: }
10422: }
1.483 albertel 10423: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10424: $extension = lc($extension);
10425: if ($extension eq 'htm') { $extension='html'; }
10426:
1.737 albertel 10427: foreach my $key (keys(%packagetab)) {
1.483 albertel 10428: #no specific packages #how's our extension
10429: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10430: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10431: \%metathesekeys);
10432: }
1.883 albertel 10433:
10434: if (!exists($metaentry{':packages'})
10435: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10436: foreach my $key (keys(%packagetab)) {
1.483 albertel 10437: #no specific packages well let's get default then
10438: if ($key!~/^default&/) { next; }
1.488 albertel 10439: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10440: \%metathesekeys);
10441: }
10442: }
1.338 www 10443: # are there custom rights to evaluate
1.599 albertel 10444: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10445:
1.338 www 10446: #
10447: # Importing a rights file here
1.339 albertel 10448: #
10449: unless ($depthcount) {
1.599 albertel 10450: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10451: my $dir=$filename;
10452: $dir=~s|[^/]*$||;
10453: $location=&filelocation($dir,$location);
1.736 albertel 10454: my $rights_metadata =
10455: &metadata($uri,'keys',$location,'_rights',
10456: $depthcount+1);
10457: foreach my $rights (split(',',$rights_metadata)) {
10458: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10459: $metathesekeys{$rights}=1;
1.339 albertel 10460: }
10461: }
10462: }
1.737 albertel 10463: # uniqifiy package listing
10464: my %seen;
10465: my @uniq_packages =
10466: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10467: $metaentry{':packages'} = join(',',@uniq_packages);
10468:
1.1070 www 10469: if ($importedparts) {
10470: # We had imported parts and need to rebuild partorder
10471: $metaentry{':partorder'}='';
10472: $metathesekeys{'partorder'}=1;
10473: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10474: if ($origfileimportpartids[$index] eq 'part') {
10475: # original part, part of the problem
10476: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10477: } else {
10478: # we have imported parts at this position
10479: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10480: }
10481: }
10482: $metaentry{':partorder'}=~s/^\,//;
10483: }
10484:
1.737 albertel 10485: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10486: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10487: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10488: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10489: # this is the end of "was not already recently cached
1.71 www 10490: }
1.599 albertel 10491: return $metaentry{':'.$what};
1.261 albertel 10492: }
10493:
1.488 albertel 10494: sub metadata_create_package_def {
1.483 albertel 10495: my ($uri,$key,$package,$metathesekeys)=@_;
10496: my ($pack,$name,$subp)=split(/\&/,$key);
10497: if ($subp eq 'default') { next; }
10498:
1.599 albertel 10499: if (defined($metaentry{':packages'})) {
10500: $metaentry{':packages'}.=','.$package;
1.483 albertel 10501: } else {
1.599 albertel 10502: $metaentry{':packages'}=$package;
1.483 albertel 10503: }
10504: my $value=$packagetab{$key};
10505: my $unikey;
10506: $unikey='parameter_0_'.$name;
1.599 albertel 10507: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10508: $$metathesekeys{$unikey}=1;
1.599 albertel 10509: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10510: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10511: }
1.599 albertel 10512: if (defined($metaentry{':'.$unikey.'.default'})) {
10513: $metaentry{':'.$unikey}=
10514: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10515: }
10516: }
10517:
1.261 albertel 10518: sub metadata_generate_part0 {
10519: my ($metadata,$metacache,$uri) = @_;
10520: my %allnames;
1.737 albertel 10521: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10522: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10523: my $part=$$metacache{':'.$metakey.'.part'};
10524: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10525: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10526: $allnames{$name}=$part;
10527: }
10528: }
10529: }
10530: foreach my $name (keys(%allnames)) {
10531: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10532: my $key=":parameter_0_$name";
1.261 albertel 10533: $$metacache{"$key.part"}='0';
10534: $$metacache{"$key.name"}=$name;
1.428 albertel 10535: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10536: $allnames{$name}.'_'.$name.
10537: '.type'};
1.428 albertel 10538: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10539: '.display'};
1.644 www 10540: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10541: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10542: $$metacache{"$key.display"}=$olddis;
10543: }
1.71 www 10544: }
10545:
1.764 albertel 10546: # ------------------------------------------------------ Devalidate title cache
10547:
10548: sub devalidate_title_cache {
10549: my ($url)=@_;
10550: if (!$env{'request.course.id'}) { return; }
10551: my $symb=&symbread($url);
10552: if (!$symb) { return; }
10553: my $key=$env{'request.course.id'}."\0".$symb;
10554: &devalidate_cache_new('title',$key);
10555: }
10556:
1.1014 droeschl 10557: # ------------------------------------------------- Get the title of a course
10558:
10559: sub current_course_title {
10560: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10561: }
1.301 www 10562: # ------------------------------------------------- Get the title of a resource
10563:
10564: sub gettitle {
10565: my $urlsymb=shift;
10566: my $symb=&symbread($urlsymb);
1.534 albertel 10567: if ($symb) {
1.620 albertel 10568: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10569: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10570: if (defined($cached)) {
10571: return $result;
10572: }
1.534 albertel 10573: my ($map,$resid,$url)=&decode_symb($symb);
10574: my $title='';
1.907 albertel 10575: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10576: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10577: } else {
10578: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10579: &GDBM_READER(),0640)) {
10580: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10581: $title=$bighash{'title_'.$mapid.'.'.$resid};
10582: untie(%bighash);
10583: }
1.534 albertel 10584: }
10585: $title=~s/\&colon\;/\:/gs;
10586: if ($title) {
1.1159 www 10587: # Remember both $symb and $title for dynamic metadata
10588: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10589: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10590: # Cache this title and then return it
1.599 albertel 10591: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10592: }
10593: $urlsymb=$url;
10594: }
10595: my $title=&metadata($urlsymb,'title');
10596: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10597: return $title;
1.301 www 10598: }
1.613 albertel 10599:
1.614 albertel 10600: sub get_slot {
10601: my ($which,$cnum,$cdom)=@_;
10602: if (!$cnum || !$cdom) {
1.790 albertel 10603: (undef,my $courseid)=&whichuser();
1.620 albertel 10604: $cdom=$env{'course.'.$courseid.'.domain'};
10605: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10606: }
1.703 albertel 10607: my $key=join("\0",'slots',$cdom,$cnum,$which);
10608: my %slotinfo;
10609: if (exists($remembered{$key})) {
10610: $slotinfo{$which} = $remembered{$key};
10611: } else {
10612: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10613: &Apache::lonhomework::showhash(%slotinfo);
10614: my ($tmp)=keys(%slotinfo);
10615: if ($tmp=~/^error:/) { return (); }
10616: $remembered{$key} = $slotinfo{$which};
10617: }
1.616 albertel 10618: if (ref($slotinfo{$which}) eq 'HASH') {
10619: return %{$slotinfo{$which}};
10620: }
10621: return $slotinfo{$which};
1.614 albertel 10622: }
1.1150 raeburn 10623:
10624: sub get_reservable_slots {
10625: my ($cnum,$cdom,$uname,$udom) = @_;
10626: my $now = time;
10627: my $reservable_info;
10628: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10629: if (exists($remembered{$key})) {
10630: $reservable_info = $remembered{$key};
10631: } else {
10632: my %resv;
10633: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10634: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10635: $reservable_info = \%resv;
10636: $remembered{$key} = $reservable_info;
10637: }
10638: return $reservable_info;
10639: }
10640:
10641: sub get_course_slots {
10642: my ($cnum,$cdom) = @_;
10643: my $hashid=$cnum.':'.$cdom;
10644: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10645: if (defined($cached)) {
10646: if (ref($result) eq 'HASH') {
10647: return %{$result};
10648: }
10649: } else {
10650: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10651: my ($tmp) = keys(%slots);
10652: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10653: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10654: return %slots;
10655: }
10656: }
10657: return;
10658: }
10659:
10660: sub devalidate_slots_cache {
10661: my ($cnum,$cdom)=@_;
10662: my $hashid=$cnum.':'.$cdom;
10663: &devalidate_cache_new('allslots',$hashid);
10664: }
10665:
1.1181 raeburn 10666: sub get_coursechange {
10667: my ($cdom,$cnum) = @_;
10668: if ($cdom eq '' || $cnum eq '') {
10669: return unless ($env{'request.course.id'});
10670: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10671: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10672: }
10673: my $hashid=$cdom.'_'.$cnum;
10674: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10675: if ((defined($cached)) && ($change ne '')) {
10676: return $change;
10677: } else {
10678: my %crshash;
10679: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10680: if ($crshash{'internal.contentchange'} eq '') {
10681: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10682: if ($change eq '') {
10683: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10684: $change = $crshash{'internal.created'};
10685: }
10686: } else {
10687: $change = $crshash{'internal.contentchange'};
10688: }
10689: my $cachetime = 600;
10690: &do_cache_new('crschange',$hashid,$change,$cachetime);
10691: }
10692: return $change;
10693: }
10694:
10695: sub devalidate_coursechange_cache {
10696: my ($cnum,$cdom)=@_;
10697: my $hashid=$cnum.':'.$cdom;
10698: &devalidate_cache_new('crschange',$hashid);
10699: }
10700:
1.31 www 10701: # ------------------------------------------------- Update symbolic store links
10702:
10703: sub symblist {
10704: my ($mapname,%newhash)=@_;
1.438 www 10705: $mapname=&deversion(&declutter($mapname));
1.31 www 10706: my %hash;
1.620 albertel 10707: if (($env{'request.course.fn'}) && (%newhash)) {
10708: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10709: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10710: foreach my $url (keys(%newhash)) {
1.711 albertel 10711: next if ($url eq 'last_known'
10712: && $env{'form.no_update_last_known'});
10713: $hash{declutter($url)}=&encode_symb($mapname,
10714: $newhash{$url}->[1],
10715: $newhash{$url}->[0]);
1.191 harris41 10716: }
1.31 www 10717: if (untie(%hash)) {
10718: return 'ok';
10719: }
10720: }
10721: }
10722: return 'error';
1.212 www 10723: }
10724:
10725: # --------------------------------------------------------------- Verify a symb
10726:
10727: sub symbverify {
1.1190 raeburn 10728: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10729: my $thisfn=$thisurl;
1.439 www 10730: $thisfn=&declutter($thisfn);
1.215 www 10731: # direct jump to resource in page or to a sequence - will construct own symbs
10732: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10733: # check URL part
1.409 www 10734: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10735:
1.431 www 10736: unless ($url eq $thisfn) { return 0; }
1.213 www 10737:
1.216 www 10738: $symb=&symbclean($symb);
1.510 www 10739: $thisurl=&deversion($thisurl);
1.439 www 10740: $thisfn=&deversion($thisfn);
1.213 www 10741:
10742: my %bighash;
10743: my $okay=0;
1.431 www 10744:
1.620 albertel 10745: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10746: &GDBM_READER(),0640)) {
1.1204 raeburn 10747: my $noclutter;
1.1032 raeburn 10748: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10749: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10750: if ($map =~ m{^uploaded/.+\.page$}) {
10751: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10752: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10753: $noclutter = 1;
10754: }
10755: }
10756: my $ids;
10757: if ($noclutter) {
10758: $ids=$bighash{'ids_'.$thisurl};
10759: } else {
10760: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10761: }
1.1102 raeburn 10762: unless ($ids) {
10763: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10764: $ids=$bighash{$idkey};
1.216 www 10765: }
10766: if ($ids) {
10767: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10768: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10769: $symb =~ s/\?.+$//;
1.1202 raeburn 10770: }
1.800 albertel 10771: foreach my $id (split(/\,/,$ids)) {
10772: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10773: if (
10774: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10775: eq $symb) {
10776: if (ref($encstate)) {
10777: $$encstate = $bighash{'encrypted_'.$id};
10778: }
1.620 albertel 10779: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10780: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10781: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10782: $okay=1;
1.1202 raeburn 10783: last;
1.582 albertel 10784: }
10785: }
1.216 www 10786: }
10787: }
1.213 www 10788: untie(%bighash);
10789: }
10790: return $okay;
1.31 www 10791: }
10792:
1.210 www 10793: # --------------------------------------------------------------- Clean-up symb
10794:
10795: sub symbclean {
10796: my $symb=shift;
1.568 albertel 10797: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10798: # remove version from map
10799: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10800:
1.210 www 10801: # remove version from URL
10802: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10803:
1.507 www 10804: # remove wrapper
10805:
1.510 www 10806: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10807: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10808: return $symb;
1.409 www 10809: }
10810:
10811: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10812:
10813: sub encode_symb {
10814: my ($map,$resid,$url)=@_;
10815: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10816: }
1.409 www 10817:
10818: sub decode_symb {
1.568 albertel 10819: my $symb=shift;
10820: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10821: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10822: return (&fixversion($map),$resid,&fixversion($url));
10823: }
10824:
10825: sub fixversion {
10826: my $fn=shift;
1.609 banghart 10827: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10828: my %bighash;
10829: my $uri=&clutter($fn);
1.620 albertel 10830: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10831: # is this cached?
1.599 albertel 10832: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10833: if (defined($cached)) { return $result; }
10834: # unfortunately not cached, or expired
1.620 albertel 10835: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10836: &GDBM_READER(),0640)) {
10837: if ($bighash{'version_'.$uri}) {
10838: my $version=$bighash{'version_'.$uri};
1.444 www 10839: unless (($version eq 'mostrecent') ||
10840: ($version==&getversion($uri))) {
1.440 www 10841: $uri=~s/\.(\w+)$/\.$version\.$1/;
10842: }
10843: }
10844: untie %bighash;
1.413 www 10845: }
1.599 albertel 10846: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10847: }
10848:
10849: sub deversion {
10850: my $url=shift;
10851: $url=~s/\.\d+\.(\w+)$/\.$1/;
10852: return $url;
1.210 www 10853: }
10854:
1.31 www 10855: # ------------------------------------------------------ Return symb list entry
10856:
10857: sub symbread {
1.249 www 10858: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10859: my $cache_str;
10860: if ($thisfn ne '') {
10861: $cache_str='request.symbread.cached.'.$thisfn;
10862: if ($env{$cache_str} ne '') {
1.1179 raeburn 10863: return $env{$cache_str};
10864: }
1.1206 raeburn 10865: } else {
1.242 www 10866: # no filename provided? try from environment
1.620 albertel 10867: if ($env{'request.symb'}) {
10868: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10869: }
1.620 albertel 10870: $thisfn=$env{'request.filename'};
1.44 www 10871: }
1.569 albertel 10872: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10873: # is that filename actually a symb? Verify, clean, and return
10874: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10875: if (&symbverify($thisfn,$1)) {
1.620 albertel 10876: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10877: }
1.242 www 10878: }
1.44 www 10879: $thisfn=declutter($thisfn);
1.31 www 10880: my %hash;
1.37 www 10881: my %bighash;
10882: my $syval='';
1.620 albertel 10883: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10884: my $targetfn = $thisfn;
1.609 banghart 10885: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10886: $targetfn = 'adm/wrapper/'.$thisfn;
10887: }
1.687 albertel 10888: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10889: $targetfn=$1;
10890: }
1.620 albertel 10891: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10892: &GDBM_READER(),0640)) {
1.481 raeburn 10893: $syval=$hash{$targetfn};
1.37 www 10894: untie(%hash);
10895: }
10896: # ---------------------------------------------------------- There was an entry
10897: if ($syval) {
1.601 albertel 10898: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10899: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10900: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10901: #return $env{$cache_str}='';
1.601 albertel 10902: #}
10903: #$syval.=$1;
10904: #}
1.37 www 10905: } else {
10906: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10907: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10908: &GDBM_READER(),0640)) {
1.37 www 10909: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10910: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10911: unless ($ids) {
10912: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10913: }
10914: unless ($ids) {
10915: # alias?
10916: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10917: }
1.37 www 10918: if ($ids) {
10919: # ------------------------------------------------------------------- Has ID(s)
10920: my @possibilities=split(/\,/,$ids);
1.39 www 10921: if ($#possibilities==0) {
10922: # ----------------------------------------------- There is only one possibility
1.37 www 10923: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10924: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10925: $resid,$thisfn);
1.249 www 10926: } elsif (!$donotrecurse) {
1.39 www 10927: # ------------------------------------------ There is more than one possibility
10928: my $realpossible=0;
1.800 albertel 10929: foreach my $id (@possibilities) {
10930: my $file=$bighash{'src_'.$id};
1.39 www 10931: if (&allowed('bre',$file)) {
1.800 albertel 10932: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10933: if ($bighash{'map_type_'.$mapid} ne 'page') {
10934: $realpossible++;
1.626 albertel 10935: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10936: $resid,$thisfn);
1.39 www 10937: }
10938: }
1.191 harris41 10939: }
1.39 www 10940: if ($realpossible!=1) { $syval=''; }
1.249 www 10941: } else {
10942: $syval='';
1.37 www 10943: }
10944: }
10945: untie(%bighash)
1.481 raeburn 10946: }
1.31 www 10947: }
1.62 www 10948: if ($syval) {
1.620 albertel 10949: return $env{$cache_str}=$syval;
1.62 www 10950: }
1.31 www 10951: }
1.949 raeburn 10952: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10953: return $env{$cache_str}='';
1.31 www 10954: }
10955:
10956: # ---------------------------------------------------------- Return random seed
10957:
1.32 www 10958: sub numval {
10959: my $txt=shift;
10960: $txt=~tr/A-J/0-9/;
10961: $txt=~tr/a-j/0-9/;
10962: $txt=~tr/K-T/0-9/;
10963: $txt=~tr/k-t/0-9/;
10964: $txt=~tr/U-Z/0-5/;
10965: $txt=~tr/u-z/0-5/;
10966: $txt=~s/\D//g;
1.564 albertel 10967: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10968: return int($txt);
1.368 albertel 10969: }
10970:
1.484 albertel 10971: sub numval2 {
10972: my $txt=shift;
10973: $txt=~tr/A-J/0-9/;
10974: $txt=~tr/a-j/0-9/;
10975: $txt=~tr/K-T/0-9/;
10976: $txt=~tr/k-t/0-9/;
10977: $txt=~tr/U-Z/0-5/;
10978: $txt=~tr/u-z/0-5/;
10979: $txt=~s/\D//g;
10980: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10981: my $total;
10982: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10983: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10984: return int($total);
10985: }
10986:
1.575 albertel 10987: sub numval3 {
10988: use integer;
10989: my $txt=shift;
10990: $txt=~tr/A-J/0-9/;
10991: $txt=~tr/a-j/0-9/;
10992: $txt=~tr/K-T/0-9/;
10993: $txt=~tr/k-t/0-9/;
10994: $txt=~tr/U-Z/0-5/;
10995: $txt=~tr/u-z/0-5/;
10996: $txt=~s/\D//g;
10997: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10998: my $total;
10999: foreach my $val (@txts) { $total+=$val; }
11000: if ($_64bit) { $total=(($total<<32)>>32); }
11001: return $total;
11002: }
11003:
1.675 albertel 11004: sub digest {
11005: my ($data)=@_;
11006: my $digest=&Digest::MD5::md5($data);
11007: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11008: my ($e,$f);
11009: {
11010: use integer;
11011: $e=($a+$b);
11012: $f=($c+$d);
11013: if ($_64bit) {
11014: $e=(($e<<32)>>32);
11015: $f=(($f<<32)>>32);
11016: }
11017: }
11018: if (wantarray) {
11019: return ($e,$f);
11020: } else {
11021: my $g;
11022: {
11023: use integer;
11024: $g=($e+$f);
11025: if ($_64bit) {
11026: $g=(($g<<32)>>32);
11027: }
11028: }
11029: return $g;
11030: }
11031: }
11032:
1.368 albertel 11033: sub latest_rnd_algorithm_id {
1.675 albertel 11034: return '64bit5';
1.366 albertel 11035: }
1.32 www 11036:
1.503 albertel 11037: sub get_rand_alg {
11038: my ($courseid)=@_;
1.790 albertel 11039: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11040: if ($courseid) {
1.620 albertel 11041: return $env{"course.$courseid.rndseed"};
1.503 albertel 11042: }
11043: return &latest_rnd_algorithm_id();
11044: }
11045:
1.562 albertel 11046: sub validCODE {
11047: my ($CODE)=@_;
11048: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11049: return 0;
11050: }
11051:
1.491 albertel 11052: sub getCODE {
1.620 albertel 11053: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11054: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11055: defined($Apache::lonhomework::parsing_a_task) ) &&
11056: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11057: return $Apache::lonhomework::history{'resource.CODE'};
11058: }
11059: return undef;
11060: }
1.1133 foxr 11061: #
11062: # Determines the random seed for a specific context:
11063: #
11064: # parameters:
11065: # symb - in course context the symb for the seed.
11066: # course_id - The course id of the form domain_coursenum.
11067: # domain - Domain for the user.
11068: # course - Course for the user.
11069: # cenv - environment of the course.
11070: #
11071: # NOTE:
11072: # All parameters are picked out of the environment if missing
11073: # or not defined.
11074: # If a symb cannot be determined the current time is used instead.
11075: #
11076: # For a given well defined symb, courside, domain, username,
11077: # and course environment, the seed is reproducible.
11078: #
1.31 www 11079: sub rndseed {
1.1133 foxr 11080: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11081: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11082: if (!defined($symb)) {
1.366 albertel 11083: unless ($symb=$wsymb) { return time; }
11084: }
1.1146 foxr 11085: if (!defined $courseid) {
11086: $courseid=$wcourseid;
11087: }
11088: if (!defined $domain) { $domain=$wdomain; }
11089: if (!defined $username) { $username=$wusername }
1.1133 foxr 11090:
11091: my $which;
11092: if (defined($cenv->{'rndseed'})) {
11093: $which = $cenv->{'rndseed'};
11094: } else {
11095: $which =&get_rand_alg($courseid);
11096: }
1.491 albertel 11097: if (defined(&getCODE())) {
1.1133 foxr 11098:
1.675 albertel 11099: if ($which eq '64bit5') {
11100: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11101: } elsif ($which eq '64bit4') {
1.575 albertel 11102: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11103: } else {
11104: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11105: }
1.675 albertel 11106: } elsif ($which eq '64bit5') {
11107: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11108: } elsif ($which eq '64bit4') {
11109: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11110: } elsif ($which eq '64bit3') {
11111: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11112: } elsif ($which eq '64bit2') {
11113: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11114: } elsif ($which eq '64bit') {
11115: return &rndseed_64bit($symb,$courseid,$domain,$username);
11116: }
11117: return &rndseed_32bit($symb,$courseid,$domain,$username);
11118: }
11119:
11120: sub rndseed_32bit {
11121: my ($symb,$courseid,$domain,$username)=@_;
11122: {
11123: use integer;
11124: my $symbchck=unpack("%32C*",$symb) << 27;
11125: my $symbseed=numval($symb) << 22;
11126: my $namechck=unpack("%32C*",$username) << 17;
11127: my $nameseed=numval($username) << 12;
11128: my $domainseed=unpack("%32C*",$domain) << 7;
11129: my $courseseed=unpack("%32C*",$courseid);
11130: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11131: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11132: #&logthis("rndseed :$num:$symb");
1.564 albertel 11133: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11134: return $num;
11135: }
11136: }
11137:
11138: sub rndseed_64bit {
11139: my ($symb,$courseid,$domain,$username)=@_;
11140: {
11141: use integer;
11142: my $symbchck=unpack("%32S*",$symb) << 21;
11143: my $symbseed=numval($symb) << 10;
11144: my $namechck=unpack("%32S*",$username);
11145:
11146: my $nameseed=numval($username) << 21;
11147: my $domainseed=unpack("%32S*",$domain) << 10;
11148: my $courseseed=unpack("%32S*",$courseid);
11149:
11150: my $num1=$symbchck+$symbseed+$namechck;
11151: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11152: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11153: #&logthis("rndseed :$num:$symb");
1.564 albertel 11154: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11155: return "$num1,$num2";
1.155 albertel 11156: }
1.366 albertel 11157: }
11158:
1.443 albertel 11159: sub rndseed_64bit2 {
11160: my ($symb,$courseid,$domain,$username)=@_;
11161: {
11162: use integer;
11163: # strings need to be an even # of cahracters long, it it is odd the
11164: # last characters gets thrown away
11165: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11166: my $symbseed=numval($symb) << 10;
11167: my $namechck=unpack("%32S*",$username.' ');
11168:
11169: my $nameseed=numval($username) << 21;
1.501 albertel 11170: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11171: my $courseseed=unpack("%32S*",$courseid.' ');
11172:
11173: my $num1=$symbchck+$symbseed+$namechck;
11174: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11175: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11176: #&logthis("rndseed :$num:$symb");
1.803 albertel 11177: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11178: return "$num1,$num2";
11179: }
11180: }
11181:
11182: sub rndseed_64bit3 {
11183: my ($symb,$courseid,$domain,$username)=@_;
11184: {
11185: use integer;
11186: # strings need to be an even # of cahracters long, it it is odd the
11187: # last characters gets thrown away
11188: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11189: my $symbseed=numval2($symb) << 10;
11190: my $namechck=unpack("%32S*",$username.' ');
11191:
11192: my $nameseed=numval2($username) << 21;
1.443 albertel 11193: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11194: my $courseseed=unpack("%32S*",$courseid.' ');
11195:
11196: my $num1=$symbchck+$symbseed+$namechck;
11197: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11198: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11199: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11200: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11201:
1.503 albertel 11202: return "$num1:$num2";
1.443 albertel 11203: }
11204: }
11205:
1.575 albertel 11206: sub rndseed_64bit4 {
11207: my ($symb,$courseid,$domain,$username)=@_;
11208: {
11209: use integer;
11210: # strings need to be an even # of cahracters long, it it is odd the
11211: # last characters gets thrown away
11212: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11213: my $symbseed=numval3($symb) << 10;
11214: my $namechck=unpack("%32S*",$username.' ');
11215:
11216: my $nameseed=numval3($username) << 21;
11217: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11218: my $courseseed=unpack("%32S*",$courseid.' ');
11219:
11220: my $num1=$symbchck+$symbseed+$namechck;
11221: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11222: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11223: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11224: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11225:
1.575 albertel 11226: return "$num1:$num2";
11227: }
11228: }
11229:
1.675 albertel 11230: sub rndseed_64bit5 {
11231: my ($symb,$courseid,$domain,$username)=@_;
11232: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11233: return "$num1:$num2";
11234: }
11235:
1.366 albertel 11236: sub rndseed_CODE_64bit {
11237: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11238: {
1.366 albertel 11239: use integer;
1.443 albertel 11240: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11241: my $symbseed=numval2($symb);
1.491 albertel 11242: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11243: my $CODEseed=numval(&getCODE());
1.443 albertel 11244: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11245: my $num1=$symbseed+$CODEchck;
11246: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11247: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11248: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11249: if ($_64bit) { $num1=(($num1<<32)>>32); }
11250: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11251: return "$num1:$num2";
1.366 albertel 11252: }
11253: }
11254:
1.575 albertel 11255: sub rndseed_CODE_64bit4 {
11256: my ($symb,$courseid,$domain,$username)=@_;
11257: {
11258: use integer;
11259: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11260: my $symbseed=numval3($symb);
11261: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11262: my $CODEseed=numval3(&getCODE());
11263: my $courseseed=unpack("%32S*",$courseid.' ');
11264: my $num1=$symbseed+$CODEchck;
11265: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11266: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11267: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11268: if ($_64bit) { $num1=(($num1<<32)>>32); }
11269: if ($_64bit) { $num2=(($num2<<32)>>32); }
11270: return "$num1:$num2";
11271: }
11272: }
11273:
1.675 albertel 11274: sub rndseed_CODE_64bit5 {
11275: my ($symb,$courseid,$domain,$username)=@_;
11276: my $code = &getCODE();
11277: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11278: return "$num1:$num2";
11279: }
11280:
1.366 albertel 11281: sub setup_random_from_rndseed {
11282: my ($rndseed)=@_;
1.503 albertel 11283: if ($rndseed =~/([,:])/) {
11284: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11285: &Math::Random::random_set_seed(abs($num1),abs($num2));
11286: } else {
11287: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11288: }
1.36 albertel 11289: }
11290:
1.474 albertel 11291: sub latest_receipt_algorithm_id {
1.835 albertel 11292: return 'receipt3';
1.474 albertel 11293: }
11294:
1.480 www 11295: sub recunique {
11296: my $fucourseid=shift;
11297: my $unique;
1.835 albertel 11298: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11299: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11300: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11301: } else {
11302: $unique=$perlvar{'lonReceipt'};
11303: }
11304: return unpack("%32C*",$unique);
11305: }
11306:
11307: sub recprefix {
11308: my $fucourseid=shift;
11309: my $prefix;
1.835 albertel 11310: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11311: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11312: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11313: } else {
11314: $prefix=$perlvar{'lonHostID'};
11315: }
11316: return unpack("%32C*",$prefix);
11317: }
11318:
1.76 www 11319: sub ireceipt {
1.474 albertel 11320: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11321:
11322: my $return =&recprefix($fucourseid).'-';
11323:
11324: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11325: $env{'request.state'} eq 'construct') {
11326: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11327: return $return;
11328: }
11329:
1.76 www 11330: my $cuname=unpack("%32C*",$funame);
11331: my $cudom=unpack("%32C*",$fudom);
11332: my $cucourseid=unpack("%32C*",$fucourseid);
11333: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11334: my $cunique=&recunique($fucourseid);
1.474 albertel 11335: my $cpart=unpack("%32S*",$part);
1.835 albertel 11336: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11337:
1.790 albertel 11338: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11339:
11340: $return.= ($cunique%$cuname+
11341: $cunique%$cudom+
11342: $cusymb%$cuname+
11343: $cusymb%$cudom+
11344: $cucourseid%$cuname+
11345: $cucourseid%$cudom+
11346: $cpart%$cuname+
11347: $cpart%$cudom);
11348: } else {
11349: $return.= ($cunique%$cuname+
11350: $cunique%$cudom+
11351: $cusymb%$cuname+
11352: $cusymb%$cudom+
11353: $cucourseid%$cuname+
11354: $cucourseid%$cudom);
11355: }
11356: return $return;
1.76 www 11357: }
11358:
11359: sub receipt {
1.474 albertel 11360: my ($part)=@_;
1.790 albertel 11361: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11362: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11363: }
1.260 ng 11364:
1.790 albertel 11365: sub whichuser {
11366: my ($passedsymb)=@_;
11367: my ($symb,$courseid,$domain,$name,$publicuser);
11368: if (defined($env{'form.grade_symb'})) {
11369: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11370: my $allowed=&allowed('vgr',$tmp_courseid);
11371: if (!$allowed &&
11372: exists($env{'request.course.sec'}) &&
11373: $env{'request.course.sec'} !~ /^\s*$/) {
11374: $allowed=&allowed('vgr',$tmp_courseid.
11375: '/'.$env{'request.course.sec'});
11376: }
11377: if ($allowed) {
11378: ($symb)=&get_env_multiple('form.grade_symb');
11379: $courseid=$tmp_courseid;
11380: ($domain)=&get_env_multiple('form.grade_domain');
11381: ($name)=&get_env_multiple('form.grade_username');
11382: return ($symb,$courseid,$domain,$name,$publicuser);
11383: }
11384: }
11385: if (!$passedsymb) {
11386: $symb=&symbread();
11387: } else {
11388: $symb=$passedsymb;
11389: }
11390: $courseid=$env{'request.course.id'};
11391: $domain=$env{'user.domain'};
11392: $name=$env{'user.name'};
11393: if ($name eq 'public' && $domain eq 'public') {
11394: if (!defined($env{'form.username'})) {
11395: $env{'form.username'}.=time.rand(10000000);
11396: }
11397: $name.=$env{'form.username'};
11398: }
11399: return ($symb,$courseid,$domain,$name,$publicuser);
11400:
11401: }
11402:
1.36 albertel 11403: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11404: # returns either the contents of the file or
11405: # -1 if the file doesn't exist
1.481 raeburn 11406: #
11407: # if the target is a file that was uploaded via DOCS,
11408: # a check will be made to see if a current copy exists on the local server,
11409: # if it does this will be served, otherwise a copy will be retrieved from
11410: # the home server for the course and stored in /home/httpd/html/userfiles on
11411: # the local server.
1.472 albertel 11412:
1.36 albertel 11413: sub getfile {
1.538 albertel 11414: my ($file) = @_;
1.609 banghart 11415: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11416: &repcopy($file);
11417: return &readfile($file);
11418: }
11419:
11420: sub repcopy_userfile {
11421: my ($file)=@_;
1.1142 raeburn 11422: my $londocroot = $perlvar{'lonDocRoot'};
11423: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11424: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11425: my ($cdom,$cnum,$filename) =
1.811 albertel 11426: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11427: my $uri="/uploaded/$cdom/$cnum/$filename";
11428: if (-e "$file") {
1.828 www 11429: # we already have a local copy, check it out
1.538 albertel 11430: my @fileinfo = stat($file);
1.828 www 11431: my $rtncode;
11432: my $info;
1.538 albertel 11433: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11434: if ($lwpresp ne 'ok') {
1.828 www 11435: # there is no such file anymore, even though we had a local copy
1.482 albertel 11436: if ($rtncode eq '404') {
1.538 albertel 11437: unlink($file);
1.482 albertel 11438: }
11439: return -1;
11440: }
11441: if ($info < $fileinfo[9]) {
1.828 www 11442: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11443: return 'ok';
1.828 www 11444: } else {
11445: # the file is outdated, get rid of it
11446: unlink($file);
1.482 albertel 11447: }
1.828 www 11448: }
11449: # one way or the other, at this point, we don't have the file
11450: # construct the correct path for the file
11451: my @parts = ($cdom,$cnum);
11452: if ($filename =~ m|^(.+)/[^/]+$|) {
11453: push @parts, split(/\//,$1);
11454: }
11455: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11456: foreach my $part (@parts) {
11457: $path .= '/'.$part;
11458: if (!-e $path) {
11459: mkdir($path,0770);
1.482 albertel 11460: }
11461: }
1.828 www 11462: # now the path exists for sure
11463: # get a user agent
11464: my $ua=new LWP::UserAgent;
11465: my $transferfile=$file.'.in.transfer';
11466: # FIXME: this should flock
11467: if (-e $transferfile) { return 'ok'; }
11468: my $request;
11469: $uri=~s/^\///;
1.980 raeburn 11470: my $homeserver = &homeserver($cnum,$cdom);
11471: my $protocol = $protocol{$homeserver};
11472: $protocol = 'http' if ($protocol ne 'https');
11473: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11474: my $response=$ua->request($request,$transferfile);
11475: # did it work?
11476: if ($response->is_error()) {
11477: unlink($transferfile);
11478: &logthis("Userfile repcopy failed for $uri");
11479: return -1;
11480: }
11481: # worked, rename the transfer file
11482: rename($transferfile,$file);
1.607 raeburn 11483: return 'ok';
1.481 raeburn 11484: }
11485:
1.517 albertel 11486: sub tokenwrapper {
11487: my $uri=shift;
1.980 raeburn 11488: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11489: $uri=~s|^/||;
1.620 albertel 11490: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11491: my $token=$1;
1.552 albertel 11492: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11493: if ($udom && $uname && $file) {
11494: $file=~s|(\?\.*)*$||;
1.949 raeburn 11495: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11496: my $homeserver = &homeserver($uname,$udom);
11497: my $protocol = $protocol{$homeserver};
11498: $protocol = 'http' if ($protocol ne 'https');
11499: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11500: (($uri=~/\?/)?'&':'?').'token='.$token.
11501: '&tokenissued='.$perlvar{'lonHostID'};
11502: } else {
11503: return '/adm/notfound.html';
11504: }
11505: }
11506:
1.828 www 11507: # call with reqtype HEAD: get last modification time
11508: # call with reqtype GET: get the file contents
11509: # Do not call this with reqtype GET for large files! It loads everything into memory
11510: #
1.481 raeburn 11511: sub getuploaded {
11512: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11513: $uri=~s/^\///;
1.980 raeburn 11514: my $homeserver = &homeserver($cnum,$cdom);
11515: my $protocol = $protocol{$homeserver};
11516: $protocol = 'http' if ($protocol ne 'https');
11517: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11518: my $ua=new LWP::UserAgent;
11519: my $request=new HTTP::Request($reqtype,$uri);
11520: my $response=$ua->request($request);
11521: $$rtncode = $response->code;
1.482 albertel 11522: if (! $response->is_success()) {
11523: return 'failed';
11524: }
11525: if ($reqtype eq 'HEAD') {
1.486 www 11526: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11527: } elsif ($reqtype eq 'GET') {
11528: $$info = $response->content;
1.472 albertel 11529: }
1.482 albertel 11530: return 'ok';
1.36 albertel 11531: }
11532:
1.481 raeburn 11533: sub readfile {
11534: my $file = shift;
11535: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11536: my $fh;
11537: open($fh,"<$file");
11538: my $a='';
1.800 albertel 11539: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11540: return $a;
11541: }
11542:
1.36 albertel 11543: sub filelocation {
1.590 banghart 11544: my ($dir,$file) = @_;
11545: my $location;
11546: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11547:
11548: if ($file =~ m-^/adm/-) {
11549: $file=~s-^/adm/wrapper/-/-;
11550: $file=~s-^/adm/coursedocs/showdoc/-/-;
11551: }
1.882 albertel 11552:
1.1139 www 11553: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11554: $location = $file;
1.609 banghart 11555: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11556: my ($udom,$uname,$filename)=
1.811 albertel 11557: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11558: my $home=&homeserver($uname,$udom);
11559: my $is_me=0;
11560: my @ids=¤t_machine_ids();
11561: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11562: if ($is_me) {
1.1117 foxr 11563: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11564: } else {
11565: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11566: $udom.'/'.$uname.'/'.$filename;
11567: }
1.882 albertel 11568: } elsif ($file =~ m-^/adm/-) {
11569: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11570: } else {
11571: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11572: $file=~s:^/(res|priv)/:/:;
11573: my $space=$1;
1.590 banghart 11574: if ( !( $file =~ m:^/:) ) {
11575: $location = $dir. '/'.$file;
11576: } else {
1.1142 raeburn 11577: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11578: }
1.59 albertel 11579: }
1.590 banghart 11580: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11581: while ($location=~m{/\.\./}) {
11582: if ($location =~ m{/[^/]+/\.\./}) {
11583: $location=~ s{/[^/]+/\.\./}{/}g;
11584: } else {
11585: $location=~ s{/\.\./}{/}g;
11586: }
11587: } #remove dir/..
1.590 banghart 11588: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11589: return $location;
1.46 www 11590: }
1.36 albertel 11591:
1.46 www 11592: sub hreflocation {
11593: my ($dir,$file)=@_;
1.980 raeburn 11594: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11595: $file=filelocation($dir,$file);
1.700 albertel 11596: } elsif ($file=~m-^/adm/-) {
11597: $file=~s-^/adm/wrapper/-/-;
11598: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11599: }
11600: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11601: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11602: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11603: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11604: {/uploaded/$1/$2/}x;
1.46 www 11605: }
1.913 albertel 11606: if ($file=~ m{^/userfiles/}) {
11607: $file =~ s{^/userfiles/}{/uploaded/};
11608: }
1.462 albertel 11609: return $file;
1.465 albertel 11610: }
11611:
1.1139 www 11612:
11613:
11614:
11615:
1.465 albertel 11616: sub current_machine_domains {
1.853 albertel 11617: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11618: }
11619:
11620: sub machine_domains {
11621: my ($hostname) = @_;
1.465 albertel 11622: my @domains;
1.838 albertel 11623: my %hostname = &all_hostnames();
1.465 albertel 11624: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11625: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11626: if ($hostname eq $name) {
1.844 albertel 11627: push(@domains,&host_domain($id));
1.465 albertel 11628: }
11629: }
11630: return @domains;
11631: }
11632:
11633: sub current_machine_ids {
1.853 albertel 11634: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11635: }
11636:
11637: sub machine_ids {
11638: my ($hostname) = @_;
11639: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11640: my @ids;
1.888 albertel 11641: my %name_to_host = &all_names();
1.889 albertel 11642: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11643: return @{ $name_to_host{$hostname} };
11644: }
11645: return;
1.31 www 11646: }
11647:
1.824 raeburn 11648: sub additional_machine_domains {
11649: my @domains;
11650: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11651: while( my $line = <$fh>) {
11652: $line =~ s/\s//g;
11653: push(@domains,$line);
11654: }
11655: return @domains;
11656: }
11657:
11658: sub default_login_domain {
11659: my $domain = $perlvar{'lonDefDomain'};
11660: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11661: foreach my $posdom (¤t_machine_domains(),
11662: &additional_machine_domains()) {
11663: if (lc($posdom) eq lc($testdomain)) {
11664: $domain=$posdom;
11665: last;
11666: }
11667: }
11668: return $domain;
11669: }
11670:
1.31 www 11671: # ------------------------------------------------------------- Declutters URLs
11672:
11673: sub declutter {
11674: my $thisfn=shift;
1.569 albertel 11675: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11676: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11677: $thisfn=~s/^\///;
1.697 albertel 11678: $thisfn=~s|^adm/wrapper/||;
11679: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11680: $thisfn=~s/^res\///;
1.1172 bisitz 11681: $thisfn=~s/^priv\///;
1.1032 raeburn 11682: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11683: $thisfn=~s/\?.+$//;
11684: }
1.268 www 11685: return $thisfn;
11686: }
11687:
11688: # ------------------------------------------------------------- Clutter up URLs
11689:
11690: sub clutter {
11691: my $thisfn='/'.&declutter(shift);
1.887 albertel 11692: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11693: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11694: $thisfn='/res'.$thisfn;
11695: }
1.1031 raeburn 11696: if ($thisfn !~m|^/adm|) {
11697: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11698: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11699: } else {
11700: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11701: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11702: if ($embstyle eq 'ssi'
11703: || ($embstyle eq 'hdn')
11704: || ($embstyle eq 'rat')
11705: || ($embstyle eq 'prv')
11706: || ($embstyle eq 'ign')) {
11707: #do nothing with these
11708: } elsif (($embstyle eq 'img')
1.695 albertel 11709: || ($embstyle eq 'emb')
11710: || ($embstyle eq 'wrp')) {
11711: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11712: } elsif ($embstyle eq 'unk'
11713: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11714: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11715: } else {
1.718 www 11716: # &logthis("Got a blank emb style");
1.695 albertel 11717: }
1.694 albertel 11718: }
11719: }
1.31 www 11720: return $thisfn;
1.12 www 11721: }
11722:
1.787 albertel 11723: sub clutter_with_no_wrapper {
11724: my $uri = &clutter(shift);
11725: if ($uri =~ m-^/adm/-) {
11726: $uri =~ s-^/adm/wrapper/-/-;
11727: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11728: }
11729: return $uri;
11730: }
11731:
1.557 albertel 11732: sub freeze_escape {
11733: my ($value)=@_;
11734: if (ref($value)) {
11735: $value=&nfreeze($value);
11736: return '__FROZEN__'.&escape($value);
11737: }
11738: return &escape($value);
11739: }
11740:
1.11 www 11741:
1.557 albertel 11742: sub thaw_unescape {
11743: my ($value)=@_;
11744: if ($value =~ /^__FROZEN__/) {
11745: substr($value,0,10,undef);
11746: $value=&unescape($value);
11747: return &thaw($value);
11748: }
11749: return &unescape($value);
11750: }
11751:
1.436 albertel 11752: sub correct_line_ends {
11753: my ($result)=@_;
11754: $$result =~s/\r\n/\n/mg;
11755: $$result =~s/\r/\n/mg;
1.415 albertel 11756: }
1.1 albertel 11757: # ================================================================ Main Program
11758:
1.184 www 11759: sub goodbye {
1.204 albertel 11760: &logthis("Starting Shut down");
1.443 albertel 11761: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11762: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11763: #converted
1.599 albertel 11764: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11765: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11766: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11767: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11768: #1.1 only
1.870 albertel 11769: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11770: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11771: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11772: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11773: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11774: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11775: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11776: &flushcourselogs();
11777: &logthis("Shutting down");
11778: }
11779:
1.852 albertel 11780: sub get_dns {
1.1210 raeburn 11781: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11782: if (!$ignore_cache) {
11783: my ($content,$cached)=
11784: &Apache::lonnet::is_cached_new('dns',$url);
11785: if ($cached) {
1.1210 raeburn 11786: &$func($content,$hashref);
1.869 albertel 11787: return;
11788: }
11789: }
11790:
11791: my %alldns;
1.852 albertel 11792: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11793: foreach my $dns (<$config>) {
11794: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11795: my $line = $1;
11796: my ($host,$protocol) = split(/:/,$line);
11797: if ($protocol ne 'https') {
11798: $protocol = 'http';
11799: }
11800: $alldns{$host} = $protocol;
1.869 albertel 11801: }
11802: while (%alldns) {
11803: my ($dns) = keys(%alldns);
1.852 albertel 11804: my $ua=new LWP::UserAgent;
1.1134 raeburn 11805: $ua->timeout(30);
1.979 raeburn 11806: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11807: my $response=$ua->request($request);
1.979 raeburn 11808: delete($alldns{$dns});
1.852 albertel 11809: next if ($response->is_error());
11810: my @content = split("\n",$response->content);
1.1210 raeburn 11811: unless ($nocache) {
1.1219 raeburn 11812: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11813: }
11814: &$func(\@content,$hashref);
1.869 albertel 11815: return;
1.852 albertel 11816: }
11817: close($config);
1.871 albertel 11818: my $which = (split('/',$url))[3];
11819: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11820: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11821: my @content = <$config>;
1.1210 raeburn 11822: &$func(\@content,$hashref);
11823: return;
11824: }
11825:
11826: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11827: sub parse_dns_checksums_tab {
1.1210 raeburn 11828: my ($lines,$hashref) = @_;
11829: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11830: my $loncaparev = &get_server_loncaparev($machine_dom);
11831: my ($release,$timestamp) = split(/\-/,$loncaparev);
11832: my (%chksum,%revnum);
11833: if (ref($lines) eq 'ARRAY') {
11834: chomp(@{$lines});
1.1238 raeburn 11835: my $version = shift(@{$lines});
11836: if ($version eq $release) {
1.1210 raeburn 11837: foreach my $line (@{$lines}) {
1.1238 raeburn 11838: my ($file,$version,$shasum) = split(/,/,$line);
11839: $chksum{$file} = $shasum;
11840: $revnum{$file} = $version;
1.1210 raeburn 11841: }
11842: if (ref($hashref) eq 'HASH') {
11843: %{$hashref} = (
11844: sums => \%chksum,
11845: versions => \%revnum,
11846: );
11847: }
11848: }
11849: }
1.869 albertel 11850: return;
1.852 albertel 11851: }
1.1210 raeburn 11852:
11853: sub fetch_dns_checksums {
1.1238 raeburn 11854: my %checksums;
11855: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11856: my $loncaparev = &get_server_loncaparev($machine_dom);
11857: my ($release,$timestamp) = split(/\-/,$loncaparev);
11858: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11859: \%checksums);
1.1210 raeburn 11860: return \%checksums;
11861: }
11862:
1.327 albertel 11863: # ------------------------------------------------------------ Read domain file
11864: {
1.852 albertel 11865: my $loaded;
1.846 albertel 11866: my %domain;
11867:
1.852 albertel 11868: sub parse_domain_tab {
11869: my ($lines) = @_;
11870: foreach my $line (@$lines) {
11871: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11872:
1.846 albertel 11873: chomp($line);
1.852 albertel 11874: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11875: my %this_domain;
11876: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11877: 'lang_def', 'city', 'longi', 'lati',
11878: 'primary') {
11879: $this_domain{$field} = shift(@elements);
11880: }
11881: $domain{$name} = \%this_domain;
1.852 albertel 11882: }
11883: }
1.864 albertel 11884:
11885: sub reset_domain_info {
11886: undef($loaded);
11887: undef(%domain);
11888: }
11889:
1.852 albertel 11890: sub load_domain_tab {
1.869 albertel 11891: my ($ignore_cache) = @_;
11892: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11893: my $fh;
11894: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11895: my @lines = <$fh>;
11896: &parse_domain_tab(\@lines);
1.448 albertel 11897: }
1.852 albertel 11898: close($fh);
11899: $loaded = 1;
1.327 albertel 11900: }
1.846 albertel 11901:
11902: sub domain {
1.852 albertel 11903: &load_domain_tab() if (!$loaded);
11904:
1.846 albertel 11905: my ($name,$what) = @_;
11906: return if ( !exists($domain{$name}) );
11907:
11908: if (!$what) {
11909: return $domain{$name}{'description'};
11910: }
11911: return $domain{$name}{$what};
11912: }
1.974 raeburn 11913:
11914: sub domain_info {
11915: &load_domain_tab() if (!$loaded);
11916: return %domain;
11917: }
11918:
1.327 albertel 11919: }
11920:
11921:
1.1 albertel 11922: # ------------------------------------------------------------- Read hosts file
11923: {
1.838 albertel 11924: my %hostname;
1.844 albertel 11925: my %hostdom;
1.845 albertel 11926: my %libserv;
1.852 albertel 11927: my $loaded;
1.888 albertel 11928: my %name_to_host;
1.1074 raeburn 11929: my %internetdom;
1.1107 raeburn 11930: my %LC_dns_serv;
1.852 albertel 11931:
11932: sub parse_hosts_tab {
11933: my ($file) = @_;
11934: foreach my $configline (@$file) {
11935: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11936: chomp($configline);
11937: if ($configline =~ /^\^/) {
11938: if ($configline =~ /^\^([\w.\-]+)/) {
11939: $LC_dns_serv{$1} = 1;
11940: }
11941: next;
11942: }
1.1074 raeburn 11943: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11944: $name=~s/\s//g;
11945: if ($id && $domain && $role && $name) {
11946: $hostname{$id}=$name;
1.888 albertel 11947: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11948: $hostdom{$id}=$domain;
11949: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11950: if (defined($protocol)) {
11951: if ($protocol eq 'https') {
11952: $protocol{$id} = $protocol;
11953: } else {
11954: $protocol{$id} = 'http';
11955: }
1.968 raeburn 11956: } else {
1.969 raeburn 11957: $protocol{$id} = 'http';
1.968 raeburn 11958: }
1.1074 raeburn 11959: if (defined($intdom)) {
11960: $internetdom{$id} = $intdom;
11961: }
1.852 albertel 11962: }
11963: }
11964: }
1.864 albertel 11965:
11966: sub reset_hosts_info {
1.897 albertel 11967: &purge_remembered();
1.864 albertel 11968: &reset_domain_info();
11969: &reset_hosts_ip_info();
1.892 albertel 11970: undef(%name_to_host);
1.864 albertel 11971: undef(%hostname);
11972: undef(%hostdom);
11973: undef(%libserv);
11974: undef($loaded);
11975: }
1.1 albertel 11976:
1.852 albertel 11977: sub load_hosts_tab {
1.869 albertel 11978: my ($ignore_cache) = @_;
11979: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11980: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11981: my @config = <$config>;
11982: &parse_hosts_tab(\@config);
11983: close($config);
11984: $loaded=1;
1.1 albertel 11985: }
1.852 albertel 11986:
1.838 albertel 11987: sub hostname {
1.852 albertel 11988: &load_hosts_tab() if (!$loaded);
11989:
1.838 albertel 11990: my ($lonid) = @_;
11991: return $hostname{$lonid};
11992: }
1.845 albertel 11993:
1.838 albertel 11994: sub all_hostnames {
1.852 albertel 11995: &load_hosts_tab() if (!$loaded);
11996:
1.838 albertel 11997: return %hostname;
11998: }
1.845 albertel 11999:
1.888 albertel 12000: sub all_names {
12001: &load_hosts_tab() if (!$loaded);
12002:
12003: return %name_to_host;
12004: }
12005:
1.974 raeburn 12006: sub all_host_domain {
12007: &load_hosts_tab() if (!$loaded);
12008: return %hostdom;
12009: }
12010:
1.845 albertel 12011: sub is_library {
1.852 albertel 12012: &load_hosts_tab() if (!$loaded);
12013:
1.845 albertel 12014: return exists($libserv{$_[0]});
12015: }
12016:
12017: sub all_library {
1.852 albertel 12018: &load_hosts_tab() if (!$loaded);
12019:
1.845 albertel 12020: return %libserv;
12021: }
12022:
1.1062 droeschl 12023: sub unique_library {
12024: #2x reverse removes all hostnames that appear more than once
12025: my %unique = reverse &all_library();
12026: return reverse %unique;
12027: }
12028:
1.841 albertel 12029: sub get_servers {
1.852 albertel 12030: &load_hosts_tab() if (!$loaded);
12031:
1.841 albertel 12032: my ($domain,$type) = @_;
12033: my %possible_hosts = ($type eq 'library') ? %libserv
12034: : %hostname;
12035: my %result;
1.842 albertel 12036: if (ref($domain) eq 'ARRAY') {
12037: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12038: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12039: $result{$host} = $hostname;
12040: }
12041: }
12042: } else {
12043: while ( my ($host,$hostname) = each(%possible_hosts)) {
12044: if ($hostdom{$host} eq $domain) {
12045: $result{$host} = $hostname;
12046: }
1.841 albertel 12047: }
12048: }
12049: return %result;
12050: }
1.845 albertel 12051:
1.1062 droeschl 12052: sub get_unique_servers {
12053: my %unique = reverse &get_servers(@_);
12054: return reverse %unique;
12055: }
12056:
1.844 albertel 12057: sub host_domain {
1.852 albertel 12058: &load_hosts_tab() if (!$loaded);
12059:
1.844 albertel 12060: my ($lonid) = @_;
12061: return $hostdom{$lonid};
12062: }
12063:
1.841 albertel 12064: sub all_domains {
1.852 albertel 12065: &load_hosts_tab() if (!$loaded);
12066:
1.841 albertel 12067: my %seen;
12068: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12069: return @uniq;
12070: }
1.1074 raeburn 12071:
12072: sub internet_dom {
12073: &load_hosts_tab() if (!$loaded);
12074:
12075: my ($lonid) = @_;
12076: return $internetdom{$lonid};
12077: }
1.1107 raeburn 12078:
12079: sub is_LC_dns {
12080: &load_hosts_tab() if (!$loaded);
12081:
12082: my ($hostname) = @_;
12083: return exists($LC_dns_serv{$hostname});
12084: }
12085:
1.1 albertel 12086: }
12087:
1.847 albertel 12088: {
12089: my %iphost;
1.856 albertel 12090: my %name_to_ip;
12091: my %lonid_to_ip;
1.869 albertel 12092:
1.847 albertel 12093: sub get_hosts_from_ip {
12094: my ($ip) = @_;
12095: my %iphosts = &get_iphost();
12096: if (ref($iphosts{$ip})) {
12097: return @{$iphosts{$ip}};
12098: }
12099: return;
1.839 albertel 12100: }
1.864 albertel 12101:
12102: sub reset_hosts_ip_info {
12103: undef(%iphost);
12104: undef(%name_to_ip);
12105: undef(%lonid_to_ip);
12106: }
1.856 albertel 12107:
12108: sub get_host_ip {
12109: my ($lonid) = @_;
12110: if (exists($lonid_to_ip{$lonid})) {
12111: return $lonid_to_ip{$lonid};
12112: }
12113: my $name=&hostname($lonid);
12114: my $ip = gethostbyname($name);
12115: return if (!$ip || length($ip) ne 4);
12116: $ip=inet_ntoa($ip);
12117: $name_to_ip{$name} = $ip;
12118: $lonid_to_ip{$lonid} = $ip;
12119: return $ip;
12120: }
1.847 albertel 12121:
12122: sub get_iphost {
1.869 albertel 12123: my ($ignore_cache) = @_;
1.894 albertel 12124:
1.869 albertel 12125: if (!$ignore_cache) {
12126: if (%iphost) {
12127: return %iphost;
12128: }
12129: my ($ip_info,$cached)=
12130: &Apache::lonnet::is_cached_new('iphost','iphost');
12131: if ($cached) {
12132: %iphost = %{$ip_info->[0]};
12133: %name_to_ip = %{$ip_info->[1]};
12134: %lonid_to_ip = %{$ip_info->[2]};
12135: return %iphost;
12136: }
12137: }
1.894 albertel 12138:
12139: # get yesterday's info for fallback
12140: my %old_name_to_ip;
12141: my ($ip_info,$cached)=
12142: &Apache::lonnet::is_cached_new('iphost','iphost');
12143: if ($cached) {
12144: %old_name_to_ip = %{$ip_info->[1]};
12145: }
12146:
1.888 albertel 12147: my %name_to_host = &all_names();
12148: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12149: my $ip;
12150: if (!exists($name_to_ip{$name})) {
12151: $ip = gethostbyname($name);
12152: if (!$ip || length($ip) ne 4) {
1.894 albertel 12153: if (defined($old_name_to_ip{$name})) {
12154: $ip = $old_name_to_ip{$name};
12155: &logthis("Can't find $name defaulting to old $ip");
12156: } else {
12157: &logthis("Name $name no IP found");
12158: next;
12159: }
12160: } else {
12161: $ip=inet_ntoa($ip);
1.847 albertel 12162: }
12163: $name_to_ip{$name} = $ip;
12164: } else {
12165: $ip = $name_to_ip{$name};
1.653 albertel 12166: }
1.888 albertel 12167: foreach my $id (@{ $name_to_host{$name} }) {
12168: $lonid_to_ip{$id} = $ip;
12169: }
12170: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12171: }
1.1219 raeburn 12172: &do_cache_new('iphost','iphost',
12173: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12174: 48*60*60);
1.869 albertel 12175:
1.847 albertel 12176: return %iphost;
1.598 albertel 12177: }
12178:
1.992 raeburn 12179: #
12180: # Given a DNS returns the loncapa host name for that DNS
12181: #
12182: sub host_from_dns {
12183: my ($dns) = @_;
12184: my @hosts;
12185: my $ip;
12186:
1.993 raeburn 12187: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12188: $ip = $name_to_ip{$dns};
12189: }
12190: if (!$ip) {
12191: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12192: if (length($ip) == 4) {
12193: $ip = &IO::Socket::inet_ntoa($ip);
12194: }
12195: }
12196: if ($ip) {
12197: @hosts = get_hosts_from_ip($ip);
12198: return $hosts[0];
12199: }
12200: return undef;
1.986 foxr 12201: }
1.992 raeburn 12202:
1.1074 raeburn 12203: sub get_internet_names {
12204: my ($lonid) = @_;
12205: return if ($lonid eq '');
12206: my ($idnref,$cached)=
12207: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12208: if ($cached) {
12209: return $idnref;
12210: }
12211: my $ip = &get_host_ip($lonid);
12212: my @hosts = &get_hosts_from_ip($ip);
12213: my %iphost = &get_iphost();
12214: my (@idns,%seen);
12215: foreach my $id (@hosts) {
12216: my $dom = &host_domain($id);
12217: my $prim_id = &domain($dom,'primary');
12218: my $prim_ip = &get_host_ip($prim_id);
12219: next if ($seen{$prim_ip});
12220: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12221: foreach my $id (@{$iphost{$prim_ip}}) {
12222: my $intdom = &internet_dom($id);
12223: unless (grep(/^\Q$intdom\E$/,@idns)) {
12224: push(@idns,$intdom);
12225: }
12226: }
12227: }
12228: $seen{$prim_ip} = 1;
12229: }
1.1219 raeburn 12230: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12231: }
12232:
1.986 foxr 12233: }
12234:
1.1079 raeburn 12235: sub all_loncaparevs {
1.1249 raeburn 12236: 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 12237: }
12238:
1.1227 raeburn 12239: # ---------------------------------------------------------- Read loncaparev table
12240: {
12241: sub load_loncaparevs {
12242: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12243: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12244: while (my $configline=<$config>) {
12245: chomp($configline);
12246: my ($hostid,$loncaparev)=split(/:/,$configline);
12247: $loncaparevs{$hostid}=$loncaparev;
12248: }
12249: close($config);
12250: }
12251: }
12252: }
12253: }
12254:
12255: # ---------------------------------------------------------- Read serverhostID table
12256: {
12257: sub load_serverhomeIDs {
12258: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12259: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12260: while (my $configline=<$config>) {
12261: chomp($configline);
12262: my ($name,$id)=split(/:/,$configline);
12263: $serverhomeIDs{$name}=$id;
12264: }
12265: close($config);
12266: }
12267: }
12268: }
12269: }
12270:
12271:
1.862 albertel 12272: BEGIN {
12273:
12274: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12275: unless ($readit) {
12276: {
12277: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12278: %perlvar = (%perlvar,%{$configvars});
12279: }
12280:
12281:
1.1 albertel 12282: # ------------------------------------------------------ Read spare server file
12283: {
1.448 albertel 12284: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12285:
12286: while (my $configline=<$config>) {
12287: chomp($configline);
1.284 matthew 12288: if ($configline) {
1.784 albertel 12289: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12290: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12291: push(@{ $spareid{$type} }, $host);
1.1 albertel 12292: }
12293: }
1.448 albertel 12294: close($config);
1.1 albertel 12295: }
1.11 www 12296: # ------------------------------------------------------------ Read permissions
12297: {
1.448 albertel 12298: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12299:
12300: while (my $configline=<$config>) {
1.448 albertel 12301: chomp($configline);
12302: if ($configline) {
12303: my ($role,$perm)=split(/ /,$configline);
12304: if ($perm ne '') { $pr{$role}=$perm; }
12305: }
1.11 www 12306: }
1.448 albertel 12307: close($config);
1.11 www 12308: }
12309:
12310: # -------------------------------------------- Read plain texts for permissions
12311: {
1.448 albertel 12312: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12313:
12314: while (my $configline=<$config>) {
1.448 albertel 12315: chomp($configline);
12316: if ($configline) {
1.742 raeburn 12317: my ($short,@plain)=split(/:/,$configline);
12318: %{$prp{$short}} = ();
12319: if (@plain > 0) {
12320: $prp{$short}{'std'} = $plain[0];
12321: for (my $i=1; $i<@plain; $i++) {
12322: $prp{$short}{'alt'.$i} = $plain[$i];
12323: }
12324: }
1.448 albertel 12325: }
1.135 www 12326: }
1.448 albertel 12327: close($config);
1.135 www 12328: }
12329:
12330: # ---------------------------------------------------------- Read package table
12331: {
1.448 albertel 12332: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12333:
12334: while (my $configline=<$config>) {
1.483 albertel 12335: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12336: chomp($configline);
12337: my ($short,$plain)=split(/:/,$configline);
12338: my ($pack,$name)=split(/\&/,$short);
12339: if ($plain ne '') {
12340: $packagetab{$pack.'&'.$name.'&name'}=$name;
12341: $packagetab{$short}=$plain;
12342: }
1.11 www 12343: }
1.448 albertel 12344: close($config);
1.329 matthew 12345: }
12346:
1.1073 raeburn 12347: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12348:
12349: &load_loncaparevs();
1.1073 raeburn 12350:
1.1074 raeburn 12351: # ---------------------------------------------------------- Read serverhostID table
12352:
1.1227 raeburn 12353: &load_serverhomeIDs();
12354:
12355: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12356: {
12357: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12358: if (-e $file) {
12359: my $parser = HTML::LCParser->new($file);
12360: while (my $token = $parser->get_token()) {
12361: if ($token->[0] eq 'S') {
12362: my $item = $token->[1];
12363: my $name = $token->[2]{'name'};
12364: my $value = $token->[2]{'value'};
12365: if ($item ne '' && $name ne '' && $value ne '') {
12366: my $release = $parser->get_text();
12367: $release =~ s/(^\s*|\s*$ )//gx;
12368: $needsrelease{$item.':'.$name.':'.$value} = $release;
12369: }
12370: }
12371: }
12372: }
1.1073 raeburn 12373: }
12374:
1.1138 raeburn 12375: # ---------------------------------------------------------- Read managers table
12376: {
12377: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12378: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12379: while (my $configline=<$config>) {
12380: chomp($configline);
12381: next if ($configline =~ /^\#/);
12382: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12383: $managerstab{$configline} = 1;
12384: }
12385: }
12386: close($config);
12387: }
12388: }
12389: }
12390:
1.329 matthew 12391: # ------------- set up temporary directory
12392: {
1.1117 foxr 12393: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12394:
1.11 www 12395: }
12396:
1.794 albertel 12397: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12398: 'compress_threshold'=> 20_000,
12399: });
1.185 www 12400:
1.281 www 12401: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12402: $dumpcount=0;
1.958 www 12403: $locknum=0;
1.22 www 12404:
1.163 harris41 12405: &logtouch();
1.672 albertel 12406: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12407: $readit=1;
1.564 albertel 12408: {
12409: use integer;
12410: my $test=(2**32)+1;
1.568 albertel 12411: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12412: &logthis(" Detected 64bit platform ($_64bit)");
12413: }
1.195 www 12414: }
1.1 albertel 12415: }
1.179 www 12416:
1.1 albertel 12417: 1;
1.191 harris41 12418: __END__
12419:
1.243 albertel 12420: =pod
12421:
1.191 harris41 12422: =head1 NAME
12423:
1.243 albertel 12424: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12425:
12426: =head1 SYNOPSIS
12427:
1.243 albertel 12428: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12429:
12430: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12431:
1.243 albertel 12432: Common parameters:
12433:
12434: =over 4
12435:
12436: =item *
12437:
12438: $uname : an internal username (if $cname expecting a course Id specifically)
12439:
12440: =item *
12441:
12442: $udom : a domain (if $cdom expecting a course's domain specifically)
12443:
12444: =item *
12445:
12446: $symb : a resource instance identifier
12447:
12448: =item *
12449:
12450: $namespace : the name of a .db file that contains the data needed or
12451: being set.
12452:
12453: =back
12454:
1.394 bowersj2 12455: =head1 OVERVIEW
1.191 harris41 12456:
1.394 bowersj2 12457: lonnet provides subroutines which interact with the
12458: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12459: about classes, users, and resources.
1.243 albertel 12460:
12461: For many of these objects you can also use this to store data about
12462: them or modify them in various ways.
1.191 harris41 12463:
1.394 bowersj2 12464: =head2 Symbs
1.191 harris41 12465:
1.394 bowersj2 12466: To identify a specific instance of a resource, LON-CAPA uses symbols
12467: or "symbs"X<symb>. These identifiers are built from the URL of the
12468: map, the resource number of the resource in the map, and the URL of
12469: the resource itself. The latter is somewhat redundant, but might help
12470: if maps change.
12471:
12472: An example is
12473:
12474: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12475:
12476: The respective map entry is
12477:
12478: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12479: title="Problem 2">
12480: </resource>
12481:
12482: Symbs are used by the random number generator, as well as to store and
12483: restore data specific to a certain instance of for example a problem.
12484:
12485: =head2 Storing And Retrieving Data
12486:
12487: X<store()>X<cstore()>X<restore()>Three of the most important functions
12488: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12489: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12490: is is the non-critical message twin of cstore. These functions are for
12491: handlers to store a perl hash to a user's permanent data space in an
12492: easy manner, and to retrieve it again on another call. It is expected
12493: that a handler would use this once at the beginning to retrieve data,
12494: and then again once at the end to send only the new data back.
12495:
12496: The data is stored in the user's data directory on the user's
12497: homeserver under the ID of the course.
12498:
12499: The hash that is returned by restore will have all of the previous
12500: value for all of the elements of the hash.
12501:
12502: Example:
12503:
12504: #creating a hash
12505: my %hash;
12506: $hash{'foo'}='bar';
12507:
12508: #storing it
12509: &Apache::lonnet::cstore(\%hash);
12510:
12511: #changing a value
12512: $hash{'foo'}='notbar';
12513:
12514: #adding a new value
12515: $hash{'bar'}='foo';
12516: &Apache::lonnet::cstore(\%hash);
12517:
12518: #retrieving the hash
12519: my %history=&Apache::lonnet::restore();
12520:
12521: #print the hash
12522: foreach my $key (sort(keys(%history))) {
12523: print("\%history{$key} = $history{$key}");
12524: }
12525:
12526: Will print out:
1.191 harris41 12527:
1.394 bowersj2 12528: %history{1:foo} = bar
12529: %history{1:keys} = foo:timestamp
12530: %history{1:timestamp} = 990455579
12531: %history{2:bar} = foo
12532: %history{2:foo} = notbar
12533: %history{2:keys} = foo:bar:timestamp
12534: %history{2:timestamp} = 990455580
12535: %history{bar} = foo
12536: %history{foo} = notbar
12537: %history{timestamp} = 990455580
12538: %history{version} = 2
12539:
12540: Note that the special hash entries C<keys>, C<version> and
12541: C<timestamp> were added to the hash. C<version> will be equal to the
12542: total number of versions of the data that have been stored. The
12543: C<timestamp> attribute will be the UNIX time the hash was
12544: stored. C<keys> is available in every historical section to list which
12545: keys were added or changed at a specific historical revision of a
12546: hash.
12547:
12548: B<Warning>: do not store the hash that restore returns directly. This
12549: will cause a mess since it will restore the historical keys as if the
12550: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12551:
1.394 bowersj2 12552: Calling convention:
1.191 harris41 12553:
1.1225 raeburn 12554: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12555: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12556:
1.394 bowersj2 12557: For more detailed information, see lonnet specific documentation.
1.191 harris41 12558:
1.394 bowersj2 12559: =head1 RETURN MESSAGES
1.191 harris41 12560:
1.394 bowersj2 12561: =over 4
1.191 harris41 12562:
1.394 bowersj2 12563: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12564:
1.394 bowersj2 12565: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12566: when the connection is brought back up
1.191 harris41 12567:
1.394 bowersj2 12568: =item * B<con_failed>: unable to contact remote host and unable to save message
12569: for later delivery
1.191 harris41 12570:
1.967 bisitz 12571: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12572:
1.394 bowersj2 12573: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12574: that was requested
1.191 harris41 12575:
1.243 albertel 12576: =back
1.191 harris41 12577:
1.243 albertel 12578: =head1 PUBLIC SUBROUTINES
1.191 harris41 12579:
1.243 albertel 12580: =head2 Session Environment Functions
1.191 harris41 12581:
1.243 albertel 12582: =over 4
1.191 harris41 12583:
1.394 bowersj2 12584: =item *
12585: X<appenv()>
1.949 raeburn 12586: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12587: the user envirnoment file, and will be restored for each access this
1.620 albertel 12588: user makes during this session, also modifies the %env for the current
1.949 raeburn 12589: process. Optional rolesarrayref - if defined contains a reference to an array
12590: of roles which are exempt from the restriction on modifying user.role entries
12591: in the user's environment.db and in %env.
1.191 harris41 12592:
12593: =item *
1.394 bowersj2 12594: X<delenv()>
1.987 raeburn 12595: B<delenv($delthis,$regexp)>: removes all items from the session
12596: environment file that begin with $delthis. If the
12597: optional second arg - $regexp - is true, $delthis is treated as a
12598: regular expression, otherwise \Q$delthis\E is used.
12599: The values are also deleted from the current processes %env.
1.191 harris41 12600:
1.795 albertel 12601: =item * get_env_multiple($name)
12602:
12603: gets $name from the %env hash, it seemlessly handles the cases where multiple
12604: values may be defined and end up as an array ref.
12605:
12606: returns an array of values
12607:
1.243 albertel 12608: =back
12609:
12610: =head2 User Information
1.191 harris41 12611:
1.243 albertel 12612: =over 4
1.191 harris41 12613:
12614: =item *
1.394 bowersj2 12615: X<queryauthenticate()>
12616: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12617: authentication scheme
12618:
12619: =item *
1.394 bowersj2 12620: X<authenticate()>
1.1073 raeburn 12621: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12622: authenticate user from domain's lib servers (first use the current
12623: one). C<$upass> should be the users password.
1.1073 raeburn 12624: $checkdefauth is optional (value is 1 if a check should be made to
12625: authenticate user using default authentication method, and allow
12626: account creation if username does not have account in the domain).
12627: $clientcancheckhost is optional (value is 1 if checking whether the
12628: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12629:
12630: =item *
1.394 bowersj2 12631: X<homeserver()>
12632: B<homeserver($uname,$udom)>: find the server which has
12633: the user's directory and files (there must be only one), this caches
12634: the answer, and also caches if there is a borken connection.
1.191 harris41 12635:
12636: =item *
1.394 bowersj2 12637: X<idget()>
12638: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12639: (IDs are a unique resource in a domain, there must be only 1 ID per
12640: username, and only 1 username per ID in a specific domain) (returns
12641: hash: id=>name,id=>name)
1.191 harris41 12642:
12643: =item *
1.394 bowersj2 12644: X<idrget()>
12645: B<idrget($udom,@unames)>: find the IDs behind a list of
12646: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12647:
12648: =item *
1.394 bowersj2 12649: X<idput()>
12650: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12651:
12652: =item *
1.394 bowersj2 12653: X<rolesinit()>
1.1169 droeschl 12654: B<rolesinit($udom,$username)>: get user privileges.
12655: returns user role, first access and timer interval hashes
1.243 albertel 12656:
12657: =item *
1.1171 droeschl 12658: X<privileged()>
12659: B<privileged($username,$domain)>: returns a true if user has a
12660: privileged and active role (i.e. su or dc), false otherwise.
12661:
12662: =item *
1.551 albertel 12663: X<getsection()>
12664: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12665: course $cname, return section name/number or '' for "not in course"
12666: and '-1' for "no section"
12667:
12668: =item *
1.394 bowersj2 12669: X<userenvironment()>
12670: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12671: passed in @what from the requested user's environment, returns a hash
12672:
1.858 raeburn 12673: =item *
12674: X<userlog_query()>
1.859 albertel 12675: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12676: activity.log file. %filters defines filters applied when parsing the
12677: log file. These can be start or end timestamps, or the type of action
12678: - log to look for Login or Logout events, check for Checkin or
12679: Checkout, role for role selection. The response is in the form
12680: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12681: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12682:
1.243 albertel 12683: =back
12684:
12685: =head2 User Roles
12686:
12687: =over 4
12688:
12689: =item *
12690:
1.810 raeburn 12691: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12692: F: full access
12693: U,I,K: authentication modes (cxx only)
12694: '': forbidden
12695: 1: user needs to choose course
12696: 2: browse allowed
1.766 albertel 12697: A: passphrase authentication needed
1.243 albertel 12698:
12699: =item *
12700:
1.1192 raeburn 12701: constructaccess($url,$setpriv) : check for access to construction space URL
12702:
12703: See if the owner domain and name in the URL match those in the
12704: expected environment. If so, return three element list
12705: ($ownername,$ownerdomain,$ownerhome).
12706:
12707: Otherwise return the null string.
12708:
12709: If second argument 'setpriv' is true, it assigns the privileges,
12710: and returns the same three element list, unless the owner has
12711: blocked "ad hoc" Domain Coordinator access to the Author Space,
12712: in which case the null string is returned.
12713:
12714: =item *
12715:
1.243 albertel 12716: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12717: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12718: and course level
12719:
12720: =item *
12721:
1.988 raeburn 12722: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12723: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12724: $type is Course (default) or Community.
1.988 raeburn 12725: If $forcedefault evaluates to true, text returned will be default
12726: text for $type. Otherwise, if this is a course, the text returned
12727: will be a custom name for the role (if defined in the course's
12728: environment). If no custom name is defined the default is returned.
12729:
1.832 raeburn 12730: =item *
12731:
1.1219 raeburn 12732: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12733: All arguments are optional. Returns a hash of a roles, either for
12734: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12735: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12736: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12737: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12738: For each key, value is set to colon-separated start and end times for
12739: the role. If no username and domain are specified, will default to
1.934 raeburn 12740: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12741: of role statuses (active, future or previous), roles
12742: (e.g., cc,in, st etc.) and domains of the roles which can be used
12743: to restrict the list of roles reported. If no array ref is
12744: provided for types, will default to return only active roles.
1.834 albertel 12745:
1.1195 raeburn 12746: =item *
12747:
12748: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12749: user: $uname:$udom has a role in the course: $cdom_$cnum.
12750:
12751: Additional optional arguments are: $type (if role checking is to be restricted
12752: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12753: available roles) or future (roles available in the future), and
12754: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12755: have active Domain Coordinator role in course's domain or in additional
12756: domains (specified in 'Domains to check for privileged users' in course
12757: environment -- set via: Course Settings -> Classlists and staff listing).
12758:
12759: =item *
12760:
12761: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12762: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12763: $possdomains and $possroles are optional array refs -- to domains to check and
12764: roles to check. If $possdomains is not specified, a dump will be done of the
12765: users' roles.db to check for a dc or su role in any domain. This can be
12766: time consuming if &privileged is called repeatedly (e.g., when displaying a
12767: classlist), so in such cases, supplying a $possdomains array is preferred, as
12768: this then allows &privileged_by_domain() to be used, which caches the identity
12769: of privileged users, eliminating the need for repeated calls to &dump().
12770:
12771: =item *
12772:
12773: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12774: where the outer hash keys are domains specified in the $possdomains array ref,
12775: next inner hash keys are privileged roles specified in the $roles array ref,
12776: and the innermost hash contains key = value pairs for username:domain = end:start
12777: for active or future "privileged" users with that role in that domain. To avoid
12778: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12779: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12780:
1.243 albertel 12781: =back
12782:
12783: =head2 User Modification
12784:
12785: =over 4
12786:
12787: =item *
12788:
1.957 raeburn 12789: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12790: user for the level given by URL. Optional start and end dates (leave empty
12791: string or zero for "no date")
1.191 harris41 12792:
12793: =item *
12794:
1.243 albertel 12795: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12796: change a users, password, possible return values are: ok,
12797: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12798: refused
1.191 harris41 12799:
12800: =item *
12801:
1.243 albertel 12802: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12803:
12804: =item *
12805:
1.1058 raeburn 12806: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12807: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12808:
12809: will update user information (firstname,middlename,lastname,generation,
12810: permanentemail), and if forceid is true, student/employee ID also.
12811: A user's institutional affiliation(s) can also be updated.
12812: User information fields will not be overwritten with empty entries
12813: unless the field is included in the $candelete array reference.
12814: This array is included when a single user is modified via "Manage Users",
12815: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12816:
12817: =item *
12818:
1.286 matthew 12819: modifystudent
12820:
1.957 raeburn 12821: modify a student's enrollment and identification information.
1.1235 raeburn 12822: The course id is resolved based on the current user's environment.
12823: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12824: associated with a course.
12825:
1.297 matthew 12826: This call is essentially a wrapper for lonnet::modifyuser and
12827: lonnet::modify_student_enrollment
1.286 matthew 12828:
12829: Inputs:
12830:
12831: =over 4
12832:
1.957 raeburn 12833: =item B<$udom> Student's loncapa domain
1.286 matthew 12834:
1.957 raeburn 12835: =item B<$uname> Student's loncapa login name
1.286 matthew 12836:
1.964 bisitz 12837: =item B<$uid> Student/Employee ID
1.286 matthew 12838:
1.957 raeburn 12839: =item B<$umode> Student's authentication mode
1.286 matthew 12840:
1.957 raeburn 12841: =item B<$upass> Student's password
1.286 matthew 12842:
1.957 raeburn 12843: =item B<$first> Student's first name
1.286 matthew 12844:
1.957 raeburn 12845: =item B<$middle> Student's middle name
1.286 matthew 12846:
1.957 raeburn 12847: =item B<$last> Student's last name
1.286 matthew 12848:
1.957 raeburn 12849: =item B<$gene> Student's generation
1.286 matthew 12850:
1.957 raeburn 12851: =item B<$usec> Student's section in course
1.286 matthew 12852:
12853: =item B<$end> Unix time of the roles expiration
12854:
12855: =item B<$start> Unix time of the roles start date
12856:
12857: =item B<$forceid> If defined, allow $uid to be changed
12858:
12859: =item B<$desiredhome> server to use as home server for student
12860:
1.957 raeburn 12861: =item B<$email> Student's permanent e-mail address
12862:
12863: =item B<$type> Type of enrollment (auto or manual)
12864:
1.963 raeburn 12865: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12866:
12867: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12868:
1.963 raeburn 12869: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12870:
1.963 raeburn 12871: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12872:
1.1216 raeburn 12873: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12874:
12875: =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 12876:
1.286 matthew 12877: =back
1.297 matthew 12878:
12879: =item *
12880:
12881: modify_student_enrollment
12882:
1.1235 raeburn 12883: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12884: 'role.request.course' must be defined for this function to proceed.
12885:
12886: Inputs:
12887:
12888: =over 4
12889:
1.1235 raeburn 12890: =item $udom, student's domain
1.297 matthew 12891:
1.1235 raeburn 12892: =item $uname, student's name
1.297 matthew 12893:
1.1235 raeburn 12894: =item $uid, student's user id
1.297 matthew 12895:
1.1235 raeburn 12896: =item $first, student's first name
1.297 matthew 12897:
12898: =item $middle
12899:
12900: =item $last
12901:
12902: =item $gene
12903:
12904: =item $usec
12905:
12906: =item $end
12907:
12908: =item $start
12909:
1.957 raeburn 12910: =item $type
12911:
12912: =item $locktype
12913:
12914: =item $cid
12915:
12916: =item $selfenroll
12917:
12918: =item $context
12919:
1.1216 raeburn 12920: =item $credits, number of credits student will earn from this class
12921:
1.297 matthew 12922: =back
12923:
1.191 harris41 12924:
12925: =item *
12926:
1.243 albertel 12927: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12928: custom role; give a custom role to a user for the level given by URL. Specify
12929: name and domain of role author, and role name
1.191 harris41 12930:
12931: =item *
12932:
1.243 albertel 12933: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12934:
12935: =item *
12936:
1.243 albertel 12937: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12938:
12939: =back
12940:
12941: =head2 Course Infomation
12942:
12943: =over 4
1.191 harris41 12944:
12945: =item *
12946:
1.1118 foxr 12947: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12948: specified course id, including all environment settings for the
12949: course, the description of the course will be in the hash under the
12950: key 'description'
1.191 harris41 12951:
1.1118 foxr 12952: $options is an optional parameter that if supplied is a hash reference that controls
12953: what how this function works. It has the following key/values:
12954:
12955: =over 4
12956:
12957: =item freshen_cache
12958:
12959: If defined, and the environment cache for the course is valid, it is
12960: returned in the returned hash.
12961:
12962: =item one_time
12963:
12964: If defined, the last cache time is set to _now_
12965:
12966: =item user
12967:
12968: If defined, the supplied username is used instead of the current user.
12969:
12970:
12971: =back
12972:
1.191 harris41 12973: =item *
12974:
1.624 albertel 12975: resdata($name,$domain,$type,@which) : request for current parameter
12976: setting for a specific $type, where $type is either 'course' or 'user',
12977: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12978: answers for 10 minutes.
1.243 albertel 12979:
1.877 foxr 12980: =item *
12981:
12982: get_courseresdata($courseid, $domain) : dump the entire course resource
12983: data base, returning a hash that is keyed by the resource name and has
12984: values that are the resource value. I believe that the timestamps and
12985: versions are also returned.
12986:
1.1236 raeburn 12987: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12988: supplemental content area. This routine caches the number of files for
12989: 10 minutes.
12990:
1.243 albertel 12991: =back
12992:
12993: =head2 Course Modification
12994:
12995: =over 4
1.191 harris41 12996:
12997: =item *
12998:
1.243 albertel 12999: writecoursepref($courseid,%prefs) : write preferences (environment
13000: database) for a course
1.191 harris41 13001:
13002: =item *
13003:
1.1011 raeburn 13004: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13005:
13006: =item *
13007:
1.1038 raeburn 13008: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13009:
1.1167 droeschl 13010: =item *
13011:
13012: is_course($courseid), is_course($cdom, $cnum)
13013:
13014: Accepts either a combined $courseid (in the form of domain_courseid) or the
13015: two component version $cdom, $cnum. It checks if the specified course exists.
13016:
13017: Returns:
13018: undef if the course doesn't exist, otherwise
13019: in scalar context the combined courseid.
13020: in list context the two components of the course identifier, domain and
13021: courseid.
13022:
1.243 albertel 13023: =back
13024:
13025: =head2 Resource Subroutines
13026:
13027: =over 4
1.191 harris41 13028:
13029: =item *
13030:
1.243 albertel 13031: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13032:
13033: =item *
13034:
1.243 albertel 13035: repcopy($filename) : subscribes to the requested file, and attempts to
13036: replicate from the owning library server, Might return
1.607 raeburn 13037: 'unavailable', 'not_found', 'forbidden', 'ok', or
13038: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13039: resource. Expects the local filesystem pathname
13040: (/home/httpd/html/res/....)
13041:
13042: =back
13043:
13044: =head2 Resource Information
13045:
13046: =over 4
1.191 harris41 13047:
13048: =item *
13049:
1.1228 raeburn 13050: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13051: and returns the value of a variety of different possible values,
13052: $varname should be a request string, and the other parameters can be
13053: used to specify who and what one is asking about. Ordinarily, $cid
13054: does not need to be specified, as it is retrived from
13055: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13056: within lonuserstate::loadmap() when initializing a course, before
13057: $env{'request.course.id'} has been set, so it needs to be provided
13058: in that one case.
1.243 albertel 13059:
13060: Possible values for $varname are environment.lastname (or other item
13061: from the envirnment hash), user.name (or someother aspect about the
13062: user), resource.0.maxtries (or some other part and parameter of a
13063: resource)
1.204 albertel 13064:
13065: =item *
13066:
1.243 albertel 13067: directcondval($number) : get current value of a condition; reads from a state
13068: string
1.204 albertel 13069:
13070: =item *
13071:
1.243 albertel 13072: condval($condidx) : value of condition index based on state
1.204 albertel 13073:
13074: =item *
13075:
1.243 albertel 13076: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13077: resource's metadata, $what should be either a specific key, or either
13078: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13079: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13080:
13081: this function automatically caches all requests
1.191 harris41 13082:
13083: =item *
13084:
1.243 albertel 13085: metadata_query($query,$custom,$customshow) : make a metadata query against the
13086: network of library servers; returns file handle of where SQL and regex results
13087: will be stored for query
1.191 harris41 13088:
13089: =item *
13090:
1.243 albertel 13091: symbread($filename) : return symbolic list entry (filename argument optional);
13092: returns the data handle
1.191 harris41 13093:
13094: =item *
13095:
1.1190 raeburn 13096: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13097: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13098: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13099: on failure, user must be in a course, as it assumes the existence of
13100: the course initial hash, and uses $env('request.course.id'}. The third
13101: arg is an optional reference to a scalar. If this arg is passed in the
13102: call to symbverify, it will be set to 1 if the symb has been set to be
13103: encrypted; otherwise it will be null.
1.191 harris41 13104:
13105: =item *
13106:
1.243 albertel 13107: symbclean($symb) : removes versions numbers from a symb, returns the
13108: cleaned symb
1.191 harris41 13109:
13110: =item *
13111:
1.243 albertel 13112: is_on_map($uri) : checks if the $uri is somewhere on the current
13113: course map, user must be in a course for it to work.
1.191 harris41 13114:
13115: =item *
13116:
1.243 albertel 13117: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13118:
13119: =item *
13120:
1.243 albertel 13121: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13122: a random seed, all arguments are optional, if they aren't sent it uses the
13123: environment to derive them. Note: if symb isn't sent and it can't get one
13124: from &symbread it will use the current time as its return value
1.191 harris41 13125:
13126: =item *
13127:
1.243 albertel 13128: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13129: unfakeable, receipt
1.191 harris41 13130:
13131: =item *
13132:
1.620 albertel 13133: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13134:
13135: =item *
13136:
1.243 albertel 13137: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13138:
13139: =item *
13140:
1.243 albertel 13141: 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 13142:
13143: =item *
13144:
1.243 albertel 13145: 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 13146:
13147: =item *
13148:
1.243 albertel 13149: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13150:
13151: =item *
13152:
1.243 albertel 13153: devalidate($symb) : devalidate temporary spreadsheet calculations,
13154: forcing spreadsheet to reevaluate the resource scores next time.
13155:
1.1195 raeburn 13156: =item *
13157:
1.1196 raeburn 13158: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13159: when viewing in course context.
1.1195 raeburn 13160:
1.1196 raeburn 13161: input: six args -- filename (decluttered), course number, course domain,
13162: url, symb (if registered) and group (if this is a
13163: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13164:
1.1196 raeburn 13165: output: array of five scalars --
1.1195 raeburn 13166: $cfile -- url for file editing if editable on current server
13167: $home -- homeserver of resource (i.e., for author if published,
13168: or course if uploaded.).
13169: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13170: $forceedit -- 1 if icon/link should be to go to edit mode
13171: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13172:
13173: =item *
13174:
13175: is_course_upload($file,$cnum,$cdom)
13176:
13177: Used in course context to determine if current file was uploaded to
13178: the course (i.e., would be found in /userfiles/docs on the course's
13179: homeserver.
13180:
13181: input: 3 args -- filename (decluttered), course number and course domain.
13182: output: boolean -- 1 if file was uploaded.
13183:
1.243 albertel 13184: =back
13185:
13186: =head2 Storing/Retreiving Data
13187:
13188: =over 4
1.191 harris41 13189:
13190: =item *
13191:
1.243 albertel 13192: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13193: for this url; hashref needs to be given and should be a \%hashname; the
13194: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13195: be derived from the env
1.191 harris41 13196:
13197: =item *
13198:
1.243 albertel 13199: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13200: uses critical subroutine
1.191 harris41 13201:
13202: =item *
13203:
1.243 albertel 13204: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13205: all args are optional
1.191 harris41 13206:
13207: =item *
13208:
1.717 albertel 13209: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13210: dumps the complete (or key matching regexp) namespace into a hash
13211: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13212: normally &store()ed into
13213:
13214: $range should be either an integer '100' (give me the first 100
13215: matching records)
13216: or be two integers sperated by a - with no spaces
13217: '30-50' (give me the 30th through the 50th matching
13218: records)
13219:
13220:
13221: =item *
13222:
13223: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13224: replaces a &store() version of data with a replacement set of data
13225: for a particular resource in a namespace passed in the $storehash hash
13226: reference
13227:
13228: =item *
13229:
1.243 albertel 13230: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13231: works very similar to store/cstore, but all data is stored in a
13232: temporary location and can be reset using tmpreset, $storehash should
13233: be a hash reference, returns nothing on success
1.191 harris41 13234:
13235: =item *
13236:
1.243 albertel 13237: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13238: similar to restore, but all data is stored in a temporary location and
13239: can be reset using tmpreset. Returns a hash of values on success,
13240: error string otherwise.
1.191 harris41 13241:
13242: =item *
13243:
1.243 albertel 13244: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13245: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13246:
13247: =item *
13248:
1.243 albertel 13249: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13250: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13251:
13252: =item *
13253:
1.243 albertel 13254: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13255: namesp ($udom and $uname are optional)
1.191 harris41 13256:
13257: =item *
13258:
1.702 albertel 13259: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13260: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13261: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13262:
1.702 albertel 13263: $range should be either an integer '100' (give me the first 100
13264: matching records)
13265: or be two integers sperated by a - with no spaces
13266: '30-50' (give me the 30th through the 50th matching
13267: records)
1.449 matthew 13268: =item *
13269:
13270: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13271: $store can be a scalar, an array reference, or if the amount to be
13272: incremented is > 1, a hash reference.
13273:
13274: ($udom and $uname are optional)
1.191 harris41 13275:
13276: =item *
13277:
1.243 albertel 13278: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13279: ($udom and $uname are optional)
1.191 harris41 13280:
13281: =item *
13282:
1.243 albertel 13283: cput($namespace,$storehash,$udom,$uname) : critical put
13284: ($udom and $uname are optional)
1.191 harris41 13285:
13286: =item *
13287:
1.748 albertel 13288: newput($namespace,$storehash,$udom,$uname) :
13289:
13290: Attempts to store the items in the $storehash, but only if they don't
13291: currently exist, if this succeeds you can be certain that you have
13292: successfully created a new key value pair in the $namespace db.
13293:
13294:
13295: Args:
13296: $namespace: name of database to store values to
13297: $storehash: hashref to store to the db
13298: $udom: (optional) domain of user containing the db
13299: $uname: (optional) name of user caontaining the db
13300:
13301: Returns:
13302: 'ok' -> succeeded in storing all keys of $storehash
13303: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13304: least <key> already existed in the db (other
13305: requested keys may also already exist)
1.967 bisitz 13306: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13307: 'con_lost' -> unable to contact request server
13308: 'refused' -> action was not allowed by remote machine
13309:
13310:
13311: =item *
13312:
1.243 albertel 13313: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13314: reference filled in from namesp (encrypts the return communication)
13315: ($udom and $uname are optional)
1.191 harris41 13316:
13317: =item *
13318:
1.243 albertel 13319: log($udom,$name,$home,$message) : write to permanent log for user; use
13320: critical subroutine
13321:
1.806 raeburn 13322: =item *
13323:
1.860 raeburn 13324: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13325: array reference filled in from namespace found in domain level on either
13326: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13327:
13328: =item *
13329:
1.860 raeburn 13330: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13331: domain level either on specified domain server ($uhome) or primary domain
13332: server ($udom and $uhome are optional)
1.806 raeburn 13333:
1.943 raeburn 13334: =item *
13335:
1.1240 raeburn 13336: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13337: for: authentication, language, quotas, timezone, date locale, and portal URL in
13338: the target domain.
13339:
13340: May also include additional key => value pairs for the following groups:
13341:
13342: =over
13343:
13344: =item
13345: disk quotas (MB allocated by default to portfolios and authoring spaces).
13346:
13347: =over
13348:
13349: =item defaultquota, authorquota
13350:
13351: =back
13352:
13353: =item
13354: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13355: portfolio for users).
13356:
13357: =over
13358:
13359: =item
13360: aboutme, blog, webdav, portfolio
13361:
13362: =back
13363:
13364: =item
13365: requestcourses: ability to request courses, and how requests are processed.
13366:
13367: =over
13368:
13369: =item
1.1246 raeburn 13370: official, unofficial, community, textbook
1.1240 raeburn 13371:
13372: =back
13373:
13374: =item
13375: inststatus: types of institutional affiliation, and order in which they are displayed.
13376:
13377: =over
13378:
13379: =item
1.1256 raeburn 13380: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13381:
13382: =back
13383:
13384: =item
13385: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13386: for course's uploaded content.
13387:
13388: =over
13389:
13390: =item
1.1246 raeburn 13391: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13392: communityquota, textbookquota
1.1240 raeburn 13393:
13394: =back
13395:
13396: =item
13397: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13398: on your servers.
13399:
13400: =over
13401:
13402: =item
13403: remotesessions, hostedsessions
13404:
13405: =back
13406:
13407: =back
13408:
13409: In cases where a domain coordinator has never used the "Set Domain Configuration"
13410: utility to create a configuration.db file on a domain's primary library server
13411: only the following domain defaults: auth_def, auth_arg_def, lang_def
13412: -- corresponding values are authentication type (internal, krb4, krb5,
13413: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13414: will be available. Values are retrieved from cache (if current), unless the
13415: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13416: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13417:
13418: Typical usage:
1.943 raeburn 13419:
1.1240 raeburn 13420: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13421:
1.243 albertel 13422: =back
13423:
13424: =head2 Network Status Functions
13425:
13426: =over 4
1.191 harris41 13427:
13428: =item *
13429:
1.1137 raeburn 13430: dirlist() : return directory list based on URI (first arg).
13431:
13432: Inputs: 1 required, 5 optional.
13433:
13434: =over
13435:
13436: =item
13437: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13438:
13439: =item
13440: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13441:
13442: =item
13443: $username - username of user/course to be listed. Extracted from $uri if absent.
13444:
13445: =item
13446: $getpropath - boolean: 1 if prepend path using &propath().
13447:
13448: =item
13449: $getuserdir - boolean: 1 if prepend path for "userfiles".
13450:
13451: =item
13452: $alternateRoot - path to prepend in place of path from $uri.
13453:
13454: =back
13455:
13456: Returns: Array of up to two items.
13457:
13458: =over
13459:
13460: a reference to an array of files/subdirectories
13461:
13462: =over
13463:
13464: Each element in the array of files/subdirectories is a & separated list of
13465: item name and the result of running stat on the item. If dirlist was requested
13466: for a file instead of a directory, the item name will be ''. For a directory
13467: listing, if the item is a metadata file, the element will end &N&M
13468: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13469: default copyright set (1).
13470:
13471: =back
13472:
13473: a scalar containing error condition (if encountered).
13474:
13475: =over
13476:
13477: =item
13478: no_host (no homeserver identified for $username:$domain).
13479:
13480: =item
13481: no_such_host (server contacted for listing not identified as valid host).
13482:
13483: =item
13484: con_lost (connection to remote server failed).
13485:
13486: =item
13487: refused (invalid $username:$domain received on lond side).
13488:
13489: =item
13490: no_such_dir (directory at specified path on lond side does not exist).
13491:
13492: =item
13493: empty (directory at specified path on lond side is empty).
13494:
13495: =over
13496:
13497: This is currently not encountered because the &ls3, &ls2,
13498: &ls (_handler) routines on the lond side do not filter out
13499: . and .. from a directory listing.
13500:
13501: =back
13502:
13503: =back
13504:
13505: =back
1.191 harris41 13506:
13507: =item *
13508:
1.243 albertel 13509: spareserver() : find server with least workload from spare.tab
13510:
1.986 foxr 13511:
13512: =item *
13513:
13514: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13515: if there is no corresponding loncapa host.
13516:
1.243 albertel 13517: =back
13518:
1.986 foxr 13519:
1.243 albertel 13520: =head2 Apache Request
13521:
13522: =over 4
1.191 harris41 13523:
13524: =item *
13525:
1.243 albertel 13526: ssi($url,%hash) : server side include, does a complete request cycle on url to
13527: localhost, posts hash
13528:
13529: =back
13530:
13531: =head2 Data to String to Data
13532:
13533: =over 4
1.191 harris41 13534:
13535: =item *
13536:
1.243 albertel 13537: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13538: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13539:
13540: =item *
13541:
1.243 albertel 13542: hashref2str($hashref) : convert a hashref into a string complete with
13543: escaping and '=' and '&' separators, supports elements that are
13544: arrayrefs and hashrefs
1.191 harris41 13545:
13546: =item *
13547:
1.243 albertel 13548: arrayref2str($arrayref) : convert an arrayref into a string complete
13549: with escaping and '&' separators, supports elements that are arrayrefs
13550: and hashrefs
1.191 harris41 13551:
13552: =item *
13553:
1.243 albertel 13554: str2hash($string) : convert string to hash using unescaping and
13555: splitting on '=' and '&', supports elements that are arrayrefs and
13556: hashrefs
1.191 harris41 13557:
13558: =item *
13559:
1.243 albertel 13560: str2array($string) : convert string to hash using unescaping and
13561: splitting on '&', supports elements that are arrayrefs and hashrefs
13562:
13563: =back
13564:
13565: =head2 Logging Routines
13566:
13567:
13568: These routines allow one to make log messages in the lonnet.log and
13569: lonnet.perm logfiles.
1.191 harris41 13570:
1.1119 foxr 13571: =over 4
13572:
1.191 harris41 13573: =item *
13574:
1.243 albertel 13575: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13576:
13577: =item *
13578:
1.243 albertel 13579: logthis() : append message to the normal lonnet.log file, it gets
13580: preiodically rolled over and deleted.
1.191 harris41 13581:
13582: =item *
13583:
1.243 albertel 13584: logperm() : append a permanent message to lonnet.perm.log, this log
13585: file never gets deleted by any automated portion of the system, only
13586: messages of critical importance should go in here.
13587:
1.1119 foxr 13588:
1.243 albertel 13589: =back
13590:
13591: =head2 General File Helper Routines
13592:
13593: =over 4
1.191 harris41 13594:
13595: =item *
13596:
1.481 raeburn 13597: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13598: (a) files in /uploaded
13599: (i) If a local copy of the file exists -
13600: compares modification date of local copy with last-modified date for
13601: definitive version stored on home server for course. If local copy is
13602: stale, requests a new version from the home server and stores it.
13603: If the original has been removed from the home server, then local copy
13604: is unlinked.
13605: (ii) If local copy does not exist -
13606: requests the file from the home server and stores it.
13607:
13608: If $caller is 'uploadrep':
13609: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13610: for request for files originally uploaded via DOCS.
13611: - returns 'ok' if fresh local copy now available, -1 otherwise.
13612:
13613: Otherwise:
13614: This indicates a call from the content generation phase of the request.
13615: - returns the entire contents of the file or -1.
13616:
13617: (b) files in /res
13618: - returns the entire contents of a file or -1;
13619: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13620:
1.712 albertel 13621:
13622: =item *
13623:
13624: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13625: reference
13626:
13627: returns either a stat() list of data about the file or an empty list
13628: if the file doesn't exist or couldn't find out about it (connection
13629: problems or user unknown)
13630:
1.191 harris41 13631: =item *
13632:
1.243 albertel 13633: filelocation($dir,$file) : returns file system location of a file
13634: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13635: directory that relative $file lookups are to looked in ($dir of /a/dir
13636: and a file of ../bob will become /a/bob)
1.191 harris41 13637:
13638: =item *
13639:
13640: hreflocation($dir,$file) : returns file system location or a URL; same as
13641: filelocation except for hrefs
13642:
13643: =item *
13644:
13645: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13646:
1.243 albertel 13647: =back
13648:
1.608 albertel 13649: =head2 Usererfile file routines (/uploaded*)
13650:
13651: =over 4
13652:
13653: =item *
13654:
13655: userfileupload(): main rotine for putting a file in a user or course's
13656: filespace, arguments are,
13657:
1.620 albertel 13658: formname - required - this is the name of the element in $env where the
1.608 albertel 13659: filename, and the contents of the file to create/modifed exist
1.620 albertel 13660: the filename is in $env{'form.'.$formname.'.filename'} and the
13661: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13662: context - if coursedoc, store the file in the course of the active role
13663: of the current user;
13664: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13665: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13666: subdir - required - subdirectory to put the file in under ../userfiles/
13667: if undefined, it will be placed in "unknown"
13668:
13669: (This routine calls clean_filename() to remove any dangerous
13670: characters from the filename, and then calls finuserfileupload() to
13671: complete the transaction)
13672:
13673: returns either the url of the uploaded file (/uploaded/....) if successful
13674: and /adm/notfound.html if unsuccessful
13675:
13676: =item *
13677:
13678: clean_filename(): routine for cleaing a filename up for storage in
13679: userfile space, argument is:
13680:
13681: filename - proposed filename
13682:
13683: returns: the new clean filename
13684:
13685: =item *
13686:
1.1090 raeburn 13687: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13688: userspace, probably shouldn't be called directly
13689:
13690: docuname: username or courseid of destination for the file
13691: docudom: domain of user/course of destination for the file
13692: formname: same as for userfileupload()
1.1090 raeburn 13693: fname: filename (including subdirectories) for the file
13694: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13695: allfiles: reference to hash used to store objects found by parser
13696: codebase: reference to hash used for codebases of java objects found by parser
13697: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13698: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13699: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13700: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13701: context: if 'overwrite', will move the uploaded file from its temporary location to
13702: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13703: mimetype: reference to scalar to accommodate mime type determined
13704: from File::MMagic if $parser = parse.
1.608 albertel 13705:
13706: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13707: and /adm/notfound.html if unsuccessful (or an error message if context
13708: was 'overwrite').
13709:
1.608 albertel 13710:
13711: =item *
13712:
13713: renameuserfile(): renames an existing userfile to a new name
13714:
13715: Args:
13716: docuname: username or courseid of destination for the file
13717: docudom: domain of user/course of destination for the file
13718: old: current file name (including any subdirs under userfiles)
13719: new: desired file name (including any subdirs under userfiles)
13720:
13721: =item *
13722:
13723: mkdiruserfile(): creates a directory is a userfiles dir
13724:
13725: Args:
13726: docuname: username or courseid of destination for the file
13727: docudom: domain of user/course of destination for the file
13728: dir: dir to create (including any subdirs under userfiles)
13729:
13730: =item *
13731:
13732: removeuserfile(): removes a file that exists in userfiles
13733:
13734: Args:
13735: docuname: username or courseid of destination for the file
13736: docudom: domain of user/course of destination for the file
13737: fname: filname to delete (including any subdirs under userfiles)
13738:
13739: =item *
13740:
13741: removeuploadedurl(): convience function for removeuserfile()
13742:
13743: Args:
13744: url: a full /uploaded/... url to delete
13745:
1.747 albertel 13746: =item *
13747:
13748: get_portfile_permissions():
13749: Args:
13750: domain: domain of user or course contain the portfolio files
13751: user: name of user or num of course contain the portfolio files
13752: Returns:
13753: hashref of a dump of the proper file_permissions.db
13754:
13755:
13756: =item *
13757:
13758: get_access_controls():
13759:
13760: Args:
13761: current_permissions: the hash ref returned from get_portfile_permissions()
13762: group: (optional) the group you want the files associated with
13763: file: (optional) the file you want access info on
13764:
13765: Returns:
1.749 raeburn 13766: a hash (keys are file names) of hashes containing
13767: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13768: values are XML containing access control settings (see below)
1.747 albertel 13769:
13770: Internal notes:
13771:
1.749 raeburn 13772: access controls are stored in file_permissions.db as key=value pairs.
13773: key -> path to file/file_name\0uniqueID:scope_end_start
13774: where scope -> public,guest,course,group,domains or users.
13775: end -> UNIX time for end of access (0 -> no end date)
13776: start -> UNIX time for start of access
13777:
13778: value -> XML description of access control
13779: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13780: <start></start>
13781: <end></end>
13782:
13783: <password></password> for scope type = guest
13784:
13785: <domain></domain> for scope type = course or group
13786: <number></number>
13787: <roles id="">
13788: <role></role>
13789: <access></access>
13790: <section></section>
13791: <group></group>
13792: </roles>
13793:
13794: <dom></dom> for scope type = domains
13795:
13796: <users> for scope type = users
13797: <user>
13798: <uname></uname>
13799: <udom></udom>
13800: </user>
13801: </users>
13802: </scope>
13803:
13804: Access data is also aggregated for each file in an additional key=value pair:
13805: key -> path to file/file_name\0accesscontrol
13806: value -> reference to hash
13807: hash contains key = value pairs
13808: where key = uniqueID:scope_end_start
13809: value = UNIX time record was last updated
13810:
13811: Used to improve speed of look-ups of access controls for each file.
13812:
13813: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13814:
1.1198 raeburn 13815: =item *
13816:
1.749 raeburn 13817: modify_access_controls():
13818:
13819: Modifies access controls for a portfolio file
13820: Args
13821: 1. file name
13822: 2. reference to hash of required changes,
13823: 3. domain
13824: 4. username
13825: where domain,username are the domain of the portfolio owner
13826: (either a user or a course)
13827:
13828: Returns:
13829: 1. result of additions or updates ('ok' or 'error', with error message).
13830: 2. result of deletions ('ok' or 'error', with error message).
13831: 3. reference to hash of any new or updated access controls.
13832: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13833: key = integer (inbound ID)
1.1198 raeburn 13834: value = uniqueID
13835:
13836: =item *
13837:
13838: get_timebased_id():
13839:
13840: Attempts to get a unique timestamp-based suffix for use with items added to a
13841: course via the Course Editor (e.g., folders, composite pages,
13842: group bulletin boards).
13843:
13844: Args: (first three required; six others optional)
13845:
13846: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13847: docssequence, or name of group
13848:
13849: 2. keyid (alphanumeric): name of temporary locking key in hash,
13850: e.g., num, boardids
13851:
13852: 3. namespace: name of gdbm file used to store suffixes already assigned;
13853: file will be named nohist_namespace.db
13854:
13855: 4. cdom: domain of course; default is current course domain from %env
13856:
13857: 5. cnum: course number; default is current course number from %env
13858:
13859: 6. idtype: set to concat if an additional digit is to be appended to the
13860: unix timestamp to form the suffix, if the plain timestamp is already
13861: in use. Default is to not do this, but simply increment the unix
13862: timestamp by 1 until a unique key is obtained.
13863:
13864: 7. who: holder of locking key; defaults to user:domain for user.
13865:
13866: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13867: retrying); default is 3.
13868:
13869: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13870:
13871: Returns:
13872:
13873: 1. suffix obtained (numeric)
13874:
13875: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13876:
13877: 3. error: contains (localized) error message if an error occurred.
13878:
1.747 albertel 13879:
1.608 albertel 13880: =back
13881:
1.243 albertel 13882: =head2 HTTP Helper Routines
13883:
13884: =over 4
13885:
1.191 harris41 13886: =item *
13887:
13888: escape() : unpack non-word characters into CGI-compatible hex codes
13889:
13890: =item *
13891:
13892: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13893:
1.243 albertel 13894: =back
13895:
13896: =head1 PRIVATE SUBROUTINES
13897:
13898: =head2 Underlying communication routines (Shouldn't call)
13899:
13900: =over 4
13901:
13902: =item *
13903:
13904: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13905:
13906: =item *
13907:
13908: reply() : uses subreply to send a message to remote machine, logs all failures
13909:
13910: =item *
13911:
13912: critical() : passes a critical message to another server; if cannot
13913: get through then place message in connection buffer directory and
13914: returns con_delayed, if incapable of saving message, returns
13915: con_failed
13916:
13917: =item *
13918:
13919: reconlonc() : tries to reconnect lonc client processes.
13920:
13921: =back
13922:
13923: =head2 Resource Access Logging
13924:
13925: =over 4
13926:
13927: =item *
13928:
13929: flushcourselogs() : flush (save) buffer logs and access logs
13930:
13931: =item *
13932:
13933: courselog($what) : save message for course in hash
13934:
13935: =item *
13936:
13937: courseacclog($what) : save message for course using &courselog(). Perform
13938: special processing for specific resource types (problems, exams, quizzes, etc).
13939:
1.191 harris41 13940: =item *
13941:
13942: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13943: as a PerlChildExitHandler
1.243 albertel 13944:
13945: =back
13946:
13947: =head2 Other
13948:
13949: =over 4
13950:
13951: =item *
13952:
13953: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13954:
13955: =back
13956:
13957: =cut
1.877 foxr 13958:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>