Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.3
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.3! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.2 2012/05/28 15:02:06 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.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1117 foxr 100:
1.1090 raeburn 101: use File::Copy;
1.676 albertel 102:
1.195 www 103: my $readit;
1.550 foxr 104: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 105:
1.619 albertel 106: require Exporter;
107:
108: our @ISA = qw (Exporter);
109: our @EXPORT = qw(%env);
110:
1.449 matthew 111:
1.1 albertel 112: # --------------------------------------------------------------------- Logging
1.729 www 113: {
114: my $logid;
115: sub instructor_log {
1.957 raeburn 116: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if (($cnum eq '') || ($cdom eq '')) {
118: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
119: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
120: }
1.729 www 121: $logid++;
1.957 raeburn 122: my $now = time();
123: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 124: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 125: { $id => {
126: 'exe_uname' => $env{'user.name'},
127: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 128: 'exe_time' => $now,
1.730 www 129: 'exe_ip' => $ENV{'REMOTE_ADDR'},
130: 'delflag' => $delflag,
131: 'logentry' => $storehash,
132: 'uname' => $uname,
133: 'udom' => $udom,
134: }
1.957 raeburn 135: },$cdom,$cnum);
1.729 www 136: }
137: }
1.1 albertel 138:
1.163 harris41 139: sub logtouch {
140: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 141: unless (-e "$execdir/logs/lonnet.log") {
142: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 143: close $fh;
144: }
145: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
146: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
147: }
148:
1.1 albertel 149: sub logthis {
150: my $message=shift;
151: my $execdir=$perlvar{'lonDaemons'};
152: my $now=time;
153: my $local=localtime($now);
1.448 albertel 154: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 155: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
156: print $fh $logstring;
1.448 albertel 157: close($fh);
158: }
1.1 albertel 159: return 1;
160: }
161:
162: sub logperm {
163: my $message=shift;
164: my $execdir=$perlvar{'lonDaemons'};
165: my $now=time;
166: my $local=localtime($now);
1.448 albertel 167: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
168: print $fh "$now:$message:$local\n";
169: close($fh);
170: }
1.1 albertel 171: return 1;
172: }
173:
1.850 albertel 174: sub create_connection {
1.853 albertel 175: my ($hostname,$lonid) = @_;
1.851 albertel 176: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 177: Type => SOCK_STREAM,
178: Timeout => 10);
179: return 0 if (!$client);
1.890 albertel 180: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 181: my $result = <$client>;
182: chomp($result);
183: return 1 if ($result eq 'done');
184: return 0;
185: }
186:
1.983 raeburn 187: sub get_server_timezone {
188: my ($cnum,$cdom) = @_;
189: my $home=&homeserver($cnum,$cdom);
190: if ($home ne 'no_host') {
191: my $cachetime = 24*3600;
192: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
193: if (defined($cached)) {
194: return $timezone;
195: } else {
196: my $timezone = &reply('servertimezone',$home);
197: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
198: }
199: }
200: }
1.850 albertel 201:
1.1106 raeburn 202: sub get_server_distarch {
203: my ($lonhost,$ignore_cache) = @_;
204: if (defined($lonhost)) {
205: if (!defined(&hostname($lonhost))) {
206: return;
207: }
208: my $cachetime = 12*3600;
209: if (!$ignore_cache) {
210: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
211: if (defined($cached)) {
212: return $distarch;
213: }
214: }
215: my $rep = &reply('serverdistarch',$lonhost);
216: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
217: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
218: $rep eq '') {
219: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
220: }
221: }
222: return;
223: }
224:
1.993 raeburn 225: sub get_server_loncaparev {
1.1073 raeburn 226: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 227: if (defined($lonhost)) {
228: if (!defined(&hostname($lonhost))) {
229: undef($lonhost);
230: }
231: }
232: if (!defined($lonhost)) {
233: if (defined(&domain($dom,'primary'))) {
234: $lonhost=&domain($dom,'primary');
235: if ($lonhost eq 'no_host') {
236: undef($lonhost);
237: }
238: }
239: }
240: if (defined($lonhost)) {
1.1073 raeburn 241: my $cachetime = 12*3600;
242: if (!$ignore_cache) {
243: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
244: if (defined($cached)) {
245: return $loncaparev;
246: }
247: }
248: my ($answer,$loncaparev);
249: my @ids=¤t_machine_ids();
250: if (grep(/^\Q$lonhost\E$/,@ids)) {
251: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 252: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 253: $loncaparev = $1;
254: }
255: } else {
256: $answer = &reply('serverloncaparev',$lonhost);
257: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
258: if ($caller eq 'loncron') {
259: my $ua=new LWP::UserAgent;
1.1082 raeburn 260: $ua->timeout(4);
1.1073 raeburn 261: my $protocol = $protocol{$lonhost};
262: $protocol = 'http' if ($protocol ne 'https');
263: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
264: my $request=new HTTP::Request('GET',$url);
265: my $response=$ua->request($request);
266: unless ($response->is_error()) {
267: my $content = $response->content;
1.1081 raeburn 268: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 269: $loncaparev = $1;
270: }
271: }
272: } else {
273: $loncaparev = $loncaparevs{$lonhost};
274: }
1.1081 raeburn 275: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
1.993 raeburn 278: }
1.1073 raeburn 279: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 280: }
281: }
282:
1.1074 raeburn 283: sub get_server_homeID {
284: my ($hostname,$ignore_cache,$caller) = @_;
285: unless ($ignore_cache) {
286: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
287: if (defined($cached)) {
288: return $serverhomeID;
289: }
290: }
291: my $cachetime = 12*3600;
292: my $serverhomeID;
293: if ($caller eq 'loncron') {
294: my @machine_ids = &machine_ids($hostname);
295: foreach my $id (@machine_ids) {
296: my $response = &reply('serverhomeID',$id);
297: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
298: $serverhomeID = $response;
299: last;
300: }
301: }
302: if ($serverhomeID eq '') {
303: $serverhomeID = $machine_ids[-1];
304: }
305: } else {
306: $serverhomeID = $serverhomeIDs{$hostname};
307: }
308: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
309: }
310:
1.1121 raeburn 311: sub get_remote_globals {
312: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 313: my ($result,%returnhash,%whatneeded);
314: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 315: foreach my $what (sort(keys(%{$whathash}))) {
316: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 317: my ($response,$cached);
1.1121 raeburn 318: unless ($ignore_cache) {
1.1125 raeburn 319: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 320: }
321: if (defined($cached)) {
1.1125 raeburn 322: $returnhash{$what} = $response;
1.1121 raeburn 323: } else {
1.1125 raeburn 324: $whatneeded{$what} = 1;
1.1121 raeburn 325: }
326: }
1.1125 raeburn 327: if (keys(%whatneeded) == 0) {
328: $result = 'ok';
329: } else {
1.1121 raeburn 330: my $requested = &freeze_escape(\%whatneeded);
331: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 332: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
333: ($rep eq 'unknown_cmd')) {
334: $result = $rep;
335: } else {
336: $result = 'ok';
1.1121 raeburn 337: my @pairs=split(/\&/,$rep);
1.1125 raeburn 338: foreach my $item (@pairs) {
339: my ($key,$value)=split(/=/,$item,2);
340: my $what = &unescape($key);
341: my $hashid = $lonhost.'-'.$what;
342: $returnhash{$what}=&thaw_unescape($value);
343: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 344: }
345: }
346: }
347: }
1.1125 raeburn 348: return ($result,\%returnhash);
1.1121 raeburn 349: }
350:
1.1124 raeburn 351: sub remote_devalidate_cache {
352: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 353: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 354: return $response;
355: }
356:
1.1 albertel 357: # -------------------------------------------------- Non-critical communication
358: sub subreply {
359: my ($cmd,$server)=@_;
1.838 albertel 360: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 361: #
362: # With loncnew process trimming, there's a timing hole between lonc server
363: # process exit and the master server picking up the listen on the AF_UNIX
364: # socket. In that time interval, a lock file will exist:
365:
366: my $lockfile=$peerfile.".lock";
367: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
368: sleep(1);
369: }
370: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 371: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 372: #
1.550 foxr 373: # We'll give the connection a few tries before abandoning it. If
374: # connection is not possible, we'll con_lost back to the client.
375: #
376: my $client;
377: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
378: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
379: Type => SOCK_STREAM,
380: Timeout => 10);
1.869 albertel 381: if ($client) {
1.550 foxr 382: last; # Connected!
1.850 albertel 383: } else {
1.853 albertel 384: &create_connection(&hostname($server),$server);
1.550 foxr 385: }
1.850 albertel 386: sleep(1); # Try again later if failed connection.
1.550 foxr 387: }
388: my $answer;
389: if ($client) {
1.704 albertel 390: print $client "sethost:$server:$cmd\n";
1.550 foxr 391: $answer=<$client>;
392: if (!$answer) { $answer="con_lost"; }
393: chomp($answer);
394: } else {
395: $answer = 'con_lost'; # Failed connection.
396: }
1.1 albertel 397: return $answer;
398: }
399:
400: sub reply {
401: my ($cmd,$server)=@_;
1.838 albertel 402: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 403: my $answer=subreply($cmd,$server);
1.65 www 404: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 405: &logthis("<font color=\"blue\">WARNING:".
1.12 www 406: " $cmd to $server returned $answer</font>");
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: # ----------------------------------------------------------- Send USR1 to lonc
412:
413: sub reconlonc {
1.891 albertel 414: my ($lonid) = @_;
415: my $hostname = &hostname($lonid);
416: if ($lonid) {
417: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
418: if ($hostname && -e $peerfile) {
419: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
420: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
421: Type => SOCK_STREAM,
422: Timeout => 10);
423: if ($client) {
424: print $client ("reset_retries\n");
425: my $answer=<$client>;
426: #reset just this one.
427: }
428: }
429: return;
430: }
431:
1.836 www 432: &logthis("Trying to reconnect lonc");
1.1 albertel 433: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 434: if (open(my $fh,"<$loncfile")) {
1.1 albertel 435: my $loncpid=<$fh>;
436: chomp($loncpid);
437: if (kill 0 => $loncpid) {
438: &logthis("lonc at pid $loncpid responding, sending USR1");
439: kill USR1 => $loncpid;
440: sleep 1;
1.836 www 441: } else {
1.12 www 442: &logthis(
1.672 albertel 443: "<font color=\"blue\">WARNING:".
1.12 www 444: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 445: }
446: } else {
1.836 www 447: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 448: }
449: }
450:
451: # ------------------------------------------------------ Critical communication
1.12 www 452:
1.1 albertel 453: sub critical {
454: my ($cmd,$server)=@_;
1.838 albertel 455: unless (&hostname($server)) {
1.672 albertel 456: &logthis("<font color=\"blue\">WARNING:".
1.89 www 457: " Critical message to unknown server ($server)</font>");
458: return 'no_such_host';
459: }
1.1 albertel 460: my $answer=reply($cmd,$server);
461: if ($answer eq 'con_lost') {
462: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 463: my $answer=reply($cmd,$server);
1.1 albertel 464: if ($answer eq 'con_lost') {
465: my $now=time;
466: my $middlename=$cmd;
1.5 www 467: $middlename=substr($middlename,0,16);
1.1 albertel 468: $middlename=~s/\W//g;
469: my $dfilename=
1.305 www 470: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
471: $dumpcount++;
1.1 albertel 472: {
1.448 albertel 473: my $dfh;
474: if (open($dfh,">$dfilename")) {
475: print $dfh "$cmd\n";
476: close($dfh);
477: }
1.1 albertel 478: }
479: sleep 2;
480: my $wcmd='';
481: {
1.448 albertel 482: my $dfh;
483: if (open($dfh,"<$dfilename")) {
484: $wcmd=<$dfh>;
485: close($dfh);
486: }
1.1 albertel 487: }
488: chomp($wcmd);
1.7 www 489: if ($wcmd eq $cmd) {
1.672 albertel 490: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 491: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 492: &logperm("D:$server:$cmd");
493: return 'con_delayed';
494: } else {
1.672 albertel 495: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 496: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 497: &logperm("F:$server:$cmd");
498: return 'con_failed';
499: }
500: }
501: }
502: return $answer;
1.405 albertel 503: }
504:
1.755 albertel 505: # ------------------------------------------- check if return value is an error
506:
507: sub error {
508: my ($result) = @_;
1.756 albertel 509: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 510: if ($2 == 2) { return undef; }
511: return $1;
512: }
513: return undef;
514: }
515:
1.783 albertel 516: sub convert_and_load_session_env {
517: my ($lonidsdir,$handle)=@_;
518: my @profile;
519: {
1.917 albertel 520: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
521: if (!$opened) {
1.915 albertel 522: return 0;
523: }
1.783 albertel 524: flock($idf,LOCK_SH);
525: @profile=<$idf>;
526: close($idf);
527: }
528: my %temp_env;
529: foreach my $line (@profile) {
1.786 albertel 530: if ($line !~ m/=/) {
531: return 0;
532: }
1.783 albertel 533: chomp($line);
534: my ($envname,$envvalue)=split(/=/,$line,2);
535: $temp_env{&unescape($envname)} = &unescape($envvalue);
536: }
537: unlink("$lonidsdir/$handle.id");
538: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
539: 0640)) {
540: %disk_env = %temp_env;
541: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
542: untie(%disk_env);
543: }
1.786 albertel 544: return 1;
1.783 albertel 545: }
546:
1.374 www 547: # ------------------------------------------- Transfer profile into environment
1.780 albertel 548: my $env_loaded;
549: sub transfer_profile_to_env {
1.788 albertel 550: my ($lonidsdir,$handle,$force_transfer) = @_;
551: if (!$force_transfer && $env_loaded) { return; }
1.374 www 552:
1.720 albertel 553: if (!defined($lonidsdir)) {
554: $lonidsdir = $perlvar{'lonIDsDir'};
555: }
556: if (!defined($handle)) {
557: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
558: }
559:
1.786 albertel 560: my $convert;
561: {
1.917 albertel 562: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
563: if (!$opened) {
1.915 albertel 564: return;
565: }
1.786 albertel 566: flock($idf,LOCK_SH);
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
568: &GDBM_READER(),0640)) {
569: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
570: untie(%disk_env);
571: } else {
572: $convert = 1;
573: }
574: }
575: if ($convert) {
576: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
577: &logthis("Failed to load session, or convert session.");
578: }
1.374 www 579: }
1.783 albertel 580:
1.786 albertel 581: my %remove;
1.783 albertel 582: while ( my $envname = each(%env) ) {
1.433 matthew 583: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
584: if ($time < time-300) {
1.783 albertel 585: $remove{$key}++;
1.433 matthew 586: }
587: }
588: }
1.783 albertel 589:
1.619 albertel 590: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 591: $env_loaded=1;
1.783 albertel 592: foreach my $expired_key (keys(%remove)) {
1.433 matthew 593: &delenv($expired_key);
1.374 www 594: }
1.1 albertel 595: }
596:
1.916 albertel 597: # ---------------------------------------------------- Check for valid session
598: sub check_for_valid_session {
1.1155 raeburn 599: my ($r,$name) = @_;
1.916 albertel 600: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 601: if ($name eq '') {
602: $name = 'lonID';
603: }
604: my $lonid=$cookies{$name};
1.916 albertel 605: return undef if (!$lonid);
606:
607: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 608: my $lonidsdir;
609: if ($name eq 'lonDAV') {
610: $lonidsdir=$r->dir_config('lonDAVsessDir');
611: } else {
612: $lonidsdir=$r->dir_config('lonIDsDir');
613: }
1.916 albertel 614: return undef if (!-e "$lonidsdir/$handle.id");
615:
1.917 albertel 616: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
617: return undef if (!$opened);
1.916 albertel 618:
619: flock($idf,LOCK_SH);
620: my %disk_env;
621: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
622: &GDBM_READER(),0640)) {
623: return undef;
624: }
625:
626: if (!defined($disk_env{'user.name'})
627: || !defined($disk_env{'user.domain'})) {
628: return undef;
629: }
630: return $handle;
631: }
632:
1.830 albertel 633: sub timed_flock {
634: my ($file,$lock_type) = @_;
635: my $failed=0;
636: eval {
637: local $SIG{__DIE__}='DEFAULT';
638: local $SIG{ALRM}=sub {
639: $failed=1;
640: die("failed lock");
641: };
642: alarm(13);
643: flock($file,$lock_type);
644: alarm(0);
645: };
646: if ($failed) {
647: return undef;
648: } else {
649: return 1;
650: }
651: }
652:
1.5 www 653: # ---------------------------------------------------------- Append Environment
654:
655: sub appenv {
1.949 raeburn 656: my ($newenv,$roles) = @_;
657: if (ref($newenv) eq 'HASH') {
658: foreach my $key (keys(%{$newenv})) {
659: my $refused = 0;
660: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
661: $refused = 1;
662: if (ref($roles) eq 'ARRAY') {
663: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
664: if (grep(/^\Q$role\E$/,@{$roles})) {
665: $refused = 0;
666: }
667: }
668: }
669: if ($refused) {
670: &logthis("<font color=\"blue\">WARNING: ".
671: "Attempt to modify environment ".$key." to ".$newenv->{$key}
672: .'</font>');
673: delete($newenv->{$key});
674: } else {
675: $env{$key}=$newenv->{$key};
676: }
677: }
678: my $opened = open(my $env_file,'+<',$env{'user.environment'});
679: if ($opened
680: && &timed_flock($env_file,LOCK_EX)
681: &&
682: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
683: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
684: while (my ($key,$value) = each(%{$newenv})) {
685: $disk_env{$key} = $value;
686: }
687: untie(%disk_env);
1.35 www 688: }
1.191 harris41 689: }
1.56 www 690: return 'ok';
691: }
692: # ----------------------------------------------------- Delete from Environment
693:
694: sub delenv {
1.1104 raeburn 695: my ($delthis,$regexp,$roles) = @_;
696: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
697: my $refused = 1;
698: if (ref($roles) eq 'ARRAY') {
699: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
700: if (grep(/^\Q$role\E$/,@{$roles})) {
701: $refused = 0;
702: }
703: }
704: if ($refused) {
705: &logthis("<font color=\"blue\">WARNING: ".
706: "Attempt to delete from environment ".$delthis);
707: return 'error';
708: }
1.56 www 709: }
1.917 albertel 710: my $opened = open(my $env_file,'+<',$env{'user.environment'});
711: if ($opened
1.915 albertel 712: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 713: &&
714: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
715: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 716: foreach my $key (keys(%disk_env)) {
1.987 raeburn 717: if ($regexp) {
718: if ($key=~/^$delthis/) {
719: delete($env{$key});
720: delete($disk_env{$key});
721: }
722: } else {
723: if ($key=~/^\Q$delthis\E/) {
724: delete($env{$key});
725: delete($disk_env{$key});
726: }
727: }
1.448 albertel 728: }
1.783 albertel 729: untie(%disk_env);
1.5 www 730: }
731: return 'ok';
1.369 albertel 732: }
733:
1.790 albertel 734: sub get_env_multiple {
735: my ($name) = @_;
736: my @values;
737: if (defined($env{$name})) {
738: # exists is it an array
739: if (ref($env{$name})) {
740: @values=@{ $env{$name} };
741: } else {
742: $values[0]=$env{$name};
743: }
744: }
745: return(@values);
746: }
747:
1.958 www 748: # ------------------------------------------------------------------- Locking
749:
750: sub set_lock {
751: my ($text)=@_;
752: $locknum++;
753: my $id=$$.'-'.$locknum;
754: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
755: 'session.lock.'.$id => $text});
756: return $id;
757: }
758:
759: sub get_locks {
760: my $num=0;
761: my %texts=();
762: foreach my $lock (split(/\,/,$env{'session.locks'})) {
763: if ($lock=~/\w/) {
764: $num++;
765: $texts{$lock}=$env{'session.lock.'.$lock};
766: }
767: }
768: return ($num,%texts);
769: }
770:
771: sub remove_lock {
772: my ($id)=@_;
773: my $newlocks='';
774: foreach my $lock (split(/\,/,$env{'session.locks'})) {
775: if (($lock=~/\w/) && ($lock ne $id)) {
776: $newlocks.=','.$lock;
777: }
778: }
779: &appenv({'session.locks' => $newlocks});
780: &delenv('session.lock.'.$id);
781: }
782:
783: sub remove_all_locks {
784: my $activelocks=$env{'session.locks'};
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: &remove_lock($lock);
788: }
789: }
790: }
791:
792:
1.369 albertel 793: # ------------------------------------------ Find out current server userload
794: sub userload {
795: my $numusers=0;
796: {
797: opendir(LONIDS,$perlvar{'lonIDsDir'});
798: my $filename;
799: my $curtime=time;
800: while ($filename=readdir(LONIDS)) {
1.925 albertel 801: next if ($filename eq '.' || $filename eq '..');
802: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 803: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 804: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 805: }
806: closedir(LONIDS);
807: }
808: my $userloadpercent=0;
809: my $maxuserload=$perlvar{'lonUserLoadLim'};
810: if ($maxuserload) {
1.371 albertel 811: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 812: }
1.372 albertel 813: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 814: return $userloadpercent;
1.283 www 815: }
816:
1.1 albertel 817: # ------------------------------ Find server with least workload from spare.tab
1.11 www 818:
1.1 albertel 819: sub spareserver {
1.1083 raeburn 820: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 821: my $spare_server;
1.370 albertel 822: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 823: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
824: : $userloadpercent;
1.1083 raeburn 825: my ($uint_dom,$remotesessions);
826: if (($udom ne '') && (&domain($udom) ne '')) {
827: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
828: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
829: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
830: $remotesessions = $udomdefaults{'remotesessions'};
831: }
1.1123 raeburn 832: my $spareshash = &this_host_spares($udom);
833: if (ref($spareshash) eq 'HASH') {
834: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
835: foreach my $try_server (@{ $spareshash->{'primary'} }) {
836: if ($uint_dom) {
837: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
838: $try_server));
839: }
840: ($spare_server, $lowest_load) =
841: &compare_server_load($try_server, $spare_server, $lowest_load);
842: }
1.1083 raeburn 843: }
1.784 albertel 844:
1.1123 raeburn 845: my $found_server = ($spare_server ne '' && $lowest_load < 100);
846:
847: if (!$found_server) {
848: if (ref($spareshash->{'default'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'default'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,
852: $remotesessions,$try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
857: }
858: }
1.784 albertel 859: }
860:
861: if (!$want_server_name) {
1.968 raeburn 862: my $protocol = 'http';
863: if ($protocol{$spare_server} eq 'https') {
864: $protocol = $protocol{$spare_server};
865: }
1.1001 raeburn 866: if (defined($spare_server)) {
867: my $hostname = &hostname($spare_server);
1.1083 raeburn 868: if (defined($hostname)) {
1.1001 raeburn 869: $spare_server = $protocol.'://'.$hostname;
870: }
871: }
1.784 albertel 872: }
873: return $spare_server;
874: }
875:
876: sub compare_server_load {
877: my ($try_server, $spare_server, $lowest_load) = @_;
878:
879: my $loadans = &reply('load', $try_server);
880: my $userloadans = &reply('userload',$try_server);
881:
882: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 883: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 884: }
885:
886: my $load;
887: if ($loadans =~ /\d/) {
888: if ($userloadans =~ /\d/) {
889: #both are numbers, pick the bigger one
890: $load = ($loadans > $userloadans) ? $loadans
891: : $userloadans;
1.411 albertel 892: } else {
1.784 albertel 893: $load = $loadans;
1.411 albertel 894: }
1.784 albertel 895: } else {
896: $load = $userloadans;
897: }
898:
899: if (($load =~ /\d/) && ($load < $lowest_load)) {
900: $spare_server = $try_server;
901: $lowest_load = $load;
1.370 albertel 902: }
1.784 albertel 903: return ($spare_server,$lowest_load);
1.202 matthew 904: }
1.914 albertel 905:
906: # --------------------------- ask offload servers if user already has a session
907: sub find_existing_session {
908: my ($udom,$uname) = @_;
1.1123 raeburn 909: my $spareshash = &this_host_spares($udom);
910: if (ref($spareshash) eq 'HASH') {
911: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
912: foreach my $try_server (@{ $spareshash->{'primary'} }) {
913: return $try_server if (&has_user_session($try_server, $udom, $uname));
914: }
915: }
916: if (ref($spareshash->{'default'}) eq 'ARRAY') {
917: foreach my $try_server (@{ $spareshash->{'default'} }) {
918: return $try_server if (&has_user_session($try_server, $udom, $uname));
919: }
920: }
1.914 albertel 921: }
922: return;
923: }
924:
925: # -------------------------------- ask if server already has a session for user
926: sub has_user_session {
927: my ($lonid,$udom,$uname) = @_;
928: my $result = &reply(join(':','userhassession',
929: map {&escape($_)} ($udom,$uname)),$lonid);
930: return 1 if ($result eq 'ok');
931:
932: return 0;
933: }
934:
1.1076 raeburn 935: # --------- determine least loaded server in a user's domain which allows login
936:
937: sub choose_server {
1.1115 raeburn 938: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 939: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 940: my %servers = &get_servers($udom);
1.1076 raeburn 941: my $lowest_load = 30000;
1.1151 raeburn 942: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 943: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 944: my $loginvia;
945: if ($checkloginvia) {
946: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 947: if ($loginvia) {
948: my ($server,$path) = split(/:/,$loginvia);
949: ($login_host, $lowest_load) =
950: &compare_server_load($server, $login_host, $lowest_load);
951: if ($login_host eq $server) {
952: $portal_path = $path;
1.1151 raeburn 953: $isredirect = 1;
1.1116 raeburn 954: }
955: } else {
956: ($login_host, $lowest_load) =
957: &compare_server_load($lonhost, $login_host, $lowest_load);
958: if ($login_host eq $lonhost) {
959: $portal_path = '';
1.1151 raeburn 960: $isredirect = '';
1.1116 raeburn 961: }
962: }
963: } else {
1.1076 raeburn 964: ($login_host, $lowest_load) =
1.1116 raeburn 965: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 966: }
967: }
968: if ($login_host ne '') {
1.1116 raeburn 969: $hostname = &hostname($login_host);
1.1076 raeburn 970: }
1.1151 raeburn 971: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 972: }
973:
1.202 matthew 974: # --------------------------------------------- Try to change a user's password
975:
976: sub changepass {
1.799 raeburn 977: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 978: $currentpass = &escape($currentpass);
979: $newpass = &escape($newpass);
1.1030 raeburn 980: my $lonhost = $perlvar{'lonHostID'};
981: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 982: $server);
983: if (! $answer) {
984: &logthis("No reply on password change request to $server ".
985: "by $uname in domain $udom.");
986: } elsif ($answer =~ "^ok") {
987: &logthis("$uname in $udom successfully changed their password ".
988: "on $server.");
989: } elsif ($answer =~ "^pwchange_failure") {
990: &logthis("$uname in $udom was unable to change their password ".
991: "on $server. The action was blocked by either lcpasswd ".
992: "or pwchange");
993: } elsif ($answer =~ "^non_authorized") {
994: &logthis("$uname in $udom did not get their password correct when ".
995: "attempting to change it on $server.");
996: } elsif ($answer =~ "^auth_mode_error") {
997: &logthis("$uname in $udom attempted to change their password despite ".
998: "not being locally or internally authenticated on $server.");
999: } elsif ($answer =~ "^unknown_user") {
1000: &logthis("$uname in $udom attempted to change their password ".
1001: "on $server but were unable to because $server is not ".
1002: "their home server.");
1003: } elsif ($answer =~ "^refused") {
1004: &logthis("$server refused to change $uname in $udom password because ".
1005: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1006: } elsif ($answer =~ "invalid_client") {
1007: &logthis("$server refused to change $uname in $udom password because ".
1008: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1009: }
1010: return $answer;
1.1 albertel 1011: }
1012:
1.169 harris41 1013: # ----------------------- Try to determine user's current authentication scheme
1014:
1015: sub queryauthenticate {
1016: my ($uname,$udom)=@_;
1.456 albertel 1017: my $uhome=&homeserver($uname,$udom);
1018: if (!$uhome) {
1019: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1020: return 'no_host';
1021: }
1022: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1023: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1024: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1025: }
1.456 albertel 1026: return $answer;
1.169 harris41 1027: }
1028:
1.1 albertel 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1030:
1.1 albertel 1031: sub authenticate {
1.1073 raeburn 1032: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1033: $upass=&escape($upass);
1034: $uname= &LONCAPA::clean_username($uname);
1.836 www 1035: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1036: my $newhome;
1.836 www 1037: if ((!$uhome) || ($uhome eq 'no_host')) {
1038: # Maybe the machine was offline and only re-appeared again recently?
1039: &reconlonc();
1040: # One more
1.952 raeburn 1041: $uhome=&homeserver($uname,$udom,1);
1042: if (($uhome eq 'no_host') && $checkdefauth) {
1043: if (defined(&domain($udom,'primary'))) {
1044: $newhome=&domain($udom,'primary');
1045: }
1046: if ($newhome ne '') {
1047: $uhome = $newhome;
1048: }
1049: }
1.836 www 1050: if ((!$uhome) || ($uhome eq 'no_host')) {
1051: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1052: return 'no_host';
1053: }
1.1 albertel 1054: }
1.1073 raeburn 1055: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1056: if ($answer eq 'authorized') {
1.952 raeburn 1057: if ($newhome) {
1058: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1059: return 'no_account_on_host';
1060: } else {
1061: &logthis("User $uname at $udom authorized by $uhome");
1062: return $uhome;
1063: }
1.471 albertel 1064: }
1065: if ($answer eq 'non_authorized') {
1066: &logthis("User $uname at $udom rejected by $uhome");
1067: return 'no_host';
1.9 www 1068: }
1.471 albertel 1069: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1070: return 'no_host';
1071: }
1072:
1.1073 raeburn 1073: sub can_host_session {
1.1074 raeburn 1074: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1075: my $canhost = 1;
1.1074 raeburn 1076: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1077: if (ref($remotesessions) eq 'HASH') {
1078: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1079: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1080: $canhost = 0;
1081: } else {
1082: $canhost = 1;
1083: }
1084: }
1085: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1086: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1087: $canhost = 1;
1088: } else {
1089: $canhost = 0;
1090: }
1091: }
1092: if ($canhost) {
1093: if ($remotesessions->{'version'} ne '') {
1094: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1095: if ($reqmajor ne '' && $reqminor ne '') {
1096: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1097: my $major = $1;
1098: my $minor = $2;
1099: if (($major < $reqmajor ) ||
1100: (($major == $reqmajor) && ($minor < $reqminor))) {
1101: $canhost = 0;
1102: }
1103: } else {
1104: $canhost = 0;
1105: }
1106: }
1107: }
1108: }
1109: }
1110: if ($canhost) {
1111: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1112: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1113: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1114: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1115: if (($uint_dom ne '') &&
1116: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1117: $canhost = 0;
1118: } else {
1119: $canhost = 1;
1120: }
1121: }
1122: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1123: if (($uint_dom ne '') &&
1124: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: }
1131: }
1132: return $canhost;
1133: }
1134:
1.1083 raeburn 1135: sub spare_can_host {
1136: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1137: my $canhost=1;
1138: my @intdoms;
1139: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1140: if (ref($internet_names) eq 'ARRAY') {
1141: @intdoms = @{$internet_names};
1142: }
1143: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1144: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1145: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1146: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1147: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1148: $canhost = &can_host_session($udom,$try_server,$remoterev,
1149: $remotesessions,
1150: $defdomdefaults{'hostedsessions'});
1151: }
1152: return $canhost;
1153: }
1154:
1.1123 raeburn 1155: sub this_host_spares {
1156: my ($dom) = @_;
1.1126 raeburn 1157: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1158: my @hosts = ¤t_machine_ids();
1159: foreach my $lonhost (@hosts) {
1160: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1161: $dom_in_use = $dom;
1162: $lonhost_in_use = $lonhost;
1.1123 raeburn 1163: last;
1164: }
1165: }
1.1126 raeburn 1166: if ($dom_in_use ne '') {
1167: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1168: }
1169: if (ref($result) ne 'HASH') {
1170: $lonhost_in_use = $perlvar{'lonHostID'};
1171: $dom_in_use = &host_domain($lonhost_in_use);
1172: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1173: if (ref($result) ne 'HASH') {
1174: $result = \%spareid;
1175: }
1176: }
1177: return $result;
1178: }
1179:
1180: sub spares_for_offload {
1181: my ($dom_in_use,$lonhost_in_use) = @_;
1182: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1183: if (defined($cached)) {
1184: return $result;
1185: } else {
1.1126 raeburn 1186: my $cachetime = 60*60*24;
1187: my %domconfig =
1188: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1189: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1190: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1191: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1192: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1193: }
1194: }
1195: }
1196: }
1.1126 raeburn 1197: return;
1.1123 raeburn 1198: }
1199:
1.1129 raeburn 1200: sub get_lonbalancer_config {
1201: my ($servers) = @_;
1202: my ($currbalancer,$currtargets);
1203: if (ref($servers) eq 'HASH') {
1204: foreach my $server (keys(%{$servers})) {
1205: my %what = (
1206: spareid => 1,
1207: perlvar => 1,
1208: );
1209: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1210: if ($result eq 'ok') {
1211: if (ref($returnhash) eq 'HASH') {
1212: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1213: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1214: $currbalancer = $server;
1215: $currtargets = {};
1216: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1217: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1218: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1219: }
1220: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1221: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1222: }
1223: }
1224: last;
1225: }
1226: }
1227: }
1228: }
1229: }
1230: }
1231: return ($currbalancer,$currtargets);
1232: }
1233:
1234: sub check_loadbalancing {
1235: my ($uname,$udom) = @_;
1236: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1237: $offloadto,$otherserver);
1238: my $lonhost = $perlvar{'lonHostID'};
1239: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1240: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1241: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1242: my $serverhomedom = &host_domain($lonhost);
1243:
1244: my $cachetime = 60*60*24;
1245:
1246: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1247: $dom_in_use = $udom;
1248: $homeintdom = 1;
1249: } else {
1250: $dom_in_use = $serverhomedom;
1251: }
1252: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1253: unless (defined($cached)) {
1254: my %domconfig =
1255: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1256: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1257: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1258: }
1259: }
1260: if (ref($result) eq 'HASH') {
1261: my $currbalancer = $result->{'lonhost'};
1262: my $currtargets = $result->{'targets'};
1263: my $currrules = $result->{'rules'};
1264: if ($currbalancer ne '') {
1265: my @hosts = ¤t_machine_ids();
1266: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1267: $is_balancer = 1;
1268: }
1269: }
1270: if ($is_balancer) {
1271: if (ref($currrules) eq 'HASH') {
1272: if ($homeintdom) {
1273: if ($uname ne '') {
1274: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1275: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1276: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1277: $rule_in_effect = $currrules->{'_LC_author'};
1278: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1279: $rule_in_effect = $currrules->{'_LC_adv'}
1280: }
1281: }
1282: if ($rule_in_effect eq '') {
1283: my %userenv = &userenvironment($udom,$uname,'inststatus');
1284: if ($userenv{'inststatus'} ne '') {
1285: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1286: my ($othertitle,$usertypes,$types) =
1287: &Apache::loncommon::sorted_inst_types($udom);
1288: if (ref($types) eq 'ARRAY') {
1289: foreach my $type (@{$types}) {
1290: if (grep(/^\Q$type\E$/,@statuses)) {
1291: if (exists($currrules->{$type})) {
1292: $rule_in_effect = $currrules->{$type};
1293: }
1294: }
1295: }
1296: }
1297: } else {
1298: if (exists($currrules->{'default'})) {
1299: $rule_in_effect = $currrules->{'default'};
1300: }
1301: }
1302: }
1303: } else {
1304: if (exists($currrules->{'default'})) {
1305: $rule_in_effect = $currrules->{'default'};
1306: }
1307: }
1308: } else {
1309: if ($currrules->{'_LC_external'} ne '') {
1310: $rule_in_effect = $currrules->{'_LC_external'};
1311: }
1312: }
1313: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1314: $uname,$udom);
1315: }
1316: }
1317: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1318: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1319: unless (defined($cached)) {
1320: my %domconfig =
1321: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1322: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1323: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1324: }
1325: }
1326: if (ref($result) eq 'HASH') {
1327: my $currbalancer = $result->{'lonhost'};
1328: my $currtargets = $result->{'targets'};
1329: my $currrules = $result->{'rules'};
1330:
1331: if ($currbalancer eq $lonhost) {
1332: $is_balancer = 1;
1333: if (ref($currrules) eq 'HASH') {
1334: if ($currrules->{'_LC_internetdom'} ne '') {
1335: $rule_in_effect = $currrules->{'_LC_internetdom'};
1336: }
1337: }
1338: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1339: $uname,$udom);
1340: }
1341: } else {
1342: if ($perlvar{'lonBalancer'} eq 'yes') {
1343: $is_balancer = 1;
1344: $offloadto = &this_host_spares($dom_in_use);
1345: }
1346: }
1347: } else {
1348: if ($perlvar{'lonBalancer'} eq 'yes') {
1349: $is_balancer = 1;
1350: $offloadto = &this_host_spares($dom_in_use);
1351: }
1352: }
1353: my $lowest_load = 30000;
1354: if (ref($offloadto) eq 'HASH') {
1355: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1356: foreach my $try_server (@{$offloadto->{'primary'}}) {
1357: ($otherserver,$lowest_load) =
1358: &compare_server_load($try_server,$otherserver,$lowest_load);
1359: }
1360: }
1361: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1362:
1363: if (!$found_server) {
1364: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1365: foreach my $try_server (@{$offloadto->{'default'}}) {
1366: ($otherserver,$lowest_load) =
1367: &compare_server_load($try_server,$otherserver,$lowest_load);
1368: }
1369: }
1370: }
1371: } elsif (ref($offloadto) eq 'ARRAY') {
1372: if (@{$offloadto} == 1) {
1373: $otherserver = $offloadto->[0];
1374: } elsif (@{$offloadto} > 1) {
1375: foreach my $try_server (@{$offloadto}) {
1376: ($otherserver,$lowest_load) =
1377: &compare_server_load($try_server,$otherserver,$lowest_load);
1378: }
1379: }
1380: }
1381: return ($is_balancer,$otherserver);
1382: }
1383:
1384: sub get_loadbalancer_targets {
1385: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1386: my $offloadto;
1387: if ($rule_in_effect eq '') {
1388: $offloadto = $currtargets;
1389: } else {
1390: if ($rule_in_effect eq 'homeserver') {
1391: my $homeserver = &homeserver($uname,$udom);
1392: if ($homeserver ne 'no_host') {
1393: $offloadto = [$homeserver];
1394: }
1395: } elsif ($rule_in_effect eq 'externalbalancer') {
1396: my %domconfig =
1397: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1398: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1399: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1400: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1401: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1402: }
1403: }
1404: } else {
1405: my %servers = &dom_servers($udom);
1406: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1407: if (&hostname($remotebalancer) ne '') {
1408: $offloadto = [$remotebalancer];
1409: }
1410: }
1411: } elsif (&hostname($rule_in_effect) ne '') {
1412: $offloadto = [$rule_in_effect];
1413: }
1414: }
1415: return $offloadto;
1416: }
1417:
1.1127 raeburn 1418: sub internet_dom_servers {
1419: my ($dom) = @_;
1420: my (%uniqservers,%servers);
1421: my $primaryserver = &hostname(&domain($dom,'primary'));
1422: my @machinedoms = &machine_domains($primaryserver);
1423: foreach my $mdom (@machinedoms) {
1424: my %currservers = %servers;
1425: my %server = &get_servers($mdom);
1426: %servers = (%currservers,%server);
1427: }
1428: my %by_hostname;
1429: foreach my $id (keys(%servers)) {
1430: push(@{$by_hostname{$servers{$id}}},$id);
1431: }
1432: foreach my $hostname (sort(keys(%by_hostname))) {
1433: if (@{$by_hostname{$hostname}} > 1) {
1434: my $match = 0;
1435: foreach my $id (@{$by_hostname{$hostname}}) {
1436: if (&host_domain($id) eq $dom) {
1437: $uniqservers{$id} = $hostname;
1438: $match = 1;
1439: }
1440: }
1441: unless ($match) {
1442: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1443: }
1444: } else {
1445: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1446: }
1447: }
1448: return %uniqservers;
1449: }
1450:
1.1 albertel 1451: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1452:
1.599 albertel 1453: my %homecache;
1.1 albertel 1454: sub homeserver {
1.230 stredwic 1455: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1456: my $index="$uname:$udom";
1.426 albertel 1457:
1.599 albertel 1458: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1459:
1460: my %servers = &get_servers($udom,'library');
1461: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1462: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1463: exists($badServerCache{$tryserver}));
1.841 albertel 1464:
1465: my $answer=reply("home:$udom:$uname",$tryserver);
1466: if ($answer eq 'found') {
1467: delete($badServerCache{$tryserver});
1468: return $homecache{$index}=$tryserver;
1469: } elsif ($answer eq 'no_host') {
1470: $badServerCache{$tryserver}=1;
1471: }
1.1 albertel 1472: }
1473: return 'no_host';
1.70 www 1474: }
1475:
1476: # ------------------------------------- Find the usernames behind a list of IDs
1477:
1478: sub idget {
1479: my ($udom,@ids)=@_;
1480: my %returnhash=();
1481:
1.841 albertel 1482: my %servers = &get_servers($udom,'library');
1483: foreach my $tryserver (keys(%servers)) {
1484: my $idlist=join('&',@ids);
1485: $idlist=~tr/A-Z/a-z/;
1486: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1487: my @answer=();
1488: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1489: @answer=split(/\&/,$reply);
1490: } ;
1491: my $i;
1492: for ($i=0;$i<=$#ids;$i++) {
1493: if ($answer[$i]) {
1494: $returnhash{$ids[$i]}=$answer[$i];
1495: }
1496: }
1497: }
1.70 www 1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------------- Find the IDs behind a list of usernames
1502:
1503: sub idrget {
1504: my ($udom,@unames)=@_;
1505: my %returnhash=();
1.800 albertel 1506: foreach my $uname (@unames) {
1507: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1508: }
1.70 www 1509: return %returnhash;
1510: }
1511:
1512: # ------------------------------- Store away a list of names and associated IDs
1513:
1514: sub idput {
1515: my ($udom,%ids)=@_;
1516: my %servers=();
1.800 albertel 1517: foreach my $uname (keys(%ids)) {
1518: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1519: my $uhom=&homeserver($uname,$udom);
1.70 www 1520: if ($uhom ne 'no_host') {
1.800 albertel 1521: my $id=&escape($ids{$uname});
1.70 www 1522: $id=~tr/A-Z/a-z/;
1.800 albertel 1523: my $esc_unam=&escape($uname);
1.70 www 1524: if ($servers{$uhom}) {
1.800 albertel 1525: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1526: } else {
1.800 albertel 1527: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1528: }
1529: }
1.191 harris41 1530: }
1.800 albertel 1531: foreach my $server (keys(%servers)) {
1532: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1533: }
1.344 www 1534: }
1535:
1.1023 raeburn 1536: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1537: sub dump_dom {
1.1165 droeschl 1538: my ($namespace, $udom, $regexp) = @_;
1539:
1540: $udom ||= $env{'user.domain'};
1541:
1542: return () unless $udom;
1543:
1544: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1545: }
1546:
1.1023 raeburn 1547: # ------------------------------------------ get items from domain db files
1.806 raeburn 1548:
1549: sub get_dom {
1.860 raeburn 1550: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1551: my $items='';
1552: foreach my $item (@$storearr) {
1553: $items.=&escape($item).'&';
1554: }
1555: $items=~s/\&$//;
1.860 raeburn 1556: if (!$udom) {
1557: $udom=$env{'user.domain'};
1558: if (defined(&domain($udom,'primary'))) {
1559: $uhome=&domain($udom,'primary');
1560: } else {
1.874 albertel 1561: undef($uhome);
1.860 raeburn 1562: }
1563: } else {
1564: if (!$uhome) {
1565: if (defined(&domain($udom,'primary'))) {
1566: $uhome=&domain($udom,'primary');
1567: }
1568: }
1569: }
1570: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1571: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1572: my %returnhash;
1.875 albertel 1573: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1574: return %returnhash;
1575: }
1.806 raeburn 1576: my @pairs=split(/\&/,$rep);
1577: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1578: return @pairs;
1579: }
1580: my $i=0;
1581: foreach my $item (@$storearr) {
1582: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1583: $i++;
1584: }
1585: return %returnhash;
1586: } else {
1.880 banghart 1587: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1588: }
1589: }
1590:
1591: # -------------------------------------------- put items in domain db files
1592:
1593: sub put_dom {
1.860 raeburn 1594: my ($namespace,$storehash,$udom,$uhome)=@_;
1595: if (!$udom) {
1596: $udom=$env{'user.domain'};
1597: if (defined(&domain($udom,'primary'))) {
1598: $uhome=&domain($udom,'primary');
1599: } else {
1.874 albertel 1600: undef($uhome);
1.860 raeburn 1601: }
1602: } else {
1603: if (!$uhome) {
1604: if (defined(&domain($udom,'primary'))) {
1605: $uhome=&domain($udom,'primary');
1606: }
1607: }
1608: }
1609: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1610: my $items='';
1611: foreach my $item (keys(%$storehash)) {
1612: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1613: }
1614: $items=~s/\&$//;
1615: return &reply("putdom:$udom:$namespace:$items",$uhome);
1616: } else {
1.860 raeburn 1617: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1618: }
1619: }
1620:
1.1023 raeburn 1621: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1622: sub newput_dom {
1.1023 raeburn 1623: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1624: my $result;
1625: if (!$udom) {
1626: $udom=$env{'user.domain'};
1627: }
1.1023 raeburn 1628: if ($udom) {
1629: my $uname = &get_domainconfiguser($udom);
1630: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1631: }
1632: return $result;
1633: }
1634:
1.1023 raeburn 1635: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1636: sub del_dom {
1.1023 raeburn 1637: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1638: if (ref($storearr) eq 'ARRAY') {
1639: if (!$udom) {
1640: $udom=$env{'user.domain'};
1641: }
1.1023 raeburn 1642: if ($udom) {
1643: my $uname = &get_domainconfiguser($udom);
1644: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1645: }
1646: }
1647: }
1648:
1.1023 raeburn 1649: # ----------------------------------construct domainconfig user for a domain
1650: sub get_domainconfiguser {
1651: my ($udom) = @_;
1652: return $udom.'-domainconfig';
1653: }
1654:
1.837 raeburn 1655: sub retrieve_inst_usertypes {
1656: my ($udom) = @_;
1657: my (%returnhash,@order);
1.989 raeburn 1658: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1659: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1660: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1661: %returnhash = %{$domdefs{'inststatustypes'}};
1662: @order = @{$domdefs{'inststatusorder'}};
1663: } else {
1664: if (defined(&domain($udom,'primary'))) {
1665: my $uhome=&domain($udom,'primary');
1666: my $rep=&reply("inst_usertypes:$udom",$uhome);
1667: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1668: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1669: return (\%returnhash,\@order);
1670: }
1671: my ($hashitems,$orderitems) = split(/:/,$rep);
1672: my @pairs=split(/\&/,$hashitems);
1673: foreach my $item (@pairs) {
1674: my ($key,$value)=split(/=/,$item,2);
1675: $key = &unescape($key);
1676: next if ($key =~ /^error: 2 /);
1677: $returnhash{$key}=&thaw_unescape($value);
1678: }
1679: my @esc_order = split(/\&/,$orderitems);
1680: foreach my $item (@esc_order) {
1681: push(@order,&unescape($item));
1682: }
1683: } else {
1684: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1685: }
1686: }
1687: return (\%returnhash,\@order);
1688: }
1689:
1.868 raeburn 1690: sub is_domainimage {
1691: my ($url) = @_;
1692: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1693: if (&domain($1) ne '') {
1694: return '1';
1695: }
1696: }
1697: return;
1698: }
1699:
1.899 raeburn 1700: sub inst_directory_query {
1701: my ($srch) = @_;
1702: my $udom = $srch->{'srchdomain'};
1703: my %results;
1704: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1705: my $outcome;
1.899 raeburn 1706: if ($homeserver ne '') {
1.904 albertel 1707: my $queryid=&reply("querysend:instdirsearch:".
1708: &escape($srch->{'srchby'}).':'.
1709: &escape($srch->{'srchterm'}).':'.
1710: &escape($srch->{'srchtype'}),$homeserver);
1711: my $host=&hostname($homeserver);
1712: if ($queryid !~/^\Q$host\E\_/) {
1713: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1714: return;
1715: }
1716: my $response = &get_query_reply($queryid);
1717: my $maxtries = 5;
1718: my $tries = 1;
1719: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1720: $response = &get_query_reply($queryid);
1721: $tries ++;
1722: }
1723:
1724: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1725: if ($response eq 'unavailable') {
1726: $outcome = $response;
1727: } else {
1728: $outcome = 'ok';
1729: my @matches = split(/\n/,$response);
1730: foreach my $match (@matches) {
1731: my ($key,$value) = split(/=/,$match);
1732: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1733: }
1.899 raeburn 1734: }
1735: }
1736: }
1.909 raeburn 1737: return ($outcome,%results);
1.899 raeburn 1738: }
1739:
1740: sub usersearch {
1741: my ($srch) = @_;
1742: my $dom = $srch->{'srchdomain'};
1743: my %results;
1744: my %libserv = &all_library();
1745: my $query = 'usersearch';
1746: foreach my $tryserver (keys(%libserv)) {
1747: if (&host_domain($tryserver) eq $dom) {
1748: my $host=&hostname($tryserver);
1749: my $queryid=
1.911 raeburn 1750: &reply("querysend:".&escape($query).':'.
1751: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1752: &escape($srch->{'srchtype'}).':'.
1753: &escape($srch->{'srchterm'}),$tryserver);
1754: if ($queryid !~/^\Q$host\E\_/) {
1755: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1756: next;
1.899 raeburn 1757: }
1758: my $reply = &get_query_reply($queryid);
1759: my $maxtries = 1;
1760: my $tries = 1;
1761: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1762: $reply = &get_query_reply($queryid);
1763: $tries ++;
1764: }
1765: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1766: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1767: } else {
1.911 raeburn 1768: my @matches;
1769: if ($reply =~ /\n/) {
1770: @matches = split(/\n/,$reply);
1771: } else {
1772: @matches = split(/\&/,$reply);
1773: }
1.899 raeburn 1774: foreach my $match (@matches) {
1775: my ($uname,$udom,%userhash);
1.911 raeburn 1776: foreach my $entry (split(/:/,$match)) {
1777: my ($key,$value) =
1778: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1779: $userhash{$key} = $value;
1780: if ($key eq 'username') {
1781: $uname = $value;
1782: } elsif ($key eq 'domain') {
1783: $udom = $value;
1.911 raeburn 1784: }
1.899 raeburn 1785: }
1786: $results{$uname.':'.$udom} = \%userhash;
1787: }
1788: }
1789: }
1790: }
1791: return %results;
1792: }
1793:
1.912 raeburn 1794: sub get_instuser {
1795: my ($udom,$uname,$id) = @_;
1796: my $homeserver = &domain($udom,'primary');
1797: my ($outcome,%results);
1798: if ($homeserver ne '') {
1799: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1800: &escape($id).':'.&escape($udom),$homeserver);
1801: my $host=&hostname($homeserver);
1802: if ($queryid !~/^\Q$host\E\_/) {
1803: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1804: return;
1805: }
1806: my $response = &get_query_reply($queryid);
1807: my $maxtries = 5;
1808: my $tries = 1;
1809: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1810: $response = &get_query_reply($queryid);
1811: $tries ++;
1812: }
1813: if (!&error($response) && $response ne 'refused') {
1814: if ($response eq 'unavailable') {
1815: $outcome = $response;
1816: } else {
1817: $outcome = 'ok';
1818: my @matches = split(/\n/,$response);
1819: foreach my $match (@matches) {
1820: my ($key,$value) = split(/=/,$match);
1821: $results{&unescape($key)} = &thaw_unescape($value);
1822: }
1823: }
1824: }
1825: }
1826: my %userinfo;
1827: if (ref($results{$uname}) eq 'HASH') {
1828: %userinfo = %{$results{$uname}};
1829: }
1830: return ($outcome,%userinfo);
1831: }
1832:
1833: sub inst_rulecheck {
1.923 raeburn 1834: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1835: my %returnhash;
1836: if ($udom ne '') {
1837: if (ref($rules) eq 'ARRAY') {
1838: @{$rules} = map {&escape($_);} (@{$rules});
1839: my $rulestr = join(':',@{$rules});
1840: my $homeserver=&domain($udom,'primary');
1841: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1842: my $response;
1843: if ($item eq 'username') {
1844: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1845: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1846: $homeserver));
1.923 raeburn 1847: } elsif ($item eq 'id') {
1848: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1849: ':'.&escape($id).':'.$rulestr,
1850: $homeserver));
1.945 raeburn 1851: } elsif ($item eq 'selfcreate') {
1852: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1853: &escape($udom).':'.&escape($uname).
1854: ':'.$rulestr,$homeserver));
1.923 raeburn 1855: }
1.912 raeburn 1856: if ($response ne 'refused') {
1857: my @pairs=split(/\&/,$response);
1858: foreach my $item (@pairs) {
1859: my ($key,$value)=split(/=/,$item,2);
1860: $key = &unescape($key);
1861: next if ($key =~ /^error: 2 /);
1862: $returnhash{$key}=&thaw_unescape($value);
1863: }
1864: }
1865: }
1866: }
1867: }
1868: return %returnhash;
1869: }
1870:
1871: sub inst_userrules {
1.923 raeburn 1872: my ($udom,$check) = @_;
1.912 raeburn 1873: my (%ruleshash,@ruleorder);
1874: if ($udom ne '') {
1875: my $homeserver=&domain($udom,'primary');
1876: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1877: my $response;
1878: if ($check eq 'id') {
1879: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1880: $homeserver);
1.943 raeburn 1881: } elsif ($check eq 'email') {
1882: $response=&reply('instemailrules:'.&escape($udom),
1883: $homeserver);
1.923 raeburn 1884: } else {
1885: $response=&reply('instuserrules:'.&escape($udom),
1886: $homeserver);
1887: }
1.912 raeburn 1888: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1889: ($response ne 'unknown_cmd') &&
1.912 raeburn 1890: ($response ne 'no_such_host')) {
1891: my ($hashitems,$orderitems) = split(/:/,$response);
1892: my @pairs=split(/\&/,$hashitems);
1893: foreach my $item (@pairs) {
1894: my ($key,$value)=split(/=/,$item,2);
1895: $key = &unescape($key);
1896: next if ($key =~ /^error: 2 /);
1897: $ruleshash{$key}=&thaw_unescape($value);
1898: }
1899: my @esc_order = split(/\&/,$orderitems);
1900: foreach my $item (@esc_order) {
1901: push(@ruleorder,&unescape($item));
1902: }
1903: }
1904: }
1905: }
1906: return (\%ruleshash,\@ruleorder);
1907: }
1908:
1.976 raeburn 1909: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1910:
1911: sub get_domain_defaults {
1912: my ($domain) = @_;
1913: my $cachetime = 60*60*24;
1914: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1915: if (defined($cached)) {
1916: if (ref($result) eq 'HASH') {
1917: return %{$result};
1918: }
1919: }
1920: my %domdefaults;
1921: my %domconfig =
1.989 raeburn 1922: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1923: 'requestcourses','inststatus',
1.1073 raeburn 1924: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1925: if (ref($domconfig{'defaults'}) eq 'HASH') {
1926: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1927: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1928: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1929: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1930: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1931: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1932: } else {
1933: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1934: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1935: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1936: }
1.976 raeburn 1937: if (ref($domconfig{'quotas'}) eq 'HASH') {
1938: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1939: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1940: } else {
1941: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1942: }
1943: my @usertools = ('aboutme','blog','portfolio');
1944: foreach my $item (@usertools) {
1945: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1946: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1947: }
1948: }
1949: }
1.985 raeburn 1950: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1951: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1952: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1953: }
1954: }
1.989 raeburn 1955: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1956: foreach my $item ('inststatustypes','inststatusorder') {
1957: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1958: }
1959: }
1.1047 raeburn 1960: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1961: foreach my $item ('canuse_pdfforms') {
1962: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1963: }
1964: }
1.1073 raeburn 1965: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1966: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1967: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1968: }
1969: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1970: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1971: }
1972: }
1.943 raeburn 1973: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1974: $cachetime);
1975: return %domdefaults;
1976: }
1977:
1.344 www 1978: # --------------------------------------------------- Assign a key to a student
1979:
1980: sub assign_access_key {
1.364 www 1981: #
1982: # a valid key looks like uname:udom#comments
1983: # comments are being appended
1984: #
1.498 www 1985: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1986: $kdom=
1.620 albertel 1987: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1988: $knum=
1.620 albertel 1989: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1990: $cdom=
1.620 albertel 1991: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1992: $cnum=
1.620 albertel 1993: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1994: $udom=$env{'user.name'} unless (defined($udom));
1995: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1996: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1997: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1998: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1999: # assigned to this person
2000: # - this should not happen,
1.345 www 2001: # unless something went wrong
2002: # the first time around
2003: # ready to assign
1.364 www 2004: $logentry=$1.'; '.$logentry;
1.496 www 2005: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2006: $kdom,$knum) eq 'ok') {
1.345 www 2007: # key now belongs to user
1.346 www 2008: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2009: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2010: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2011: return 'ok';
2012: } else {
2013: return
2014: 'error: Count not permanently assign key, will need to be re-entered later.';
2015: }
2016: } else {
2017: return 'error: Could not assign key, try again later.';
2018: }
1.364 www 2019: } elsif (!$existing{$ckey}) {
1.345 www 2020: # the key does not exist
2021: return 'error: The key does not exist';
2022: } else {
2023: # the key is somebody else's
2024: return 'error: The key is already in use';
2025: }
1.344 www 2026: }
2027:
1.364 www 2028: # ------------------------------------------ put an additional comment on a key
2029:
2030: sub comment_access_key {
2031: #
2032: # a valid key looks like uname:udom#comments
2033: # comments are being appended
2034: #
2035: my ($ckey,$cdom,$cnum,$logentry)=@_;
2036: $cdom=
1.620 albertel 2037: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2038: $cnum=
1.620 albertel 2039: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2040: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2041: if ($existing{$ckey}) {
2042: $existing{$ckey}.='; '.$logentry;
2043: # ready to assign
1.367 www 2044: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2045: $cdom,$cnum) eq 'ok') {
2046: return 'ok';
2047: } else {
2048: return 'error: Count not store comment.';
2049: }
2050: } else {
2051: # the key does not exist
2052: return 'error: The key does not exist';
2053: }
2054: }
2055:
1.344 www 2056: # ------------------------------------------------------ Generate a set of keys
2057:
2058: sub generate_access_keys {
1.364 www 2059: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2060: $cdom=
1.620 albertel 2061: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2062: $cnum=
1.620 albertel 2063: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2064: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2065: unless (($cdom) && ($cnum)) { return 0; }
2066: if ($number>10000) { return 0; }
2067: sleep(2); # make sure don't get same seed twice
2068: srand(time()^($$+($$<<15))); # from "Programming Perl"
2069: my $total=0;
2070: for (my $i=1;$i<=$number;$i++) {
2071: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2072: sprintf("%lx",int(100000*rand)).'-'.
2073: sprintf("%lx",int(100000*rand));
2074: $newkey=~s/1/g/g; # folks mix up 1 and l
2075: $newkey=~s/0/h/g; # and also 0 and O
2076: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2077: if ($existing{$newkey}) {
2078: $i--;
2079: } else {
1.364 www 2080: if (&put('accesskeys',
2081: { $newkey => '# generated '.localtime().
1.620 albertel 2082: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2083: '; '.$logentry },
2084: $cdom,$cnum) eq 'ok') {
1.344 www 2085: $total++;
2086: }
2087: }
2088: }
1.620 albertel 2089: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2090: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2091: return $total;
2092: }
2093:
2094: # ------------------------------------------------------- Validate an accesskey
2095:
2096: sub validate_access_key {
2097: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2098: $cdom=
1.620 albertel 2099: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2100: $cnum=
1.620 albertel 2101: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2102: $udom=$env{'user.domain'} unless (defined($udom));
2103: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2104: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2105: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2106: }
2107:
2108: # ------------------------------------- Find the section of student in a course
1.652 albertel 2109: sub devalidate_getsection_cache {
2110: my ($udom,$unam,$courseid)=@_;
2111: my $hashid="$udom:$unam:$courseid";
2112: &devalidate_cache_new('getsection',$hashid);
2113: }
1.298 matthew 2114:
1.815 albertel 2115: sub courseid_to_courseurl {
2116: my ($courseid) = @_;
2117: #already url style courseid
2118: return $courseid if ($courseid =~ m{^/});
2119:
2120: if (exists($env{'course.'.$courseid.'.num'})) {
2121: my $cnum = $env{'course.'.$courseid.'.num'};
2122: my $cdom = $env{'course.'.$courseid.'.domain'};
2123: return "/$cdom/$cnum";
2124: }
2125:
2126: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2127: if (exists($courseinfo{'num'})) {
2128: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2129: }
2130:
2131: return undef;
2132: }
2133:
1.298 matthew 2134: sub getsection {
2135: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2136: my $cachetime=1800;
1.551 albertel 2137:
2138: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2139: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2140: if (defined($cached)) { return $result; }
2141:
1.298 matthew 2142: my %Pending;
2143: my %Expired;
2144: #
2145: # Each role can either have not started yet (pending), be active,
2146: # or have expired.
2147: #
2148: # If there is an active role, we are done.
2149: #
2150: # If there is more than one role which has not started yet,
2151: # choose the one which will start sooner
2152: # If there is one role which has not started yet, return it.
2153: #
2154: # If there is more than one expired role, choose the one which ended last.
2155: # If there is a role which has expired, return it.
2156: #
1.815 albertel 2157: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2158: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2159: foreach my $key (keys(%roleshash)) {
1.479 albertel 2160: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2161: my $section=$1;
2162: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2163: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2164: my $now=time;
1.548 albertel 2165: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2166: $Expired{$end}=$section;
2167: next;
2168: }
1.548 albertel 2169: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2170: $Pending{$start}=$section;
2171: next;
2172: }
1.599 albertel 2173: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2174: }
2175: #
2176: # Presumedly there will be few matching roles from the above
2177: # loop and the sorting time will be negligible.
2178: if (scalar(keys(%Pending))) {
2179: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2180: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2181: }
2182: if (scalar(keys(%Expired))) {
2183: my @sorted = sort {$a <=> $b} keys(%Expired);
2184: my $time = pop(@sorted);
1.599 albertel 2185: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2186: }
1.599 albertel 2187: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2188: }
1.70 www 2189:
1.599 albertel 2190: sub save_cache {
2191: &purge_remembered();
1.722 albertel 2192: #&Apache::loncommon::validate_page();
1.620 albertel 2193: undef(%env);
1.780 albertel 2194: undef($env_loaded);
1.599 albertel 2195: }
1.452 albertel 2196:
1.599 albertel 2197: my $to_remember=-1;
2198: my %remembered;
2199: my %accessed;
2200: my $kicks=0;
2201: my $hits=0;
1.849 albertel 2202: sub make_key {
2203: my ($name,$id) = @_;
1.872 albertel 2204: if (length($id) > 65
2205: && length(&escape($id)) > 200) {
2206: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2207: }
1.849 albertel 2208: return &escape($name.':'.$id);
2209: }
2210:
1.599 albertel 2211: sub devalidate_cache_new {
2212: my ($name,$id,$debug) = @_;
2213: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2214: $id=&make_key($name,$id);
1.599 albertel 2215: $memcache->delete($id);
2216: delete($remembered{$id});
2217: delete($accessed{$id});
2218: }
2219:
2220: sub is_cached_new {
2221: my ($name,$id,$debug) = @_;
1.849 albertel 2222: $id=&make_key($name,$id);
1.599 albertel 2223: if (exists($remembered{$id})) {
1.1133 foxr 2224: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2225: $accessed{$id}=[&gettimeofday()];
2226: $hits++;
2227: return ($remembered{$id},1);
2228: }
2229: my $value = $memcache->get($id);
2230: if (!(defined($value))) {
2231: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2232: return (undef,undef);
1.416 albertel 2233: }
1.599 albertel 2234: if ($value eq '__undef__') {
2235: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2236: $value=undef;
2237: }
2238: &make_room($id,$value,$debug);
2239: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2240: return ($value,1);
2241: }
2242:
2243: sub do_cache_new {
2244: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2245: $id=&make_key($name,$id);
1.599 albertel 2246: my $setvalue=$value;
2247: if (!defined($setvalue)) {
2248: $setvalue='__undef__';
2249: }
1.623 albertel 2250: if (!defined($time) ) {
2251: $time=600;
2252: }
1.599 albertel 2253: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2254: my $result = $memcache->set($id,$setvalue,$time);
2255: if (! $result) {
1.872 albertel 2256: &logthis("caching of id -> $id failed");
1.910 albertel 2257: $memcache->disconnect_all();
1.872 albertel 2258: }
1.600 albertel 2259: # need to make a copy of $value
1.919 albertel 2260: &make_room($id,$value,$debug);
1.599 albertel 2261: return $value;
2262: }
2263:
2264: sub make_room {
2265: my ($id,$value,$debug)=@_;
1.919 albertel 2266:
2267: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2268: : $value;
1.599 albertel 2269: if ($to_remember<0) { return; }
2270: $accessed{$id}=[&gettimeofday()];
2271: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2272: my $to_kick;
2273: my $max_time=0;
2274: foreach my $other (keys(%accessed)) {
2275: if (&tv_interval($accessed{$other}) > $max_time) {
2276: $to_kick=$other;
2277: $max_time=&tv_interval($accessed{$other});
2278: }
2279: }
2280: delete($remembered{$to_kick});
2281: delete($accessed{$to_kick});
2282: $kicks++;
2283: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2284: return;
2285: }
2286:
1.599 albertel 2287: sub purge_remembered {
1.604 albertel 2288: #&logthis("Tossing ".scalar(keys(%remembered)));
2289: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2290: undef(%remembered);
2291: undef(%accessed);
1.428 albertel 2292: }
1.70 www 2293: # ------------------------------------- Read an entry from a user's environment
2294:
2295: sub userenvironment {
2296: my ($udom,$unam,@what)=@_;
1.976 raeburn 2297: my $items;
2298: foreach my $item (@what) {
2299: $items.=&escape($item).'&';
2300: }
2301: $items=~s/\&$//;
1.70 www 2302: my %returnhash=();
1.1009 raeburn 2303: my $uhome = &homeserver($unam,$udom);
2304: unless ($uhome eq 'no_host') {
2305: my @answer=split(/\&/,
2306: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2307: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2308: return %returnhash;
2309: }
1.1009 raeburn 2310: my $i;
2311: for ($i=0;$i<=$#what;$i++) {
2312: $returnhash{$what[$i]}=&unescape($answer[$i]);
2313: }
1.70 www 2314: }
2315: return %returnhash;
1.1 albertel 2316: }
2317:
1.617 albertel 2318: # ---------------------------------------------------------- Get a studentphoto
2319: sub studentphoto {
2320: my ($udom,$unam,$ext) = @_;
2321: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2322: if (defined($env{'request.course.id'})) {
1.708 raeburn 2323: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2324: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2325: return(&retrievestudentphoto($udom,$unam,$ext));
2326: } else {
2327: my ($result,$perm_reqd)=
1.707 albertel 2328: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2329: if ($result eq 'ok') {
2330: if (!($perm_reqd eq 'yes')) {
2331: return(&retrievestudentphoto($udom,$unam,$ext));
2332: }
2333: }
2334: }
2335: }
2336: } else {
2337: my ($result,$perm_reqd) =
1.707 albertel 2338: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2339: if ($result eq 'ok') {
2340: if (!($perm_reqd eq 'yes')) {
2341: return(&retrievestudentphoto($udom,$unam,$ext));
2342: }
2343: }
2344: }
2345: return '/adm/lonKaputt/lonlogo_broken.gif';
2346: }
2347:
2348: sub retrievestudentphoto {
2349: my ($udom,$unam,$ext,$type) = @_;
2350: my $home=&Apache::lonnet::homeserver($unam,$udom);
2351: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2352: if ($ret eq 'ok') {
2353: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2354: if ($type eq 'thumbnail') {
2355: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2356: }
2357: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2358: return $tokenurl;
2359: } else {
2360: if ($type eq 'thumbnail') {
2361: return '/adm/lonKaputt/genericstudent_tn.gif';
2362: } else {
2363: return '/adm/lonKaputt/lonlogo_broken.gif';
2364: }
1.617 albertel 2365: }
2366: }
2367:
1.263 www 2368: # -------------------------------------------------------------------- New chat
2369:
2370: sub chatsend {
1.724 raeburn 2371: my ($newentry,$anon,$group)=@_;
1.620 albertel 2372: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2373: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2374: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2375: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2376: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2377: &escape($newentry)).':'.$group,$chome);
1.292 www 2378: }
2379:
2380: # ------------------------------------------ Find current version of a resource
2381:
2382: sub getversion {
2383: my $fname=&clutter(shift);
2384: unless ($fname=~/^\/res\//) { return -1; }
2385: return ¤tversion(&filelocation('',$fname));
2386: }
2387:
2388: sub currentversion {
2389: my $fname=shift;
2390: my $author=$fname;
2391: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2392: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2393: my $home=&homeserver($uname,$udom);
1.292 www 2394: if ($home eq 'no_host') {
2395: return -1;
2396: }
1.1112 www 2397: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2398: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2399: return -1;
2400: }
1.1112 www 2401: return $answer;
1.263 www 2402: }
2403:
1.1111 www 2404: #
2405: # Return special version number of resource if set by override, empty otherwise
2406: #
2407: sub usedversion {
2408: my $fname=shift;
2409: unless ($fname) { $fname=$env{'request.uri'}; }
2410: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2411: if ($urlversion) { return $urlversion; }
2412: return '';
2413: }
2414:
1.1 albertel 2415: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2416:
1.1 albertel 2417: sub subscribe {
2418: my $fname=shift;
1.761 raeburn 2419: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2420: $fname=~s/[\n\r]//g;
1.1 albertel 2421: my $author=$fname;
2422: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2423: my ($udom,$uname)=split(/\//,$author);
2424: my $home=homeserver($uname,$udom);
1.335 albertel 2425: if ($home eq 'no_host') {
2426: return 'not_found';
1.1 albertel 2427: }
2428: my $answer=reply("sub:$fname",$home);
1.64 www 2429: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2430: $answer.=' by '.$home;
2431: }
1.1 albertel 2432: return $answer;
2433: }
2434:
1.8 www 2435: # -------------------------------------------------------------- Replicate file
2436:
2437: sub repcopy {
2438: my $filename=shift;
1.23 www 2439: $filename=~s/\/+/\//g;
1.1142 raeburn 2440: my $londocroot = $perlvar{'lonDocRoot'};
2441: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2442: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2443: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2444: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2445: return &repcopy_userfile($filename);
2446: }
1.532 albertel 2447: $filename=~s/[\n\r]//g;
1.8 www 2448: my $transname="$filename.in.transfer";
1.828 www 2449: # FIXME: this should flock
1.607 raeburn 2450: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2451: my $remoteurl=subscribe($filename);
1.64 www 2452: if ($remoteurl =~ /^con_lost by/) {
2453: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2454: return 'unavailable';
1.8 www 2455: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2456: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2457: return 'not_found';
1.64 www 2458: } elsif ($remoteurl =~ /^rejected by/) {
2459: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2460: return 'forbidden';
1.20 www 2461: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2462: return 'ok';
1.8 www 2463: } else {
1.290 www 2464: my $author=$filename;
2465: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2466: my ($udom,$uname)=split(/\//,$author);
2467: my $home=homeserver($uname,$udom);
2468: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2469: my @parts=split(/\//,$filename);
2470: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2471: if ($path ne "$londocroot/res") {
1.8 www 2472: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2473: return 'bad_request';
1.8 www 2474: }
2475: my $count;
2476: for ($count=5;$count<$#parts;$count++) {
2477: $path.="/$parts[$count]";
2478: if ((-e $path)!=1) {
2479: mkdir($path,0777);
2480: }
2481: }
2482: my $ua=new LWP::UserAgent;
2483: my $request=new HTTP::Request('GET',"$remoteurl");
2484: my $response=$ua->request($request,$transname);
2485: if ($response->is_error()) {
2486: unlink($transname);
2487: my $message=$response->status_line;
1.672 albertel 2488: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2489: ." LWP get: $message: $filename</font>");
1.607 raeburn 2490: return 'unavailable';
1.8 www 2491: } else {
1.16 www 2492: if ($remoteurl!~/\.meta$/) {
2493: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2494: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2495: if ($mresponse->is_error()) {
2496: unlink($filename.'.meta');
2497: &logthis(
1.672 albertel 2498: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2499: }
2500: }
1.8 www 2501: rename($transname,$filename);
1.607 raeburn 2502: return 'ok';
1.8 www 2503: }
1.290 www 2504: }
1.8 www 2505: }
1.330 www 2506: }
2507:
2508: # ------------------------------------------------ Get server side include body
2509: sub ssi_body {
1.381 albertel 2510: my ($filelink,%form)=@_;
1.606 matthew 2511: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2512: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2513: }
1.953 www 2514: my $output='';
2515: my $response;
1.980 raeburn 2516: if ($filelink=~/^https?\:/) {
1.954 raeburn 2517: ($output,$response)=&externalssi($filelink);
1.953 www 2518: } else {
1.1004 droeschl 2519: $filelink .= $filelink=~/\?/ ? '&' : '?';
2520: $filelink .= 'inhibitmenu=yes';
1.953 www 2521: ($output,$response)=&ssi($filelink,%form);
2522: }
1.778 albertel 2523: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2524: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2525: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2526: if (wantarray) {
2527: return ($output, $response);
2528: } else {
2529: return $output;
2530: }
1.8 www 2531: }
2532:
1.15 www 2533: # --------------------------------------------------------- Server Side Include
2534:
1.782 albertel 2535: sub absolute_url {
2536: my ($host_name) = @_;
2537: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2538: if ($host_name eq '') {
2539: $host_name = $ENV{'SERVER_NAME'};
2540: }
2541: return $protocol.$host_name;
2542: }
2543:
1.942 foxr 2544: #
2545: # Server side include.
2546: # Parameters:
2547: # fn Possibly encrypted resource name/id.
2548: # form Hash that describes how the rendering should be done
2549: # and other things.
1.944 foxr 2550: # Returns:
1.950 raeburn 2551: # Scalar context: The content of the response.
2552: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2553: #
1.15 www 2554: sub ssi {
2555:
1.944 foxr 2556: my ($fn,%form)=@_;
1.15 www 2557: my $ua=new LWP::UserAgent;
1.23 www 2558: my $request;
1.711 albertel 2559:
2560: $form{'no_update_last_known'}=1;
1.895 albertel 2561: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2562: if (%form) {
1.782 albertel 2563: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2564: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2565: } else {
1.782 albertel 2566: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2567: }
2568:
1.15 www 2569: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2570: my $response= $ua->request($request);
1.944 foxr 2571: if (wantarray) {
1.1172.2.3! raeburn 2572: return ($response->content, $response);
1.944 foxr 2573: } else {
1.1172.2.3! raeburn 2574: return $response->content;
1.942 foxr 2575: }
1.324 www 2576: }
2577:
2578: sub externalssi {
2579: my ($url)=@_;
2580: my $ua=new LWP::UserAgent;
2581: my $request=new HTTP::Request('GET',$url);
2582: my $response=$ua->request($request);
1.954 raeburn 2583: if (wantarray) {
2584: return ($response->content, $response);
2585: } else {
2586: return $response->content;
2587: }
1.15 www 2588: }
1.254 www 2589:
1.492 albertel 2590: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2591:
2592: sub allowuploaded {
2593: my ($srcurl,$url)=@_;
2594: $url=&clutter(&declutter($url));
2595: my $dir=$url;
2596: $dir=~s/\/[^\/]+$//;
2597: my %httpref=();
2598: my $httpurl=&hreflocation('',$url);
2599: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2600: &Apache::lonnet::appenv(\%httpref);
1.254 www 2601: }
1.477 raeburn 2602:
1.478 albertel 2603: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2604: # input: action, courseID, current domain, intended
1.637 raeburn 2605: # path to file, source of file, instruction to parse file for objects,
2606: # ref to hash for embedded objects,
2607: # ref to hash for codebase of java objects.
1.1095 raeburn 2608: # reference to scalar to accommodate mime type determined
2609: # from File::MMagic if $parser = parse.
1.637 raeburn 2610: #
1.485 raeburn 2611: # output: url to file (if action was uploaddoc),
2612: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2613: #
1.478 albertel 2614: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2615: # course.
1.477 raeburn 2616: #
1.478 albertel 2617: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2618: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2619: # course's home server.
1.477 raeburn 2620: #
1.478 albertel 2621: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2622: # be copied from $source (current location) to
2623: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2624: # and will then be copied to
2625: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2626: # course's home server.
1.485 raeburn 2627: #
1.481 raeburn 2628: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2629: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2630: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2631: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2632: # in course's home server.
1.637 raeburn 2633: #
1.477 raeburn 2634:
2635: sub process_coursefile {
1.1095 raeburn 2636: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2637: $mimetype)=@_;
1.477 raeburn 2638: my $fetchresult;
1.638 albertel 2639: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2640: if ($action eq 'propagate') {
1.638 albertel 2641: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2642: $home);
1.481 raeburn 2643: } else {
1.477 raeburn 2644: my $fpath = '';
2645: my $fname = $file;
1.478 albertel 2646: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2647: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2648: my $filepath = &build_filepath($fpath);
1.481 raeburn 2649: if ($action eq 'copy') {
2650: if ($source eq '') {
2651: $fetchresult = 'no source file';
2652: return $fetchresult;
2653: } else {
2654: my $destination = $filepath.'/'.$fname;
2655: rename($source,$destination);
2656: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2657: $home);
1.481 raeburn 2658: }
2659: } elsif ($action eq 'uploaddoc') {
2660: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2661: print $fh $env{'form.'.$source};
1.481 raeburn 2662: close($fh);
1.637 raeburn 2663: if ($parser eq 'parse') {
1.1024 raeburn 2664: my $mm = new File::MMagic;
1.1095 raeburn 2665: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2666: if ($type eq 'text/html') {
1.1024 raeburn 2667: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2668: unless ($parse_result eq 'ok') {
2669: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2670: }
1.637 raeburn 2671: }
1.1095 raeburn 2672: if (ref($mimetype)) {
2673: $$mimetype = $type;
2674: }
1.637 raeburn 2675: }
1.477 raeburn 2676: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2677: $home);
1.481 raeburn 2678: if ($fetchresult eq 'ok') {
2679: return '/uploaded/'.$fpath.'/'.$fname;
2680: } else {
2681: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2682: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2683: return '/adm/notfound.html';
2684: }
1.477 raeburn 2685: }
2686: }
1.485 raeburn 2687: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2688: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2689: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2690: }
2691: return $fetchresult;
2692: }
2693:
1.637 raeburn 2694: sub build_filepath {
2695: my ($fpath) = @_;
2696: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2697: unless ($fpath eq '') {
2698: my @parts=split('/',$fpath);
2699: foreach my $part (@parts) {
2700: $filepath.= '/'.$part;
2701: if ((-e $filepath)!=1) {
2702: mkdir($filepath,0777);
2703: }
2704: }
2705: }
2706: return $filepath;
2707: }
2708:
2709: sub store_edited_file {
1.638 albertel 2710: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2711: my $file = $primary_url;
2712: $file =~ s#^/uploaded/$docudom/$docuname/##;
2713: my $fpath = '';
2714: my $fname = $file;
2715: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2716: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2717: my $filepath = &build_filepath($fpath);
2718: open(my $fh,'>'.$filepath.'/'.$fname);
2719: print $fh $content;
2720: close($fh);
1.638 albertel 2721: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2722: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2723: $home);
1.637 raeburn 2724: if ($$fetchresult eq 'ok') {
2725: return '/uploaded/'.$fpath.'/'.$fname;
2726: } else {
1.638 albertel 2727: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2728: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2729: return '/adm/notfound.html';
2730: }
2731: }
2732:
1.531 albertel 2733: sub clean_filename {
1.831 albertel 2734: my ($fname,$args)=@_;
1.315 www 2735: # Replace Windows backslashes by forward slashes
1.257 www 2736: $fname=~s/\\/\//g;
1.831 albertel 2737: if (!$args->{'keep_path'}) {
2738: # Get rid of everything but the actual filename
2739: $fname=~s/^.*\/([^\/]+)$/$1/;
2740: }
1.315 www 2741: # Replace spaces by underscores
2742: $fname=~s/\s+/\_/g;
2743: # Replace all other weird characters by nothing
1.831 albertel 2744: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2745: # Replace all .\d. sequences with _\d. so they no longer look like version
2746: # numbers
2747: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2748: return $fname;
2749: }
1.1051 raeburn 2750: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2751: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2752: # image with the same aspect ratio as the original, but with dimensions which do
2753: # not exceed $resizewidth and $resizeheight.
2754:
1.984 neumanie 2755: sub resizeImage {
1.1051 raeburn 2756: my ($img_path,$resizewidth,$resizeheight) = @_;
2757: my $ima = Image::Magick->new;
2758: my $resized;
2759: if (-e $img_path) {
2760: $ima->Read($img_path);
2761: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2762: my $width = $ima->Get('width');
2763: my $height = $ima->Get('height');
2764: if ($width > $resizewidth) {
2765: my $factor = $width/$resizewidth;
2766: my $newheight = $height/$factor;
2767: $ima->Scale(width=>$resizewidth,height=>$newheight);
2768: $resized = 1;
2769: }
2770: }
2771: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2772: my $width = $ima->Get('width');
2773: my $height = $ima->Get('height');
2774: if ($height > $resizeheight) {
2775: my $factor = $height/$resizeheight;
2776: my $newwidth = $width/$factor;
2777: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2778: $resized = 1;
2779: }
2780: }
2781: if ($resized) {
2782: $ima->Write($img_path);
2783: }
2784: }
2785: return;
1.977 amueller 2786: }
2787:
1.608 albertel 2788: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2789: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2790: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2791: # $context - possible values: coursedoc, existingfile, overwrite,
2792: # canceloverwrite, or ''.
2793: # if 'coursedoc': upload to the current course
2794: # if 'existingfile': write file to tmp/overwrites directory
2795: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2796: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2797: # $subdir - directory in userfile to store the file into
1.858 raeburn 2798: # $parser - instruction to parse file for objects ($parser = parse)
2799: # $allfiles - reference to hash for embedded objects
2800: # $codebase - reference to hash for codebase of java objects
2801: # $desuname - username for permanent storage of uploaded file
2802: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2803: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2804: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2805: # $resizewidth - width (pixels) to which to resize uploaded image
2806: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2807: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2808: # from File::MMagic.
1.858 raeburn 2809: #
1.686 albertel 2810: # output: url of file in userspace, or error: <message>
2811: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2812:
1.531 albertel 2813: sub userfileupload {
1.1090 raeburn 2814: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2815: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2816: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2817: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2818: $fname=&clean_filename($fname);
1.1090 raeburn 2819: # See if there is anything left
1.257 www 2820: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2821: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2822: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2823: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2824: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2825: my $now = time;
1.1090 raeburn 2826: my $filepath;
1.1095 raeburn 2827: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2828: $filepath = 'tmp/helprequests/'.$now;
2829: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2830: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2831: '_'.$env{'user.domain'}.'/pending';
2832: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2833: my ($docuname,$docudom);
2834: if ($destudom) {
2835: $docudom = $destudom;
2836: } else {
2837: $docudom = $env{'user.domain'};
2838: }
2839: if ($destuname) {
2840: $docuname = $destuname;
2841: } else {
2842: $docuname = $env{'user.name'};
2843: }
2844: if (exists($env{'form.group'})) {
2845: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2846: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2847: }
2848: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2849: if ($context eq 'canceloverwrite') {
2850: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2851: if (-e $tempfile) {
2852: my @info = stat($tempfile);
2853: if ($info[9] eq $env{'form.timestamp'}) {
2854: unlink($tempfile);
2855: }
2856: }
2857: return;
1.523 raeburn 2858: }
2859: }
1.1090 raeburn 2860: # Create the directory if not present
1.741 raeburn 2861: my @parts=split(/\//,$filepath);
2862: my $fullpath = $perlvar{'lonDaemons'};
2863: for (my $i=0;$i<@parts;$i++) {
2864: $fullpath .= '/'.$parts[$i];
2865: if ((-e $fullpath)!=1) {
2866: mkdir($fullpath,0777);
2867: }
2868: }
2869: open(my $fh,'>'.$fullpath.'/'.$fname);
2870: print $fh $env{'form.'.$formname};
2871: close($fh);
1.1090 raeburn 2872: if ($context eq 'existingfile') {
2873: my @info = stat($fullpath.'/'.$fname);
2874: return ($fullpath.'/'.$fname,$info[9]);
2875: } else {
2876: return $fullpath.'/'.$fname;
2877: }
1.523 raeburn 2878: }
1.995 raeburn 2879: if ($subdir eq 'scantron') {
2880: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2881: } else {
1.995 raeburn 2882: $fname="$subdir/$fname";
2883: }
1.1090 raeburn 2884: if ($context eq 'coursedoc') {
1.638 albertel 2885: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2886: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2887: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2888: return &finishuserfileupload($docuname,$docudom,
2889: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2890: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2891: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2892: } else {
1.620 albertel 2893: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2894: return &process_coursefile('uploaddoc',$docuname,$docudom,
2895: $fname,$formname,$parser,
1.1095 raeburn 2896: $allfiles,$codebase,$mimetype);
1.481 raeburn 2897: }
1.719 banghart 2898: } elsif (defined($destuname)) {
2899: my $docuname=$destuname;
2900: my $docudom=$destudom;
1.860 raeburn 2901: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2902: $parser,$allfiles,$codebase,
1.1051 raeburn 2903: $thumbwidth,$thumbheight,
1.1095 raeburn 2904: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2905: } else {
1.638 albertel 2906: my $docuname=$env{'user.name'};
2907: my $docudom=$env{'user.domain'};
1.714 raeburn 2908: if (exists($env{'form.group'})) {
2909: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2910: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2911: }
1.860 raeburn 2912: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2913: $parser,$allfiles,$codebase,
1.1051 raeburn 2914: $thumbwidth,$thumbheight,
1.1095 raeburn 2915: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2916: }
1.271 www 2917: }
2918:
2919: sub finishuserfileupload {
1.860 raeburn 2920: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2921: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2922: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2923: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2924:
1.860 raeburn 2925: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2926: $file=$fname;
2927: if ($fname=~m|/|) {
2928: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2929: $path.=$fnamepath.'/';
2930: }
1.259 www 2931: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2932: my $count;
2933: for ($count=4;$count<=$#parts;$count++) {
2934: $filepath.="/$parts[$count]";
2935: if ((-e $filepath)!=1) {
2936: mkdir($filepath,0777);
2937: }
2938: }
1.984 neumanie 2939:
1.258 www 2940: # Save the file
2941: {
1.701 albertel 2942: if (!open(FH,'>'.$filepath.'/'.$file)) {
2943: &logthis('Failed to create '.$filepath.'/'.$file);
2944: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2945: return '/adm/notfound.html';
2946: }
1.1090 raeburn 2947: if ($context eq 'overwrite') {
1.1117 foxr 2948: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2949: my $target = $filepath.'/'.$file;
2950: if (-e $source) {
2951: my @info = stat($source);
2952: if ($info[9] eq $env{'form.timestamp'}) {
2953: unless (&File::Copy::move($source,$target)) {
2954: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2955: return "Moving from $source failed";
2956: }
2957: } else {
2958: return "Temporary file: $source had unexpected date/time for last modification";
2959: }
2960: } else {
2961: return "Temporary file: $source missing";
2962: }
2963: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2964: &logthis('Failed to write to '.$filepath.'/'.$file);
2965: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2966: return '/adm/notfound.html';
2967: }
1.570 albertel 2968: close(FH);
1.1051 raeburn 2969: if ($resizewidth && $resizeheight) {
2970: my $mm = new File::MMagic;
2971: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2972: if ($mime_type =~ m{^image/}) {
2973: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2974: }
1.977 amueller 2975: }
1.258 www 2976: }
1.1152 raeburn 2977: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2978: if (ref($mimetype)) {
2979: if ($$mimetype eq '') {
2980: my $mm = new File::MMagic;
2981: my $type = $mm->checktype_filename($filepath.'/'.$file);
2982: $$mimetype = $type;
2983: }
2984: }
2985: }
1.637 raeburn 2986: if ($parser eq 'parse') {
1.1152 raeburn 2987: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 2988: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2989: $allfiles,$codebase);
2990: unless ($parse_result eq 'ok') {
2991: &logthis('Failed to parse '.$filepath.$file.
2992: ' for embedded media: '.$parse_result);
2993: }
1.637 raeburn 2994: }
2995: }
1.860 raeburn 2996: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2997: my $input = $filepath.'/'.$file;
2998: my $output = $filepath.'/'.'tn-'.$file;
2999: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3000: system("convert -sample $thumbsize $input $output");
3001: if (-e $filepath.'/'.'tn-'.$file) {
3002: $fetchthumb = 1;
3003: }
3004: }
1.858 raeburn 3005:
1.259 www 3006: # Notify homeserver to grep it
3007: #
1.984 neumanie 3008: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3009: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3010: if ($fetchresult eq 'ok') {
1.860 raeburn 3011: if ($fetchthumb) {
3012: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3013: if ($thumbresult ne 'ok') {
3014: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3015: $docuhome.': '.$thumbresult);
3016: }
3017: }
1.259 www 3018: #
1.258 www 3019: # Return the URL to it
1.494 albertel 3020: return '/uploaded/'.$path.$file;
1.263 www 3021: } else {
1.494 albertel 3022: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3023: ': '.$fetchresult);
1.263 www 3024: return '/adm/notfound.html';
1.858 raeburn 3025: }
1.493 albertel 3026: }
3027:
1.637 raeburn 3028: sub extract_embedded_items {
1.961 raeburn 3029: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3030: my @state = ();
1.1164 raeburn 3031: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3032: my %javafiles = (
3033: codebase => '',
3034: code => '',
3035: archive => ''
3036: );
3037: my %mediafiles = (
3038: src => '',
3039: movie => '',
3040: );
1.648 raeburn 3041: my $p;
3042: if ($content) {
3043: $p = HTML::LCParser->new($content);
3044: } else {
1.961 raeburn 3045: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3046: }
1.641 albertel 3047: while (my $t=$p->get_token()) {
1.640 albertel 3048: if ($t->[0] eq 'S') {
3049: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3050: push(@state, $tagname);
1.648 raeburn 3051: if (lc($tagname) eq 'allow') {
3052: &add_filetype($allfiles,$attr->{'src'},'src');
3053: }
1.640 albertel 3054: if (lc($tagname) eq 'img') {
3055: &add_filetype($allfiles,$attr->{'src'},'src');
3056: }
1.886 albertel 3057: if (lc($tagname) eq 'a') {
3058: &add_filetype($allfiles,$attr->{'href'},'href');
3059: }
1.645 raeburn 3060: if (lc($tagname) eq 'script') {
1.1164 raeburn 3061: my $src;
1.645 raeburn 3062: if ($attr->{'archive'} =~ /\.jar$/i) {
3063: &add_filetype($allfiles,$attr->{'archive'},'archive');
3064: } else {
1.1164 raeburn 3065: if ($attr->{'src'} ne '') {
3066: $src = $attr->{'src'};
3067: &add_filetype($allfiles,$src,'src');
3068: }
3069: }
3070: my $text = $p->get_trimmed_text();
3071: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3072: my @swfargs = split(/,/,$1);
3073: foreach my $item (@swfargs) {
3074: $item =~ s/["']//g;
3075: $item =~ s/^\s+//;
3076: $item =~ s/\s+$//;
3077: }
3078: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3079: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3080: push(@{$related{$swfargs[0]}},$swfargs[2]);
3081: } else {
3082: $related{$swfargs[0]} = [$swfargs[2]];
3083: }
3084: }
1.645 raeburn 3085: }
3086: }
3087: if (lc($tagname) eq 'link') {
3088: if (lc($attr->{'rel'}) eq 'stylesheet') {
3089: &add_filetype($allfiles,$attr->{'href'},'href');
3090: }
3091: }
1.640 albertel 3092: if (lc($tagname) eq 'object' ||
3093: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3094: foreach my $item (keys(%javafiles)) {
3095: $javafiles{$item} = '';
3096: }
1.1164 raeburn 3097: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3098: $lastids{lc($tagname)} = $attr->{'id'};
3099: }
1.640 albertel 3100: }
3101: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3102: my $name = lc($attr->{'name'});
3103: foreach my $item (keys(%javafiles)) {
3104: if ($name eq $item) {
3105: $javafiles{$item} = $attr->{'value'};
3106: last;
3107: }
3108: }
1.1164 raeburn 3109: my $pathfrom;
1.640 albertel 3110: foreach my $item (keys(%mediafiles)) {
3111: if ($name eq $item) {
1.1164 raeburn 3112: $pathfrom = $attr->{'value'};
3113: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3114: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3115: last;
3116: }
3117: }
1.1164 raeburn 3118: if ($name eq 'flashvars') {
3119: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3120: }
3121: if ($pathfrom ne '') {
3122: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3123: $pathfrom);
3124: }
1.640 albertel 3125: }
3126: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3127: foreach my $item (keys(%javafiles)) {
3128: if ($attr->{$item}) {
3129: $javafiles{$item} = $attr->{$item};
3130: last;
3131: }
3132: }
3133: foreach my $item (keys(%mediafiles)) {
3134: if ($attr->{$item}) {
3135: &add_filetype($allfiles,$attr->{$item},$item);
3136: last;
3137: }
3138: }
1.1164 raeburn 3139: if (lc($tagname) eq 'embed') {
3140: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3141: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3142: $attr->{'src'});
3143: }
3144: }
1.640 albertel 3145: }
1.1164 raeburn 3146: if ($t->[4] =~ m{/>$}) {
3147: pop(@state);
3148: }
1.640 albertel 3149: } elsif ($t->[0] eq 'E') {
3150: my ($tagname) = ($t->[1]);
3151: if ($javafiles{'codebase'} ne '') {
3152: $javafiles{'codebase'} .= '/';
3153: }
3154: if (lc($tagname) eq 'applet' ||
3155: lc($tagname) eq 'object' ||
3156: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3157: ) {
3158: foreach my $item (keys(%javafiles)) {
3159: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3160: my $file=$javafiles{'codebase'}.$javafiles{$item};
3161: &add_filetype($allfiles,$file,$item);
3162: }
3163: }
3164: }
3165: pop @state;
3166: }
3167: }
1.1164 raeburn 3168: foreach my $id (sort(keys(%flashvars))) {
3169: if ($shockwave{$id} ne '') {
3170: my @pairs = split(/\&/,$flashvars{$id});
3171: foreach my $pair (@pairs) {
3172: my ($key,$value) = split(/\=/,$pair);
3173: if ($key eq 'thumb') {
3174: &add_filetype($allfiles,$value,$key);
3175: } elsif ($key eq 'content') {
3176: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3177: my ($ext) = ($value =~ /\.([^.]+)$/);
3178: if ($ext ne '') {
3179: &add_filetype($allfiles,$path.$value,$ext);
3180: }
3181: }
3182: }
3183: }
3184: }
1.637 raeburn 3185: return 'ok';
3186: }
3187:
1.639 albertel 3188: sub add_filetype {
3189: my ($allfiles,$file,$type)=@_;
3190: if (exists($allfiles->{$file})) {
3191: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3192: push(@{$allfiles->{$file}}, &escape($type));
3193: }
3194: } else {
3195: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3196: }
3197: }
3198:
1.1164 raeburn 3199: sub embedded_dependency {
3200: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3201: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3202: if (($identifier ne '') &&
3203: (ref($related->{$identifier}) eq 'ARRAY') &&
3204: ($pathfrom ne '')) {
3205: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3206: foreach my $dep (@{$related->{$identifier}}) {
3207: &add_filetype($allfiles,$path.$dep,'object');
3208: }
3209: }
3210: }
3211: return;
3212: }
3213:
1.493 albertel 3214: sub removeuploadedurl {
1.984 neumanie 3215: my ($url)=@_;
3216: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3217: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3218: }
3219:
3220: sub removeuserfile {
3221: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3222: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3223: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3224: if ($result eq 'ok') {
1.798 raeburn 3225: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3226: my $metafile = $fname.'.meta';
3227: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3228: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3229: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3230: my $sqlresult =
1.823 albertel 3231: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3232: 'portfolio_metadata',$group,
3233: 'delete');
1.798 raeburn 3234: }
3235: }
3236: return $result;
1.257 www 3237: }
1.15 www 3238:
1.530 albertel 3239: sub mkdiruserfile {
3240: my ($docuname,$docudom,$dir)=@_;
3241: my $home=&homeserver($docuname,$docudom);
3242: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3243: }
3244:
1.531 albertel 3245: sub renameuserfile {
3246: my ($docuname,$docudom,$old,$new)=@_;
3247: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3248: my $result = &reply("renameuserfile:$docudom:$docuname:".
3249: &escape("$old").':'.&escape("$new"),$home);
3250: if ($result eq 'ok') {
3251: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3252: my $oldmeta = $old.'.meta';
3253: my $newmeta = $new.'.meta';
3254: my $metaresult =
3255: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3256: my $url = "/uploaded/$docudom/$docuname/$old";
3257: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3258: my $sqlresult =
1.823 albertel 3259: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3260: 'portfolio_metadata',$group,
3261: 'delete');
1.798 raeburn 3262: }
3263: }
3264: return $result;
1.531 albertel 3265: }
3266:
1.14 www 3267: # ------------------------------------------------------------------------- Log
3268:
3269: sub log {
3270: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3271: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3272: }
3273:
3274: # ------------------------------------------------------------------ Course Log
1.352 www 3275: #
3276: # This routine flushes several buffers of non-mission-critical nature
3277: #
1.157 www 3278:
3279: sub flushcourselogs {
1.352 www 3280: &logthis('Flushing log buffers');
3281: #
3282: # course logs
3283: # This is a log of all transactions in a course, which can be used
3284: # for data mining purposes
3285: #
3286: # It also collects the courseid database, which lists last transaction
3287: # times and course titles for all courseids
3288: #
3289: my %courseidbuffer=();
1.921 raeburn 3290: foreach my $crsid (keys(%courselogs)) {
1.352 www 3291: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3292: &escape($courselogs{$crsid}),
3293: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3294: delete $courselogs{$crsid};
3295: } else {
3296: &logthis('Failed to flush log buffer for '.$crsid);
3297: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3298: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3299: " exceeded maximum size, deleting.</font>");
3300: delete $courselogs{$crsid};
3301: }
1.352 www 3302: }
1.920 raeburn 3303: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3304: 'description' => $coursedescrbuf{$crsid},
3305: 'inst_code' => $courseinstcodebuf{$crsid},
3306: 'type' => $coursetypebuf{$crsid},
3307: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3308: };
1.191 harris41 3309: }
1.352 www 3310: #
3311: # Write course id database (reverse lookup) to homeserver of courses
3312: # Is used in pickcourse
3313: #
1.840 albertel 3314: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3315: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3316: $courseidbuffer{$crs_home},
3317: $crs_home,'timeonly');
1.352 www 3318: }
3319: #
3320: # File accesses
3321: # Writes to the dynamic metadata of resources to get hit counts, etc.
3322: #
1.449 matthew 3323: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3324: if ($entry =~ /___count$/) {
3325: my ($dom,$name);
1.807 albertel 3326: ($dom,$name,undef)=
1.811 albertel 3327: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3328: if (! defined($dom) || $dom eq '' ||
3329: ! defined($name) || $name eq '') {
1.620 albertel 3330: my $cid = $env{'request.course.id'};
3331: $dom = $env{'request.'.$cid.'.domain'};
3332: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3333: }
1.450 matthew 3334: my $value = $accesshash{$entry};
3335: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3336: my %temphash=($url => $value);
1.449 matthew 3337: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3338: if ($result eq 'ok') {
3339: delete $accesshash{$entry};
3340: }
3341: } else {
1.811 albertel 3342: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3343: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3344: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3345: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3346: delete $accesshash{$entry};
3347: }
1.185 www 3348: }
1.191 harris41 3349: }
1.352 www 3350: #
3351: # Roles
3352: # Reverse lookup of user roles for course faculty/staff and co-authorship
3353: #
1.800 albertel 3354: foreach my $entry (keys(%userrolehash)) {
1.351 www 3355: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3356: split(/\:/,$entry);
3357: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3358: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3359: $rudom,$runame) eq 'ok') {
3360: delete $userrolehash{$entry};
3361: }
3362: }
1.662 raeburn 3363: #
3364: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3365: #
3366: my %domrolebuffer = ();
1.1000 raeburn 3367: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3368: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3369: if ($domrolebuffer{$rudom}) {
3370: $domrolebuffer{$rudom}.='&'.&escape($entry).
3371: '='.&escape($domainrolehash{$entry});
3372: } else {
3373: $domrolebuffer{$rudom}.=&escape($entry).
3374: '='.&escape($domainrolehash{$entry});
3375: }
3376: delete $domainrolehash{$entry};
3377: }
3378: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3379: my %servers = &get_servers($dom,'library');
3380: foreach my $tryserver (keys(%servers)) {
3381: unless (&reply('domroleput:'.$dom.':'.
3382: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3383: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3384: }
1.662 raeburn 3385: }
3386: }
1.186 www 3387: $dumpcount++;
1.157 www 3388: }
3389:
3390: sub courselog {
3391: my $what=shift;
1.158 www 3392: $what=time.':'.$what;
1.620 albertel 3393: unless ($env{'request.course.id'}) { return ''; }
3394: $coursedombuf{$env{'request.course.id'}}=
3395: $env{'course.'.$env{'request.course.id'}.'.domain'};
3396: $coursenumbuf{$env{'request.course.id'}}=
3397: $env{'course.'.$env{'request.course.id'}.'.num'};
3398: $coursehombuf{$env{'request.course.id'}}=
3399: $env{'course.'.$env{'request.course.id'}.'.home'};
3400: $coursedescrbuf{$env{'request.course.id'}}=
3401: $env{'course.'.$env{'request.course.id'}.'.description'};
3402: $courseinstcodebuf{$env{'request.course.id'}}=
3403: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3404: $courseownerbuf{$env{'request.course.id'}}=
3405: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3406: $coursetypebuf{$env{'request.course.id'}}=
3407: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3408: if (defined $courselogs{$env{'request.course.id'}}) {
3409: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3410: } else {
1.620 albertel 3411: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3412: }
1.620 albertel 3413: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3414: &flushcourselogs();
3415: }
1.158 www 3416: }
3417:
3418: sub courseacclog {
3419: my $fnsymb=shift;
1.620 albertel 3420: unless ($env{'request.course.id'}) { return ''; }
3421: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3422: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3423: $what.=':POST';
1.583 matthew 3424: # FIXME: Probably ought to escape things....
1.800 albertel 3425: foreach my $key (keys(%env)) {
3426: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3427: my $formitem = $1;
3428: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3429: $what.=':'.$formitem.'='.$env{$key};
3430: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3431: $what.=':'.$formitem.'='.$env{$key};
3432: }
1.158 www 3433: }
1.191 harris41 3434: }
1.583 matthew 3435: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3436: # FIXME: We should not be depending on a form parameter that someone
3437: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3438: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3439: $what.= ':POST';
3440: # FIXME: Probably ought to escape things....
3441: foreach my $element ('courseexp','crsfulltext','crsrelated',
3442: 'crsdiscuss') {
1.620 albertel 3443: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3444: }
3445: }
1.158 www 3446: }
3447: &courselog($what);
1.149 www 3448: }
3449:
1.185 www 3450: sub countacc {
3451: my $url=&declutter(shift);
1.458 matthew 3452: return if (! defined($url) || $url eq '');
1.620 albertel 3453: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3454: #
3455: # Mark that this url was used in this course
3456: #
1.620 albertel 3457: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3458: #
3459: # Increase the access count for this resource in this child process
3460: #
1.281 www 3461: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3462: $accesshash{$key}++;
1.185 www 3463: }
1.349 www 3464:
1.361 www 3465: sub linklog {
3466: my ($from,$to)=@_;
3467: $from=&declutter($from);
3468: $to=&declutter($to);
3469: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3470: $accesshash{$to.'___'.$from.'___goto'}=1;
3471: }
1.1160 www 3472:
3473: sub statslog {
3474: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3475: if ($users<2) { return; }
3476: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3477: 'course' => $env{'request.course.id'},
3478: 'sections' => '"all"',
3479: 'num_students' => $users,
3480: 'part' => $part,
3481: 'symb' => $symb,
3482: 'mean_tries' => $av_attempts,
3483: 'deg_of_diff' => $degdiff});
3484: foreach my $key (keys(%dynstore)) {
3485: $accesshash{$key}=$dynstore{$key};
3486: }
3487: }
1.361 www 3488:
1.349 www 3489: sub userrolelog {
3490: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3491: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3492: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3493: $userrolehash
3494: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3495: =$tend.':'.$tstart;
1.662 raeburn 3496: }
1.1169 droeschl 3497: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3498: $userrolehash
3499: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3500: =$tend.':'.$tstart;
3501: }
1.1169 droeschl 3502: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3503: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3504: $domainrolehash
3505: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3506: = $tend.':'.$tstart;
3507: }
1.351 www 3508: }
3509:
1.957 raeburn 3510: sub courserolelog {
3511: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3512: if (($trole eq 'cc') || ($trole eq 'in') ||
3513: ($trole eq 'ep') || ($trole eq 'ad') ||
3514: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3515: ($trole=~/^cr/) || ($trole eq 'gr') ||
3516: ($trole eq 'co')) {
1.957 raeburn 3517: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3518: my $cdom = $1;
3519: my $cnum = $2;
3520: my $sec = $3;
3521: my $namespace = 'rolelog';
3522: my %storehash = (
3523: role => $trole,
3524: start => $tstart,
3525: end => $tend,
3526: selfenroll => $selfenroll,
3527: context => $context,
3528: );
3529: if ($trole eq 'gr') {
3530: $namespace = 'groupslog';
3531: $storehash{'group'} = $sec;
3532: } else {
3533: $storehash{'section'} = $sec;
3534: }
3535: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3536: if (($trole ne 'st') || ($sec ne '')) {
3537: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3538: }
1.957 raeburn 3539: }
3540: }
3541: return;
3542: }
3543:
1.351 www 3544: sub get_course_adv_roles {
1.948 raeburn 3545: my ($cid,$codes) = @_;
1.620 albertel 3546: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3547: my %coursehash=&coursedescription($cid);
1.988 raeburn 3548: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3549: my %nothide=();
1.800 albertel 3550: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3551: if ($user !~ /:/) {
3552: $nothide{join(':',split(/[\@]/,$user))}=1;
3553: } else {
3554: $nothide{$user}=1;
3555: }
1.470 www 3556: }
1.351 www 3557: my %returnhash=();
3558: my %dumphash=
3559: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3560: my $now=time;
1.997 raeburn 3561: my %privileged;
1.1000 raeburn 3562: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3563: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3564: if (($tstart) && ($tstart<0)) { next; }
3565: if (($tend) && ($tend<$now)) { next; }
3566: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3567: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3568: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3569: unless (ref($privileged{$domain}) eq 'HASH') {
3570: my %dompersonnel =
1.998 raeburn 3571: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3572: $privileged{$domain} = {};
3573: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3574: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3575: foreach my $user (keys(%{$dompersonnel{$server}})) {
3576: my ($trole,$uname,$udom) = split(/:/,$user);
3577: $privileged{$udom}{$uname} = 1;
3578: }
3579: }
3580: }
3581: }
3582: if ((exists($privileged{$domain}{$username})) &&
3583: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3584: if ($role eq 'cr') { next; }
1.948 raeburn 3585: if ($codes) {
3586: if ($section) { $role .= ':'.$section; }
3587: if ($returnhash{$role}) {
3588: $returnhash{$role}.=','.$username.':'.$domain;
3589: } else {
3590: $returnhash{$role}=$username.':'.$domain;
3591: }
1.351 www 3592: } else {
1.988 raeburn 3593: my $key=&plaintext($role,$crstype);
1.973 bisitz 3594: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3595: if ($returnhash{$key}) {
3596: $returnhash{$key}.=','.$username.':'.$domain;
3597: } else {
3598: $returnhash{$key}=$username.':'.$domain;
3599: }
1.351 www 3600: }
1.948 raeburn 3601: }
1.400 www 3602: return %returnhash;
3603: }
3604:
3605: sub get_my_roles {
1.937 raeburn 3606: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3607: unless (defined($uname)) { $uname=$env{'user.name'}; }
3608: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3609: my (%dumphash,%nothide);
1.1086 raeburn 3610: if ($context eq 'userroles') {
1.1166 raeburn 3611: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3612: } else {
3613: %dumphash=
1.400 www 3614: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3615: if ($hidepriv) {
3616: my %coursehash=&coursedescription($udom.'_'.$uname);
3617: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3618: if ($user !~ /:/) {
3619: $nothide{join(':',split(/[\@]/,$user))} = 1;
3620: } else {
3621: $nothide{$user} = 1;
3622: }
3623: }
3624: }
1.858 raeburn 3625: }
1.400 www 3626: my %returnhash=();
3627: my $now=time;
1.999 raeburn 3628: my %privileged;
1.800 albertel 3629: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3630: my ($role,$tend,$tstart);
3631: if ($context eq 'userroles') {
1.1149 raeburn 3632: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3633: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3634: } else {
3635: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3636: }
1.400 www 3637: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3638: my $status = 'active';
1.939 raeburn 3639: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3640: $status = 'previous';
3641: }
3642: if (($tstart) && ($now<$tstart)) {
3643: $status = 'future';
3644: }
3645: if (ref($types) eq 'ARRAY') {
3646: if (!grep(/^\Q$status\E$/,@{$types})) {
3647: next;
3648: }
3649: } else {
3650: if ($status ne 'active') {
3651: next;
3652: }
3653: }
1.867 raeburn 3654: my ($rolecode,$username,$domain,$section,$area);
3655: if ($context eq 'userroles') {
3656: ($area,$rolecode) = split(/_/,$entry);
3657: (undef,$domain,$username,$section) = split(/\//,$area);
3658: } else {
3659: ($role,$username,$domain,$section) = split(/\:/,$entry);
3660: }
1.832 raeburn 3661: if (ref($roledoms) eq 'ARRAY') {
3662: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3663: next;
3664: }
3665: }
3666: if (ref($roles) eq 'ARRAY') {
3667: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3668: if ($role =~ /^cr\//) {
3669: if (!grep(/^cr$/,@{$roles})) {
3670: next;
3671: }
1.1104 raeburn 3672: } elsif ($role =~ /^gr\//) {
3673: if (!grep(/^gr$/,@{$roles})) {
3674: next;
3675: }
1.922 raeburn 3676: } else {
3677: next;
3678: }
1.832 raeburn 3679: }
1.867 raeburn 3680: }
1.937 raeburn 3681: if ($hidepriv) {
1.999 raeburn 3682: if ($context eq 'userroles') {
3683: if ((&privileged($username,$domain)) &&
3684: (!$nothide{$username.':'.$domain})) {
3685: next;
3686: }
3687: } else {
3688: unless (ref($privileged{$domain}) eq 'HASH') {
3689: my %dompersonnel =
3690: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3691: $privileged{$domain} = {};
3692: if (keys(%dompersonnel)) {
3693: foreach my $server (keys(%dompersonnel)) {
3694: if (ref($dompersonnel{$server}) eq 'HASH') {
3695: foreach my $user (keys(%{$dompersonnel{$server}})) {
3696: my ($trole,$uname,$udom) = split(/:/,$user);
3697: $privileged{$udom}{$uname} = $trole;
3698: }
3699: }
3700: }
3701: }
3702: }
3703: if (exists($privileged{$domain}{$username})) {
3704: if (!$nothide{$username.':'.$domain}) {
3705: next;
3706: }
3707: }
1.937 raeburn 3708: }
3709: }
1.933 raeburn 3710: if ($withsec) {
3711: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3712: $tstart.':'.$tend;
3713: } else {
3714: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3715: }
1.832 raeburn 3716: }
1.373 www 3717: return %returnhash;
1.399 www 3718: }
3719:
3720: # ----------------------------------------------------- Frontpage Announcements
3721: #
3722: #
3723:
3724: sub postannounce {
3725: my ($server,$text)=@_;
1.844 albertel 3726: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3727: unless ($text=~/\w/) { $text=''; }
3728: return &reply('setannounce:'.&escape($text),$server);
3729: }
3730:
3731: sub getannounce {
1.448 albertel 3732:
3733: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3734: my $announcement='';
1.800 albertel 3735: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3736: close($fh);
1.399 www 3737: if ($announcement=~/\w/) {
3738: return
3739: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3740: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3741: } else {
3742: return '';
3743: }
3744: } else {
3745: return '';
3746: }
1.351 www 3747: }
1.353 www 3748:
3749: # ---------------------------------------------------------- Course ID routines
3750: # Deal with domain's nohist_courseid.db files
3751: #
3752:
3753: sub courseidput {
1.921 raeburn 3754: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3755: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3756: my $outcome;
3757: if ($caller eq 'timeonly') {
3758: my $cids = '';
3759: foreach my $item (keys(%$storehash)) {
3760: $cids.=&escape($item).'&';
3761: }
3762: $cids=~s/\&$//;
3763: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3764: $coursehome);
3765: } else {
3766: my $items = '';
3767: foreach my $item (keys(%$storehash)) {
3768: $items.= &escape($item).'='.
3769: &freeze_escape($$storehash{$item}).'&';
3770: }
3771: $items=~s/\&$//;
3772: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3773: $coursehome);
1.918 raeburn 3774: }
3775: if ($outcome eq 'unknown_cmd') {
3776: my $what;
3777: foreach my $cid (keys(%$storehash)) {
3778: $what .= &escape($cid).'=';
1.921 raeburn 3779: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3780: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3781: }
3782: $what =~ s/\:$/&/;
3783: }
3784: $what =~ s/\&$//;
3785: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3786: } else {
3787: return $outcome;
3788: }
1.353 www 3789: }
3790:
3791: sub courseiddump {
1.921 raeburn 3792: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3793: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3794: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3795: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3796: my $as_hash = 1;
3797: my %returnhash;
3798: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3799: my %libserv = &all_library();
3800: foreach my $tryserver (keys(%libserv)) {
3801: if ( ( $hostidflag == 1
3802: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3803: || (!defined($hostidflag)) ) {
3804:
1.918 raeburn 3805: if (($domfilter eq '') ||
3806: (&host_domain($tryserver) eq $domfilter)) {
3807: my $rep =
3808: &reply('courseiddump:'.&host_domain($tryserver).':'.
3809: $sincefilter.':'.&escape($descfilter).':'.
3810: &escape($instcodefilter).':'.&escape($ownerfilter).
3811: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3812: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3813: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3814: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3815: &escape($cc_clone).':'.$cloneonly.':'.
3816: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3817: &escape($creationcontext).':'.$domcloner,
3818: $tryserver);
1.918 raeburn 3819: my @pairs=split(/\&/,$rep);
3820: foreach my $item (@pairs) {
3821: my ($key,$value)=split(/\=/,$item,2);
3822: $key = &unescape($key);
3823: next if ($key =~ /^error: 2 /);
3824: my $result = &thaw_unescape($value);
3825: if (ref($result) eq 'HASH') {
3826: $returnhash{$key}=$result;
3827: } else {
1.921 raeburn 3828: my @responses = split(/:/,$value);
3829: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3830: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3831: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3832: }
1.1008 raeburn 3833: }
1.353 www 3834: }
3835: }
3836: }
3837: }
3838: return %returnhash;
3839: }
3840:
1.1055 raeburn 3841: sub courselastaccess {
3842: my ($cdom,$cnum,$hostidref) = @_;
3843: my %returnhash;
3844: if ($cdom && $cnum) {
3845: my $chome = &homeserver($cnum,$cdom);
3846: if ($chome ne 'no_host') {
3847: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3848: &extract_lastaccess(\%returnhash,$rep);
3849: }
3850: } else {
3851: if (!$cdom) { $cdom=''; }
3852: my %libserv = &all_library();
3853: foreach my $tryserver (keys(%libserv)) {
3854: if (ref($hostidref) eq 'ARRAY') {
3855: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3856: }
3857: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3858: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3859: &extract_lastaccess(\%returnhash,$rep);
3860: }
3861: }
3862: }
3863: return %returnhash;
3864: }
3865:
3866: sub extract_lastaccess {
3867: my ($returnhash,$rep) = @_;
3868: if (ref($returnhash) eq 'HASH') {
3869: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3870: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3871: $rep eq '') {
3872: my @pairs=split(/\&/,$rep);
3873: foreach my $item (@pairs) {
3874: my ($key,$value)=split(/\=/,$item,2);
3875: $key = &unescape($key);
3876: next if ($key =~ /^error: 2 /);
3877: $returnhash->{$key} = &thaw_unescape($value);
3878: }
3879: }
3880: }
3881: return;
3882: }
3883:
1.658 raeburn 3884: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3885:
3886: sub dcmailput {
1.685 raeburn 3887: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3888: my $status = &Apache::lonnet::critical(
1.740 www 3889: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3890: &escape($message),$server);
1.662 raeburn 3891: return $status;
3892: }
3893:
1.658 raeburn 3894: sub dcmaildump {
3895: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3896: my %returnhash=();
1.846 albertel 3897:
3898: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3899: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3900: &escape($enddate).':';
3901: my @esc_senders=map { &escape($_)} @$senders;
3902: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3903: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3904: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3905: if (($key) && ($value)) {
3906: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3907: }
3908: }
3909: }
3910: return %returnhash;
3911: }
1.662 raeburn 3912: # ---------------------------------------------------------- Domain roles
3913:
3914: sub get_domain_roles {
3915: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3916: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3917: $startdate = '.';
3918: }
1.1018 raeburn 3919: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3920: $enddate = '.';
3921: }
1.922 raeburn 3922: my $rolelist;
3923: if (ref($roles) eq 'ARRAY') {
3924: $rolelist = join(':',@{$roles});
3925: }
1.662 raeburn 3926: my %personnel = ();
1.841 albertel 3927:
3928: my %servers = &get_servers($dom,'library');
3929: foreach my $tryserver (keys(%servers)) {
3930: %{$personnel{$tryserver}}=();
3931: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3932: &escape($startdate).':'.
3933: &escape($enddate).':'.
3934: &escape($rolelist), $tryserver))) {
3935: my ($key,$value) = split(/\=/,$line,2);
3936: if (($key) && ($value)) {
3937: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3938: }
3939: }
1.662 raeburn 3940: }
3941: return %personnel;
3942: }
1.658 raeburn 3943:
1.1057 www 3944: # ----------------------------------------------------------- Interval timing
1.149 www 3945:
1.1153 www 3946: {
3947: # Caches needed for speedup of navmaps
3948: # We don't want to cache this for very long at all (5 seconds at most)
3949: #
3950: # The user for whom we cache
3951: my $cachedkey='';
3952: # The cached times for this user
3953: my %cachedtimes=();
3954: # When this was last done
3955: my $cachedtime=();
3956:
3957: sub load_all_first_access {
1.1154 raeburn 3958: my ($uname,$udom)=@_;
1.1156 www 3959: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 3960: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 3961: return;
3962: }
3963: $cachedtime=time;
3964: $cachedkey=$uname.':'.$udom;
3965: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 3966: }
3967:
1.504 albertel 3968: sub get_first_access {
1.1162 raeburn 3969: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 3970: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3971: if ($argsymb) { $symb=$argsymb; }
3972: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 3973: if ($argmap) { $map = $argmap; }
1.926 albertel 3974: if ($type eq 'course') {
3975: $res='course';
3976: } elsif ($type eq 'map') {
1.588 albertel 3977: $res=&symbread($map);
3978: } else {
3979: $res=$symb;
3980: }
1.1153 www 3981: &load_all_first_access($uname,$udom);
3982: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 3983: }
3984:
3985: sub set_first_access {
1.1162 raeburn 3986: my ($type,$interval)=@_;
1.790 albertel 3987: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3988: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3989: if ($type eq 'course') {
3990: $res='course';
3991: } elsif ($type eq 'map') {
1.588 albertel 3992: $res=&symbread($map);
3993: } else {
3994: $res=$symb;
3995: }
1.1153 www 3996: $cachedkey='';
1.1162 raeburn 3997: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 3998: if (!$firstaccess) {
1.1162 raeburn 3999: my $start = time;
4000: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4001: $udom,$uname);
4002: if ($putres eq 'ok') {
4003: &put('timerinterval',{"$courseid\0$res"=>$interval},
4004: $udom,$uname);
4005: &appenv(
4006: {
4007: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4008: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4009: }
4010: );
4011: }
4012: return $putres;
1.505 albertel 4013: }
4014: return 'already_set';
1.504 albertel 4015: }
1.1153 www 4016: }
1.110 www 4017: # --------------------------------------------- Set Expire Date for Spreadsheet
4018:
4019: sub expirespread {
4020: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4021: my $cid=$env{'request.course.id'};
1.110 www 4022: if ($cid) {
4023: my $now=time;
4024: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4025: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4026: $env{'course.'.$cid.'.num'}.
1.110 www 4027: ':nohist_expirationdates:'.
4028: &escape($key).'='.$now,
1.620 albertel 4029: $env{'course.'.$cid.'.home'})
1.110 www 4030: }
4031: return 'ok';
1.14 www 4032: }
4033:
1.109 www 4034: # ----------------------------------------------------- Devalidate Spreadsheets
4035:
4036: sub devalidate {
1.325 www 4037: my ($symb,$uname,$udom)=@_;
1.620 albertel 4038: my $cid=$env{'request.course.id'};
1.109 www 4039: if ($cid) {
1.391 matthew 4040: # delete the stored spreadsheets for
4041: # - the student level sheet of this user in course's homespace
4042: # - the assessment level sheet for this resource
4043: # for this user in user's homespace
1.553 albertel 4044: # - current conditional state info
1.325 www 4045: my $key=$uname.':'.$udom.':';
1.109 www 4046: my $status=
1.299 matthew 4047: &del('nohist_calculatedsheets',
1.391 matthew 4048: [$key.'studentcalc:'],
1.620 albertel 4049: $env{'course.'.$cid.'.domain'},
4050: $env{'course.'.$cid.'.num'})
1.133 albertel 4051: .' '.
4052: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4053: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4054: unless ($status eq 'ok ok') {
4055: &logthis('Could not devalidate spreadsheet '.
1.325 www 4056: $uname.' at '.$udom.' for '.
1.109 www 4057: $symb.': '.$status);
1.133 albertel 4058: }
1.553 albertel 4059: &delenv('user.state.'.$cid);
1.109 www 4060: }
4061: }
4062:
1.265 albertel 4063: sub get_scalar {
4064: my ($string,$end) = @_;
4065: my $value;
4066: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4067: $value = $1;
4068: } elsif ($$string =~ s/^([^&]*?)&//) {
4069: $value = $1;
4070: }
4071: return &unescape($value);
4072: }
4073:
4074: sub array2str {
4075: my (@array) = @_;
4076: my $result=&arrayref2str(\@array);
4077: $result=~s/^__ARRAY_REF__//;
4078: $result=~s/__END_ARRAY_REF__$//;
4079: return $result;
4080: }
4081:
1.204 albertel 4082: sub arrayref2str {
4083: my ($arrayref) = @_;
1.265 albertel 4084: my $result='__ARRAY_REF__';
1.204 albertel 4085: foreach my $elem (@$arrayref) {
1.265 albertel 4086: if(ref($elem) eq 'ARRAY') {
4087: $result.=&arrayref2str($elem).'&';
4088: } elsif(ref($elem) eq 'HASH') {
4089: $result.=&hashref2str($elem).'&';
4090: } elsif(ref($elem)) {
4091: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4092: } else {
4093: $result.=&escape($elem).'&';
4094: }
4095: }
4096: $result=~s/\&$//;
1.265 albertel 4097: $result .= '__END_ARRAY_REF__';
1.204 albertel 4098: return $result;
4099: }
4100:
1.168 albertel 4101: sub hash2str {
1.204 albertel 4102: my (%hash) = @_;
4103: my $result=&hashref2str(\%hash);
1.265 albertel 4104: $result=~s/^__HASH_REF__//;
4105: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4106: return $result;
4107: }
4108:
4109: sub hashref2str {
4110: my ($hashref)=@_;
1.265 albertel 4111: my $result='__HASH_REF__';
1.800 albertel 4112: foreach my $key (sort(keys(%$hashref))) {
4113: if (ref($key) eq 'ARRAY') {
4114: $result.=&arrayref2str($key).'=';
4115: } elsif (ref($key) eq 'HASH') {
4116: $result.=&hashref2str($key).'=';
4117: } elsif (ref($key)) {
1.265 albertel 4118: $result.='=';
1.800 albertel 4119: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4120: } else {
1.1132 raeburn 4121: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4122: }
4123:
1.800 albertel 4124: if(ref($hashref->{$key}) eq 'ARRAY') {
4125: $result.=&arrayref2str($hashref->{$key}).'&';
4126: } elsif(ref($hashref->{$key}) eq 'HASH') {
4127: $result.=&hashref2str($hashref->{$key}).'&';
4128: } elsif(ref($hashref->{$key})) {
1.265 albertel 4129: $result.='&';
1.800 albertel 4130: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4131: } else {
1.800 albertel 4132: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4133: }
4134: }
1.168 albertel 4135: $result=~s/\&$//;
1.265 albertel 4136: $result .= '__END_HASH_REF__';
1.168 albertel 4137: return $result;
4138: }
4139:
4140: sub str2hash {
1.265 albertel 4141: my ($string)=@_;
4142: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4143: return %$hash;
4144: }
4145:
4146: sub str2hashref {
1.168 albertel 4147: my ($string) = @_;
1.265 albertel 4148:
4149: my %hash;
4150:
4151: if($string !~ /^__HASH_REF__/) {
4152: if (! ($string eq '' || !defined($string))) {
4153: $hash{'error'}='Not hash reference';
4154: }
4155: return (\%hash, $string);
4156: }
4157:
4158: $string =~ s/^__HASH_REF__//;
4159:
4160: while($string !~ /^__END_HASH_REF__/) {
4161: #key
4162: my $key='';
4163: if($string =~ /^__HASH_REF__/) {
4164: ($key, $string)=&str2hashref($string);
4165: if(defined($key->{'error'})) {
4166: $hash{'error'}='Bad data';
4167: return (\%hash, $string);
4168: }
4169: } elsif($string =~ /^__ARRAY_REF__/) {
4170: ($key, $string)=&str2arrayref($string);
4171: if($key->[0] eq 'Array reference error') {
4172: $hash{'error'}='Bad data';
4173: return (\%hash, $string);
4174: }
4175: } else {
4176: $string =~ s/^(.*?)=//;
1.267 albertel 4177: $key=&unescape($1);
1.265 albertel 4178: }
4179: $string =~ s/^=//;
4180:
4181: #value
4182: my $value='';
4183: if($string =~ /^__HASH_REF__/) {
4184: ($value, $string)=&str2hashref($string);
4185: if(defined($value->{'error'})) {
4186: $hash{'error'}='Bad data';
4187: return (\%hash, $string);
4188: }
4189: } elsif($string =~ /^__ARRAY_REF__/) {
4190: ($value, $string)=&str2arrayref($string);
4191: if($value->[0] eq 'Array reference error') {
4192: $hash{'error'}='Bad data';
4193: return (\%hash, $string);
4194: }
4195: } else {
4196: $value=&get_scalar(\$string,'__END_HASH_REF__');
4197: }
4198: $string =~ s/^&//;
4199:
4200: $hash{$key}=$value;
1.204 albertel 4201: }
1.265 albertel 4202:
4203: $string =~ s/^__END_HASH_REF__//;
4204:
4205: return (\%hash, $string);
1.204 albertel 4206: }
4207:
4208: sub str2array {
1.265 albertel 4209: my ($string)=@_;
4210: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4211: return @$array;
4212: }
4213:
4214: sub str2arrayref {
1.204 albertel 4215: my ($string) = @_;
1.265 albertel 4216: my @array;
4217:
4218: if($string !~ /^__ARRAY_REF__/) {
4219: if (! ($string eq '' || !defined($string))) {
4220: $array[0]='Array reference error';
4221: }
4222: return (\@array, $string);
4223: }
4224:
4225: $string =~ s/^__ARRAY_REF__//;
4226:
4227: while($string !~ /^__END_ARRAY_REF__/) {
4228: my $value='';
4229: if($string =~ /^__HASH_REF__/) {
4230: ($value, $string)=&str2hashref($string);
4231: if(defined($value->{'error'})) {
4232: $array[0] ='Array reference error';
4233: return (\@array, $string);
4234: }
4235: } elsif($string =~ /^__ARRAY_REF__/) {
4236: ($value, $string)=&str2arrayref($string);
4237: if($value->[0] eq 'Array reference error') {
4238: $array[0] ='Array reference error';
4239: return (\@array, $string);
4240: }
4241: } else {
4242: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4243: }
4244: $string =~ s/^&//;
4245:
4246: push(@array, $value);
1.191 harris41 4247: }
1.265 albertel 4248:
4249: $string =~ s/^__END_ARRAY_REF__//;
4250:
4251: return (\@array, $string);
1.168 albertel 4252: }
4253:
1.167 albertel 4254: # -------------------------------------------------------------------Temp Store
4255:
1.168 albertel 4256: sub tmpreset {
4257: my ($symb,$namespace,$domain,$stuname) = @_;
4258: if (!$symb) {
4259: $symb=&symbread();
1.620 albertel 4260: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4261: }
4262: $symb=escape($symb);
4263:
1.620 albertel 4264: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4265: $namespace=~s/\//\_/g;
4266: $namespace=~s/\W//g;
4267:
1.620 albertel 4268: if (!$domain) { $domain=$env{'user.domain'}; }
4269: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4270: if ($domain eq 'public' && $stuname eq 'public') {
4271: $stuname=$ENV{'REMOTE_ADDR'};
4272: }
1.1117 foxr 4273: my $path=LONCAPA::tempdir();
1.168 albertel 4274: my %hash;
4275: if (tie(%hash,'GDBM_File',
4276: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4277: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4278: foreach my $key (keys(%hash)) {
1.180 albertel 4279: if ($key=~ /:$symb/) {
1.168 albertel 4280: delete($hash{$key});
4281: }
4282: }
4283: }
4284: }
4285:
1.167 albertel 4286: sub tmpstore {
1.168 albertel 4287: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4288:
4289: if (!$symb) {
4290: $symb=&symbread();
1.620 albertel 4291: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4292: }
4293: $symb=escape($symb);
4294:
4295: if (!$namespace) {
4296: # I don't think we would ever want to store this for a course.
4297: # it seems this will only be used if we don't have a course.
1.620 albertel 4298: #$namespace=$env{'request.course.id'};
1.168 albertel 4299: #if (!$namespace) {
1.620 albertel 4300: $namespace=$env{'request.state'};
1.168 albertel 4301: #}
4302: }
4303: $namespace=~s/\//\_/g;
4304: $namespace=~s/\W//g;
1.620 albertel 4305: if (!$domain) { $domain=$env{'user.domain'}; }
4306: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4307: if ($domain eq 'public' && $stuname eq 'public') {
4308: $stuname=$ENV{'REMOTE_ADDR'};
4309: }
1.168 albertel 4310: my $now=time;
4311: my %hash;
1.1117 foxr 4312: my $path=LONCAPA::tempdir();
1.168 albertel 4313: if (tie(%hash,'GDBM_File',
4314: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4315: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4316: $hash{"version:$symb"}++;
4317: my $version=$hash{"version:$symb"};
4318: my $allkeys='';
4319: foreach my $key (keys(%$storehash)) {
4320: $allkeys.=$key.':';
1.591 albertel 4321: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4322: }
4323: $hash{"$version:$symb:timestamp"}=$now;
4324: $allkeys.='timestamp';
4325: $hash{"$version:keys:$symb"}=$allkeys;
4326: if (untie(%hash)) {
4327: return 'ok';
4328: } else {
4329: return "error:$!";
4330: }
4331: } else {
4332: return "error:$!";
4333: }
4334: }
1.167 albertel 4335:
1.168 albertel 4336: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4337:
1.168 albertel 4338: sub tmprestore {
4339: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4340:
1.168 albertel 4341: if (!$symb) {
4342: $symb=&symbread();
1.620 albertel 4343: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4344: }
4345: $symb=escape($symb);
4346:
1.620 albertel 4347: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4348:
1.620 albertel 4349: if (!$domain) { $domain=$env{'user.domain'}; }
4350: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4351: if ($domain eq 'public' && $stuname eq 'public') {
4352: $stuname=$ENV{'REMOTE_ADDR'};
4353: }
1.168 albertel 4354: my %returnhash;
4355: $namespace=~s/\//\_/g;
4356: $namespace=~s/\W//g;
4357: my %hash;
1.1117 foxr 4358: my $path=LONCAPA::tempdir();
1.168 albertel 4359: if (tie(%hash,'GDBM_File',
4360: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4361: &GDBM_READER(),0640)) {
1.168 albertel 4362: my $version=$hash{"version:$symb"};
4363: $returnhash{'version'}=$version;
4364: my $scope;
4365: for ($scope=1;$scope<=$version;$scope++) {
4366: my $vkeys=$hash{"$scope:keys:$symb"};
4367: my @keys=split(/:/,$vkeys);
4368: my $key;
4369: $returnhash{"$scope:keys"}=$vkeys;
4370: foreach $key (@keys) {
1.591 albertel 4371: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4372: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4373: }
4374: }
1.168 albertel 4375: if (!(untie(%hash))) {
4376: return "error:$!";
4377: }
4378: } else {
4379: return "error:$!";
4380: }
4381: return %returnhash;
1.167 albertel 4382: }
4383:
1.9 www 4384: # ----------------------------------------------------------------------- Store
4385:
4386: sub store {
1.124 www 4387: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4388: my $home='';
4389:
1.168 albertel 4390: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4391:
1.213 www 4392: $symb=&symbclean($symb);
1.122 albertel 4393: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4394:
1.620 albertel 4395: if (!$domain) { $domain=$env{'user.domain'}; }
4396: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4397:
4398: &devalidate($symb,$stuname,$domain);
1.109 www 4399:
4400: $symb=escape($symb);
1.187 www 4401: if (!$namespace) {
1.620 albertel 4402: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4403: return '';
4404: }
4405: }
1.620 albertel 4406: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4407:
4408: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4409: $$storehash{'host'}=$perlvar{'lonHostID'};
4410:
1.12 www 4411: my $namevalue='';
1.800 albertel 4412: foreach my $key (keys(%$storehash)) {
4413: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4414: }
1.12 www 4415: $namevalue=~s/\&$//;
1.187 www 4416: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4417: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4418: }
4419:
1.47 www 4420: # -------------------------------------------------------------- Critical Store
4421:
4422: sub cstore {
1.124 www 4423: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4424: my $home='';
4425:
1.168 albertel 4426: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4427:
1.213 www 4428: $symb=&symbclean($symb);
1.122 albertel 4429: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4430:
1.620 albertel 4431: if (!$domain) { $domain=$env{'user.domain'}; }
4432: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4433:
4434: &devalidate($symb,$stuname,$domain);
1.109 www 4435:
4436: $symb=escape($symb);
1.187 www 4437: if (!$namespace) {
1.620 albertel 4438: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4439: return '';
4440: }
4441: }
1.620 albertel 4442: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4443:
4444: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4445: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4446:
1.47 www 4447: my $namevalue='';
1.800 albertel 4448: foreach my $key (keys(%$storehash)) {
4449: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4450: }
1.47 www 4451: $namevalue=~s/\&$//;
1.187 www 4452: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4453: return critical
4454: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4455: }
4456:
1.9 www 4457: # --------------------------------------------------------------------- Restore
4458:
4459: sub restore {
1.124 www 4460: my ($symb,$namespace,$domain,$stuname) = @_;
4461: my $home='';
4462:
1.168 albertel 4463: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4464:
1.122 albertel 4465: if (!$symb) {
4466: unless ($symb=escape(&symbread())) { return ''; }
4467: } else {
1.213 www 4468: $symb=&escape(&symbclean($symb));
1.122 albertel 4469: }
1.188 www 4470: if (!$namespace) {
1.620 albertel 4471: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4472: return '';
4473: }
4474: }
1.620 albertel 4475: if (!$domain) { $domain=$env{'user.domain'}; }
4476: if (!$stuname) { $stuname=$env{'user.name'}; }
4477: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4478: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4479:
1.12 www 4480: my %returnhash=();
1.800 albertel 4481: foreach my $line (split(/\&/,$answer)) {
4482: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4483: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4484: }
1.75 www 4485: my $version;
4486: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4487: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4488: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4489: }
1.75 www 4490: }
1.13 www 4491: return %returnhash;
1.34 www 4492: }
4493:
4494: # ---------------------------------------------------------- Course Description
1.1118 foxr 4495: #
4496: #
1.34 www 4497:
4498: sub coursedescription {
1.731 albertel 4499: my ($courseid,$args)=@_;
1.34 www 4500: $courseid=~s/^\///;
1.49 www 4501: $courseid=~s/\_/\//g;
1.34 www 4502: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4503: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4504: my $normalid=$cdomain.'_'.$cnum;
4505: # need to always cache even if we get errors otherwise we keep
4506: # trying and trying and trying to get the course description.
4507: my %envhash=();
4508: my %returnhash=();
1.731 albertel 4509:
4510: my $expiretime=600;
4511: if ($env{'request.course.id'} eq $normalid) {
4512: $expiretime=120;
4513: }
4514:
4515: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4516: if (!$args->{'freshen_cache'}
4517: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4518: foreach my $key (keys(%env)) {
4519: next if ($key !~ /^\Q$prefix\E(.*)/);
4520: my ($setting) = $1;
4521: $returnhash{$setting} = $env{$key};
4522: }
4523: return %returnhash;
4524: }
4525:
1.1118 foxr 4526: # get the data again
4527:
1.731 albertel 4528: if (!$args->{'one_time'}) {
4529: $envhash{'course.'.$normalid.'.last_cache'}=time;
4530: }
1.811 albertel 4531:
1.34 www 4532: if ($chome ne 'no_host') {
1.302 albertel 4533: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4534: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4535: my $username = $env{'user.name'}; # Defult username
4536: if(defined $args->{'user'}) {
4537: $username = $args->{'user'};
4538: }
1.129 albertel 4539: $returnhash{'home'}= $chome;
4540: $returnhash{'domain'} = $cdomain;
4541: $returnhash{'num'} = $cnum;
1.741 raeburn 4542: if (!defined($returnhash{'type'})) {
4543: $returnhash{'type'} = 'Course';
4544: }
1.130 albertel 4545: while (my ($name,$value) = each %returnhash) {
1.53 www 4546: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4547: }
1.270 www 4548: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4549: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4550: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4551: $envhash{'course.'.$normalid.'.home'}=$chome;
4552: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4553: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4554: }
4555: }
1.731 albertel 4556: if (!$args->{'one_time'}) {
1.949 raeburn 4557: &appenv(\%envhash);
1.731 albertel 4558: }
1.302 albertel 4559: return %returnhash;
1.461 www 4560: }
4561:
1.1080 raeburn 4562: sub update_released_required {
4563: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4564: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4565: $cid = $env{'request.course.id'};
4566: $cdom = $env{'course.'.$cid.'.domain'};
4567: $cnum = $env{'course.'.$cid.'.num'};
4568: $chome = $env{'course.'.$cid.'.home'};
4569: }
4570: if ($needsrelease) {
4571: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4572: my $needsupdate;
4573: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4574: $needsupdate = 1;
4575: } else {
4576: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4577: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4578: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4579: $needsupdate = 1;
4580: }
4581: }
4582: if ($needsupdate) {
4583: my %needshash = (
4584: 'internal.releaserequired' => $needsrelease,
4585: );
4586: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4587: if ($putresult eq 'ok') {
4588: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4589: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4590: if (ref($crsinfo{$cid}) eq 'HASH') {
4591: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4592: &courseidput($cdom,\%crsinfo,$chome,'notime');
4593: }
4594: }
4595: }
4596: }
4597: return;
4598: }
4599:
1.461 www 4600: # -------------------------------------------------See if a user is privileged
4601:
4602: sub privileged {
4603: my ($username,$domain)=@_;
1.1170 droeschl 4604:
4605: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4606: my $now = time;
4607:
4608: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4609: my ($trole, $tend, $tstart) = split(/_/, $role);
4610: if (($trole eq 'dc') || ($trole eq 'su')) {
4611: return 1 unless ($tend && $tend < $now)
4612: or ($tstart && $tstart > $now);
4613: }
1.461 www 4614: }
1.1170 droeschl 4615:
1.461 www 4616: return 0;
1.9 www 4617: }
1.1 albertel 4618:
1.103 harris41 4619: # -------------------------------------------------------- Get user privileges
1.11 www 4620:
4621: sub rolesinit {
1.1169 droeschl 4622: my ($domain, $username) = @_;
4623: my %userroles = ('user.login.time' => time);
4624: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4625:
4626: # firstaccess and timerinterval are related to timed maps/resources.
4627: # also, blocking can be triggered by an activating timer
4628: # it's saved in the user's %env.
4629: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4630: my %timerinterval = &dump('timerinterval', $domain, $username);
4631: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4632: %timerintchk, %timerintenv);
4633:
1.1162 raeburn 4634: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4635: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4636: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4637: }
1.1169 droeschl 4638:
1.1162 raeburn 4639: foreach my $key (keys(%timerinterval)) {
4640: my ($cid,$rest) = split(/\0/,$key);
4641: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4642: }
1.1169 droeschl 4643:
1.11 www 4644: my %allroles=();
1.1162 raeburn 4645: my %allgroups=();
1.11 www 4646:
1.1169 droeschl 4647: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4648: my $role = $rolesdump{$area};
4649: $area =~ s/\_\w\w$//;
4650:
4651: my ($trole, $tend, $tstart, $group_privs);
4652:
4653: if ($role =~ /^cr/) {
4654: # Custom role, defined by a user
4655: # e.g., user.role.cr/msu/smith/mynewrole
4656: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4657: $trole = $1;
4658: ($tend, $tstart) = split('_', $2);
4659: } else {
4660: $trole = $role;
4661: }
4662: } elsif ($role =~ m|^gr/|) {
4663: # Role of member in a group, defined within a course/community
4664: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4665: ($trole, $tend, $tstart) = split(/_/, $role);
4666: next if $tstart eq '-1';
4667: ($trole, $group_privs) = split(/\//, $trole);
4668: $group_privs = &unescape($group_privs);
4669: } else {
4670: # Just a normal role, defined in roles.tab
4671: ($trole, $tend, $tstart) = split(/_/,$role);
4672: }
4673:
4674: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4675: $username);
4676: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4677:
4678: # role expired or not available yet?
4679: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4680: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4681:
4682: next if $area eq '' or $trole eq '';
4683:
4684: my $spec = "$trole.$area";
4685: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4686:
4687: if ($trole =~ /^cr\//) {
4688: # Custom role, defined by a user
4689: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4690: } elsif ($trole eq 'gr') {
4691: # Role of a member in a group, defined within a course/community
4692: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4693: next;
4694: } else {
4695: # Normal role, defined in roles.tab
4696: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4697: }
4698:
4699: my $cid = $tdomain.'_'.$trest;
4700: unless ($firstaccchk{$cid}) {
4701: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4702: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4703: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4704: $coursetimerstarts{$cid}{$item};
4705: }
4706: }
4707: $firstaccchk{$cid} = 1;
4708: }
4709: unless ($timerintchk{$cid}) {
4710: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4711: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4712: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4713: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4714: }
1.12 www 4715: }
1.1169 droeschl 4716: $timerintchk{$cid} = 1;
1.191 harris41 4717: }
1.11 www 4718: }
1.1169 droeschl 4719:
4720: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4721: \%allroles, \%allgroups);
4722: $env{'user.adv'} = $userroles{'user.adv'};
4723:
1.1162 raeburn 4724: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4725: }
4726:
1.567 raeburn 4727: sub set_arearole {
4728: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4729: # log the associated role with the area
4730: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4731: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4732: }
4733:
4734: sub custom_roleprivs {
4735: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4736: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4737: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4738: if (&hostname($homsvr) ne '') {
1.567 raeburn 4739: my ($rdummy,$roledef)=
4740: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4741: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4742: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4743: if (defined($syspriv)) {
1.1043 raeburn 4744: if ($trest =~ /^$match_community$/) {
4745: $syspriv =~ s/bre\&S//;
4746: }
1.567 raeburn 4747: $$allroles{'cm./'}.=':'.$syspriv;
4748: $$allroles{$spec.'./'}.=':'.$syspriv;
4749: }
4750: if ($tdomain ne '') {
4751: if (defined($dompriv)) {
4752: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4753: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4754: }
4755: if (($trest ne '') && (defined($coursepriv))) {
4756: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4757: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4758: }
4759: }
4760: }
4761: }
4762: }
4763:
1.678 raeburn 4764: sub group_roleprivs {
4765: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4766: my $access = 1;
4767: my $now = time;
4768: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4769: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4770: if ($access) {
1.811 albertel 4771: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4772: $$allgroups{$course}{$group} .=':'.$group_privs;
4773: }
4774: }
1.567 raeburn 4775:
4776: sub standard_roleprivs {
4777: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4778: if (defined($pr{$trole.':s'})) {
4779: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4780: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4781: }
4782: if ($tdomain ne '') {
4783: if (defined($pr{$trole.':d'})) {
4784: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4785: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4786: }
4787: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4788: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4789: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4790: }
4791: }
4792: }
4793:
4794: sub set_userprivs {
1.1064 raeburn 4795: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4796: my $author=0;
4797: my $adv=0;
1.678 raeburn 4798: my %grouproles = ();
4799: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4800: my @groupkeys;
1.1000 raeburn 4801: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4802: push(@groupkeys,$role);
4803: }
4804: if (ref($groups_roles) eq 'HASH') {
4805: foreach my $key (keys(%{$groups_roles})) {
4806: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4807: push(@groupkeys,$key);
4808: }
4809: }
4810: }
4811: if (@groupkeys > 0) {
4812: foreach my $role (@groupkeys) {
4813: my ($trole,$area,$sec,$extendedarea);
4814: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4815: $trole = $1;
4816: $area = $2;
4817: $sec = $3;
4818: $extendedarea = $area.$sec;
4819: if (exists($$allgroups{$area})) {
4820: foreach my $group (keys(%{$$allgroups{$area}})) {
4821: my $spec = $trole.'.'.$extendedarea;
4822: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4823: $$allgroups{$area}{$group};
1.1064 raeburn 4824: }
1.678 raeburn 4825: }
4826: }
4827: }
4828: }
4829: }
1.800 albertel 4830: foreach my $group (keys(%grouproles)) {
4831: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4832: }
1.800 albertel 4833: foreach my $role (keys(%{$allroles})) {
4834: my %thesepriv;
1.941 raeburn 4835: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4836: foreach my $item (split(/:/,$$allroles{$role})) {
4837: if ($item ne '') {
4838: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4839: if ($restrictions eq '') {
4840: $thesepriv{$privilege}='F';
4841: } elsif ($thesepriv{$privilege} ne 'F') {
4842: $thesepriv{$privilege}.=$restrictions;
4843: }
4844: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4845: }
4846: }
4847: my $thesestr='';
1.1104 raeburn 4848: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4849: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4850: }
4851: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4852: }
4853: return ($author,$adv);
4854: }
4855:
1.994 raeburn 4856: sub role_status {
1.1104 raeburn 4857: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4858: my @pwhere = ();
4859: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4860: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4861: unless (!defined($$role) || $$role eq '') {
4862: $$where=join('.',@pwhere);
4863: $$trolecode=$$role.'.'.$$where;
4864: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4865: $$tstatus='is';
1.1104 raeburn 4866: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4867: $$tstatus='future';
1.1034 raeburn 4868: if ($$tstart<$now) {
4869: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4870: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4871: my (%allroles,%allgroups,$group_privs,
4872: %groups_roles,@rolecodes);
1.1002 raeburn 4873: my %userroles = (
4874: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4875: );
1.1064 raeburn 4876: @rolecodes = ('cm');
1.1002 raeburn 4877: my $spec=$$role.'.'.$$where;
4878: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4879: if ($$role =~ /^cr\//) {
4880: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4881: push(@rolecodes,'cr');
1.1002 raeburn 4882: } elsif ($$role eq 'gr') {
1.1064 raeburn 4883: push(@rolecodes,$$role);
1.1002 raeburn 4884: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4885: $env{'user.name'});
1.1064 raeburn 4886: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4887: (undef,my $group_privs) = split(/\//,$trole);
4888: $group_privs = &unescape($group_privs);
4889: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4890: 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 4891: &get_groups_roles($tdomain,$trest,
4892: \%course_roles,\@rolecodes,
4893: \%groups_roles);
1.1002 raeburn 4894: } else {
1.1064 raeburn 4895: push(@rolecodes,$$role);
1.1002 raeburn 4896: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4897: }
1.1064 raeburn 4898: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4899: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4900: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4901: }
4902: }
1.1034 raeburn 4903: $$tstatus = 'is';
1.1002 raeburn 4904: }
1.994 raeburn 4905: }
4906: if ($$tend) {
1.1104 raeburn 4907: if ($$tend<$update) {
1.994 raeburn 4908: $$tstatus='expired';
4909: } elsif ($$tend<$now) {
4910: $$tstatus='will_not';
4911: }
4912: }
4913: }
4914: }
4915: }
4916:
1.1104 raeburn 4917: sub get_groups_roles {
4918: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4919: return unless((ref($cdom_courseroles) eq 'HASH') &&
4920: (ref($rolecodes) eq 'ARRAY') &&
4921: (ref($groups_roles) eq 'HASH'));
4922: if (keys(%{$cdom_courseroles}) > 0) {
4923: my ($cnum) = ($rest =~ /^($match_courseid)/);
4924: if ($cdom ne '' && $cnum ne '') {
4925: foreach my $key (keys(%{$cdom_courseroles})) {
4926: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4927: my $crsrole = $1;
4928: my $crssec = $2;
4929: if ($crsrole =~ /^cr/) {
4930: unless (grep(/^cr$/,@{$rolecodes})) {
4931: push(@{$rolecodes},'cr');
4932: }
4933: } else {
4934: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4935: push(@{$rolecodes},$crsrole);
4936: }
4937: }
4938: my $rolekey = "$crsrole./$cdom/$cnum";
4939: if ($crssec ne '') {
4940: $rolekey .= "/$crssec";
4941: }
4942: $rolekey .= './';
4943: $groups_roles->{$rolekey} = $rolecodes;
4944: }
4945: }
4946: }
4947: }
4948: return;
4949: }
4950:
4951: sub delete_env_groupprivs {
4952: my ($where,$courseroles,$possroles) = @_;
4953: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4954: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4955: unless (ref($courseroles->{$udom}) eq 'HASH') {
4956: %{$courseroles->{$udom}} =
4957: &get_my_roles('','','userroles',['active'],
4958: $possroles,[$udom],1);
4959: }
4960: if (ref($courseroles->{$udom}) eq 'HASH') {
4961: foreach my $item (keys(%{$courseroles->{$udom}})) {
4962: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4963: my $area = '/'.$cdom.'/'.$cnum;
4964: my $privkey = "user.priv.$crsrole.$area";
4965: if ($crssec ne '') {
4966: $privkey .= '/'.$crssec;
4967: }
4968: $privkey .= ".$area/$group";
4969: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4970: }
4971: }
4972: return;
4973: }
4974:
1.994 raeburn 4975: sub check_adhoc_privs {
1.1104 raeburn 4976: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4977: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4978: if ($env{$cckey}) {
4979: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4980: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4981: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4982: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4983: }
4984: } else {
1.1088 raeburn 4985: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4986: }
4987: }
4988:
4989: sub set_adhoc_privileges {
4990: # role can be cc or ca
1.1088 raeburn 4991: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4992: my $area = '/'.$dcdom.'/'.$pickedcourse;
4993: my $spec = $role.'.'.$area;
4994: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4995: $env{'user.name'});
4996: my %ccrole = ();
4997: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4998: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4999: &appenv(\%userroles,[$role,'cm']);
5000: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5001: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5002: &appenv( {'request.role' => $spec,
5003: 'request.role.domain' => $dcdom,
5004: 'request.course.sec' => ''
5005: }
5006: );
5007: my $tadv=0;
5008: if (&allowed('adv') eq 'F') { $tadv=1; }
5009: &appenv({'request.role.adv' => $tadv});
5010: }
1.994 raeburn 5011: }
5012:
1.12 www 5013: # --------------------------------------------------------------- get interface
5014:
5015: sub get {
1.131 albertel 5016: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5017: my $items='';
1.800 albertel 5018: foreach my $item (@$storearr) {
5019: $items.=&escape($item).'&';
1.191 harris41 5020: }
1.12 www 5021: $items=~s/\&$//;
1.620 albertel 5022: if (!$udomain) { $udomain=$env{'user.domain'}; }
5023: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5024: my $uhome=&homeserver($uname,$udomain);
5025:
1.133 albertel 5026: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5027: my @pairs=split(/\&/,$rep);
1.273 albertel 5028: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5029: return @pairs;
5030: }
1.15 www 5031: my %returnhash=();
1.42 www 5032: my $i=0;
1.800 albertel 5033: foreach my $item (@$storearr) {
5034: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5035: $i++;
1.191 harris41 5036: }
1.15 www 5037: return %returnhash;
1.27 www 5038: }
5039:
5040: # --------------------------------------------------------------- del interface
5041:
5042: sub del {
1.133 albertel 5043: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5044: my $items='';
1.800 albertel 5045: foreach my $item (@$storearr) {
5046: $items.=&escape($item).'&';
1.191 harris41 5047: }
1.984 neumanie 5048:
1.27 www 5049: $items=~s/\&$//;
1.620 albertel 5050: if (!$udomain) { $udomain=$env{'user.domain'}; }
5051: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5052: my $uhome=&homeserver($uname,$udomain);
5053: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5054: }
5055:
5056: # -------------------------------------------------------------- dump interface
5057:
5058: sub dump {
1.1166 raeburn 5059: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755 albertel 5060: if (!$udomain) { $udomain=$env{'user.domain'}; }
5061: if (!$uname) { $uname=$env{'user.name'}; }
5062: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5063:
1.755 albertel 5064: if ($regexp) {
5065: $regexp=&escape($regexp);
5066: } else {
5067: $regexp='.';
5068: }
1.1166 raeburn 5069: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5070: my @pairs=split(/\&/,$rep);
5071: my %returnhash=();
1.1098 foxr 5072: if (!($rep =~ /^error/ )) {
5073: foreach my $item (@pairs) {
5074: my ($key,$value)=split(/=/,$item,2);
5075: $key = &unescape($key);
5076: next if ($key =~ /^error: 2 /);
5077: $returnhash{$key}=&thaw_unescape($value);
5078: }
1.755 albertel 5079: }
5080: return %returnhash;
1.407 www 5081: }
5082:
1.1098 foxr 5083:
1.717 albertel 5084: # --------------------------------------------------------- dumpstore interface
5085:
5086: sub dumpstore {
5087: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5088: if (!$udomain) { $udomain=$env{'user.domain'}; }
5089: if (!$uname) { $uname=$env{'user.name'}; }
5090: my $uhome=&homeserver($uname,$udomain);
5091: if ($regexp) {
5092: $regexp=&escape($regexp);
5093: } else {
5094: $regexp='.';
5095: }
5096: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5097: my @pairs=split(/\&/,$rep);
5098: my %returnhash=();
5099: foreach my $item (@pairs) {
5100: my ($key,$value)=split(/=/,$item,2);
5101: next if ($key =~ /^error: 2 /);
5102: $returnhash{$key}=&thaw_unescape($value);
5103: }
5104: return %returnhash;
1.717 albertel 5105: }
5106:
1.407 www 5107: # -------------------------------------------------------------- keys interface
5108:
5109: sub getkeys {
5110: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5111: if (!$udomain) { $udomain=$env{'user.domain'}; }
5112: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5113: my $uhome=&homeserver($uname,$udomain);
5114: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5115: my @keyarray=();
1.800 albertel 5116: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5117: next if ($key =~ /^error: 2 /);
1.800 albertel 5118: push(@keyarray,&unescape($key));
1.407 www 5119: }
5120: return @keyarray;
1.318 matthew 5121: }
5122:
1.319 matthew 5123: # --------------------------------------------------------------- currentdump
5124: sub currentdump {
1.328 matthew 5125: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5126: $courseid = $env{'request.course.id'} if (! defined($courseid));
5127: $sdom = $env{'user.domain'} if (! defined($sdom));
5128: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5129: my $uhome = &homeserver($sname,$sdom);
5130: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5131: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5132: #
1.318 matthew 5133: my %returnhash=();
1.319 matthew 5134: #
5135: if ($rep eq "unknown_cmd") {
5136: # an old lond will not know currentdump
5137: # Do a dump and make it look like a currentdump
1.822 albertel 5138: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5139: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5140: my %hash = @tmp;
5141: @tmp=();
1.424 matthew 5142: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5143: } else {
5144: my @pairs=split(/\&/,$rep);
1.800 albertel 5145: foreach my $pair (@pairs) {
5146: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5147: my ($symb,$param) = split(/:/,$key);
5148: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5149: &thaw_unescape($value);
1.319 matthew 5150: }
1.191 harris41 5151: }
1.12 www 5152: return %returnhash;
1.424 matthew 5153: }
5154:
5155: sub convert_dump_to_currentdump{
5156: my %hash = %{shift()};
5157: my %returnhash;
5158: # Code ripped from lond, essentially. The only difference
5159: # here is the unescaping done by lonnet::dump(). Conceivably
5160: # we might run in to problems with parameter names =~ /^v\./
5161: while (my ($key,$value) = each(%hash)) {
5162: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5163: $symb = &unescape($symb);
5164: $param = &unescape($param);
1.424 matthew 5165: next if ($v eq 'version' || $symb eq 'keys');
5166: next if (exists($returnhash{$symb}) &&
5167: exists($returnhash{$symb}->{$param}) &&
5168: $returnhash{$symb}->{'v.'.$param} > $v);
5169: $returnhash{$symb}->{$param}=$value;
5170: $returnhash{$symb}->{'v.'.$param}=$v;
5171: }
5172: #
5173: # Remove all of the keys in the hashes which keep track of
5174: # the version of the parameter.
5175: while (my ($symb,$param_hash) = each(%returnhash)) {
5176: # use a foreach because we are going to delete from the hash.
5177: foreach my $key (keys(%$param_hash)) {
5178: delete($param_hash->{$key}) if ($key =~ /^v\./);
5179: }
5180: }
5181: return \%returnhash;
1.12 www 5182: }
5183:
1.627 albertel 5184: # ------------------------------------------------------ critical inc interface
5185:
5186: sub cinc {
5187: return &inc(@_,'critical');
5188: }
5189:
1.449 matthew 5190: # --------------------------------------------------------------- inc interface
5191:
5192: sub inc {
1.627 albertel 5193: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5194: if (!$udomain) { $udomain=$env{'user.domain'}; }
5195: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5196: my $uhome=&homeserver($uname,$udomain);
5197: my $items='';
5198: if (! ref($store)) {
5199: # got a single value, so use that instead
5200: $items = &escape($store).'=&';
5201: } elsif (ref($store) eq 'SCALAR') {
5202: $items = &escape($$store).'=&';
5203: } elsif (ref($store) eq 'ARRAY') {
5204: $items = join('=&',map {&escape($_);} @{$store});
5205: } elsif (ref($store) eq 'HASH') {
5206: while (my($key,$value) = each(%{$store})) {
5207: $items.= &escape($key).'='.&escape($value).'&';
5208: }
5209: }
5210: $items=~s/\&$//;
1.627 albertel 5211: if ($critical) {
5212: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5213: } else {
5214: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5215: }
1.449 matthew 5216: }
5217:
1.12 www 5218: # --------------------------------------------------------------- put interface
5219:
5220: sub put {
1.134 albertel 5221: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5222: if (!$udomain) { $udomain=$env{'user.domain'}; }
5223: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5224: my $uhome=&homeserver($uname,$udomain);
1.12 www 5225: my $items='';
1.800 albertel 5226: foreach my $item (keys(%$storehash)) {
5227: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5228: }
1.12 www 5229: $items=~s/\&$//;
1.134 albertel 5230: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5231: }
5232:
1.631 albertel 5233: # ------------------------------------------------------------ newput interface
5234:
5235: sub newput {
5236: my ($namespace,$storehash,$udomain,$uname)=@_;
5237: if (!$udomain) { $udomain=$env{'user.domain'}; }
5238: if (!$uname) { $uname=$env{'user.name'}; }
5239: my $uhome=&homeserver($uname,$udomain);
5240: my $items='';
5241: foreach my $key (keys(%$storehash)) {
5242: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5243: }
5244: $items=~s/\&$//;
5245: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5246: }
5247:
5248: # --------------------------------------------------------- putstore interface
5249:
1.524 raeburn 5250: sub putstore {
1.715 albertel 5251: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5252: if (!$udomain) { $udomain=$env{'user.domain'}; }
5253: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5254: my $uhome=&homeserver($uname,$udomain);
5255: my $items='';
1.715 albertel 5256: foreach my $key (keys(%$storehash)) {
5257: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5258: }
1.715 albertel 5259: $items=~s/\&$//;
1.716 albertel 5260: my $esc_symb=&escape($symb);
5261: my $esc_v=&escape($version);
1.715 albertel 5262: my $reply =
1.716 albertel 5263: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5264: $uhome);
5265: if ($reply eq 'unknown_cmd') {
1.716 albertel 5266: # gfall back to way things use to be done
1.715 albertel 5267: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5268: $uname);
1.524 raeburn 5269: }
1.715 albertel 5270: return $reply;
5271: }
5272:
5273: sub old_putstore {
1.716 albertel 5274: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5275: if (!$udomain) { $udomain=$env{'user.domain'}; }
5276: if (!$uname) { $uname=$env{'user.name'}; }
5277: my $uhome=&homeserver($uname,$udomain);
5278: my %newstorehash;
1.800 albertel 5279: foreach my $item (keys(%$storehash)) {
5280: my $key = $version.':'.&escape($symb).':'.$item;
5281: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5282: }
5283: my $items='';
5284: my %allitems = ();
1.800 albertel 5285: foreach my $item (keys(%newstorehash)) {
5286: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5287: my $key = $1.':keys:'.$2;
5288: $allitems{$key} .= $3.':';
5289: }
1.800 albertel 5290: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5291: }
1.800 albertel 5292: foreach my $item (keys(%allitems)) {
5293: $allitems{$item} =~ s/\:$//;
5294: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5295: }
5296: $items=~s/\&$//;
5297: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5298: }
5299:
1.47 www 5300: # ------------------------------------------------------ critical put interface
5301:
5302: sub cput {
1.134 albertel 5303: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5304: if (!$udomain) { $udomain=$env{'user.domain'}; }
5305: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5306: my $uhome=&homeserver($uname,$udomain);
1.47 www 5307: my $items='';
1.800 albertel 5308: foreach my $item (keys(%$storehash)) {
5309: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5310: }
1.47 www 5311: $items=~s/\&$//;
1.134 albertel 5312: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5313: }
5314:
5315: # -------------------------------------------------------------- eget interface
5316:
5317: sub eget {
1.133 albertel 5318: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5319: my $items='';
1.800 albertel 5320: foreach my $item (@$storearr) {
5321: $items.=&escape($item).'&';
1.191 harris41 5322: }
1.12 www 5323: $items=~s/\&$//;
1.620 albertel 5324: if (!$udomain) { $udomain=$env{'user.domain'}; }
5325: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5326: my $uhome=&homeserver($uname,$udomain);
5327: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5328: my @pairs=split(/\&/,$rep);
5329: my %returnhash=();
1.42 www 5330: my $i=0;
1.800 albertel 5331: foreach my $item (@$storearr) {
5332: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5333: $i++;
1.191 harris41 5334: }
1.12 www 5335: return %returnhash;
5336: }
5337:
1.667 albertel 5338: # ------------------------------------------------------------ tmpput interface
5339: sub tmpput {
1.802 raeburn 5340: my ($storehash,$server,$context)=@_;
1.667 albertel 5341: my $items='';
1.800 albertel 5342: foreach my $item (keys(%$storehash)) {
5343: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5344: }
5345: $items=~s/\&$//;
1.802 raeburn 5346: if (defined($context)) {
5347: $items .= ':'.&escape($context);
5348: }
1.667 albertel 5349: return &reply("tmpput:$items",$server);
5350: }
5351:
5352: # ------------------------------------------------------------ tmpget interface
5353: sub tmpget {
1.688 albertel 5354: my ($token,$server)=@_;
5355: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5356: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5357: my %returnhash;
5358: foreach my $item (split(/\&/,$rep)) {
5359: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5360: next if ($key =~ /^error: 2 /);
1.667 albertel 5361: $returnhash{&unescape($key)}=&thaw_unescape($value);
5362: }
5363: return %returnhash;
5364: }
5365:
1.1113 raeburn 5366: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5367: sub tmpdel {
5368: my ($token,$server)=@_;
5369: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5370: return &reply("tmpdel:$token",$server);
5371: }
5372:
1.765 albertel 5373: # -------------------------------------------------- portfolio access checking
5374:
5375: sub portfolio_access {
1.766 albertel 5376: my ($requrl) = @_;
1.765 albertel 5377: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5378: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5379: if ($result) {
5380: my %setters;
5381: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5382: my ($startblock,$endblock) =
5383: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5384: if ($startblock && $endblock) {
5385: return 'B';
5386: }
5387: } else {
5388: my ($startblock,$endblock) =
5389: &Apache::loncommon::blockcheck(\%setters,'port');
5390: if ($startblock && $endblock) {
5391: return 'B';
5392: }
5393: }
5394: }
1.765 albertel 5395: if ($result eq 'ok') {
1.766 albertel 5396: return 'F';
1.765 albertel 5397: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5398: return 'A';
1.765 albertel 5399: }
1.766 albertel 5400: return '';
1.765 albertel 5401: }
5402:
5403: sub get_portfolio_access {
1.767 albertel 5404: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5405:
5406: if (!ref($access_hash)) {
5407: my $current_perms = &get_portfile_permissions($udom,$unum);
5408: my %access_controls = &get_access_controls($current_perms,$group,
5409: $file_name);
5410: $access_hash = $access_controls{$file_name};
5411: }
5412:
1.765 albertel 5413: my ($public,$guest,@domains,@users,@courses,@groups);
5414: my $now = time;
5415: if (ref($access_hash) eq 'HASH') {
5416: foreach my $key (keys(%{$access_hash})) {
5417: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5418: if ($start > $now) {
5419: next;
5420: }
5421: if ($end && $end<$now) {
5422: next;
5423: }
5424: if ($scope eq 'public') {
5425: $public = $key;
5426: last;
5427: } elsif ($scope eq 'guest') {
5428: $guest = $key;
5429: } elsif ($scope eq 'domains') {
5430: push(@domains,$key);
5431: } elsif ($scope eq 'users') {
5432: push(@users,$key);
5433: } elsif ($scope eq 'course') {
5434: push(@courses,$key);
5435: } elsif ($scope eq 'group') {
5436: push(@groups,$key);
5437: }
5438: }
5439: if ($public) {
5440: return 'ok';
5441: }
5442: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5443: if ($guest) {
5444: return $guest;
5445: }
5446: } else {
5447: if (@domains > 0) {
5448: foreach my $domkey (@domains) {
5449: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5450: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5451: return 'ok';
5452: }
5453: }
5454: }
5455: }
5456: if (@users > 0) {
5457: foreach my $userkey (@users) {
1.865 raeburn 5458: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5459: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5460: if (ref($item) eq 'HASH') {
5461: if (($item->{'uname'} eq $env{'user.name'}) &&
5462: ($item->{'udom'} eq $env{'user.domain'})) {
5463: return 'ok';
5464: }
5465: }
5466: }
5467: }
1.765 albertel 5468: }
5469: }
5470: my %roleshash;
5471: my @courses_and_groups = @courses;
5472: push(@courses_and_groups,@groups);
5473: if (@courses_and_groups > 0) {
5474: my (%allgroups,%allroles);
5475: my ($start,$end,$role,$sec,$group);
5476: foreach my $envkey (%env) {
1.1060 raeburn 5477: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5478: my $cid = $2.'_'.$3;
5479: if ($1 eq 'gr') {
5480: $group = $4;
5481: $allgroups{$cid}{$group} = $env{$envkey};
5482: } else {
5483: if ($4 eq '') {
5484: $sec = 'none';
5485: } else {
5486: $sec = $4;
5487: }
5488: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5489: }
1.811 albertel 5490: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5491: my $cid = $2.'_'.$3;
5492: if ($4 eq '') {
5493: $sec = 'none';
5494: } else {
5495: $sec = $4;
5496: }
5497: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5498: }
5499: }
5500: if (keys(%allroles) == 0) {
5501: return;
5502: }
5503: foreach my $key (@courses_and_groups) {
5504: my %content = %{$$access_hash{$key}};
5505: my $cnum = $content{'number'};
5506: my $cdom = $content{'domain'};
5507: my $cid = $cdom.'_'.$cnum;
5508: if (!exists($allroles{$cid})) {
5509: next;
5510: }
5511: foreach my $role_id (keys(%{$content{'roles'}})) {
5512: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5513: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5514: my @status = @{$content{'roles'}{$role_id}{'access'}};
5515: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5516: foreach my $role (keys(%{$allroles{$cid}})) {
5517: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5518: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5519: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5520: if (grep/^all$/,@sections) {
5521: return 'ok';
5522: } else {
5523: if (grep/^$sec$/,@sections) {
5524: return 'ok';
5525: }
5526: }
5527: }
5528: }
5529: if (keys(%{$allgroups{$cid}}) == 0) {
5530: if (grep/^none$/,@groups) {
5531: return 'ok';
5532: }
5533: } else {
5534: if (grep/^all$/,@groups) {
5535: return 'ok';
5536: }
5537: foreach my $group (keys(%{$allgroups{$cid}})) {
5538: if (grep/^$group$/,@groups) {
5539: return 'ok';
5540: }
5541: }
5542: }
5543: }
5544: }
5545: }
5546: }
5547: }
5548: if ($guest) {
5549: return $guest;
5550: }
5551: }
5552: }
5553: return;
5554: }
5555:
5556: sub course_group_datechecker {
5557: my ($dates,$now,$status) = @_;
5558: my ($start,$end) = split(/\./,$dates);
5559: if (!$start && !$end) {
5560: return 'ok';
5561: }
5562: if (grep/^active$/,@{$status}) {
5563: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5564: return 'ok';
5565: }
5566: }
5567: if (grep/^previous$/,@{$status}) {
5568: if ($end > $now ) {
5569: return 'ok';
5570: }
5571: }
5572: if (grep/^future$/,@{$status}) {
5573: if ($start > $now) {
5574: return 'ok';
5575: }
5576: }
5577: return;
5578: }
5579:
5580: sub parse_portfolio_url {
5581: my ($url) = @_;
5582:
5583: my ($type,$udom,$unum,$group,$file_name);
5584:
1.823 albertel 5585: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5586: $type = 1;
5587: $udom = $1;
5588: $unum = $2;
5589: $file_name = $3;
1.823 albertel 5590: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5591: $type = 2;
5592: $udom = $1;
5593: $unum = $2;
5594: $group = $3;
5595: $file_name = $3.'/'.$4;
5596: }
5597: if (wantarray) {
5598: return ($type,$udom,$unum,$file_name,$group);
5599: }
5600: return $type;
5601: }
5602:
5603: sub is_portfolio_url {
5604: my ($url) = @_;
5605: return scalar(&parse_portfolio_url($url));
5606: }
5607:
1.798 raeburn 5608: sub is_portfolio_file {
5609: my ($file) = @_;
1.820 raeburn 5610: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5611: return 1;
5612: }
5613: return;
5614: }
5615:
1.976 raeburn 5616: sub usertools_access {
1.1084 raeburn 5617: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5618: my ($access,%tools);
5619: if ($context eq '') {
5620: $context = 'tools';
5621: }
5622: if ($context eq 'requestcourses') {
5623: %tools = (
5624: official => 1,
5625: unofficial => 1,
1.1006 raeburn 5626: community => 1,
1.985 raeburn 5627: );
5628: } else {
5629: %tools = (
5630: aboutme => 1,
5631: blog => 1,
5632: portfolio => 1,
5633: );
5634: }
1.976 raeburn 5635: return if (!defined($tools{$tool}));
5636:
5637: if ((!defined($udom)) || (!defined($uname))) {
5638: $udom = $env{'user.domain'};
5639: $uname = $env{'user.name'};
5640: }
5641:
1.978 raeburn 5642: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5643: if ($action ne 'reload') {
1.985 raeburn 5644: if ($context eq 'requestcourses') {
5645: return $env{'environment.canrequest.'.$tool};
5646: } else {
5647: return $env{'environment.availabletools.'.$tool};
5648: }
5649: }
1.976 raeburn 5650: }
5651:
5652: my ($toolstatus,$inststatus);
5653:
1.985 raeburn 5654: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5655: ($action ne 'reload')) {
5656: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5657: $inststatus = $env{'environment.inststatus'};
5658: } else {
1.1084 raeburn 5659: if (ref($userenvref) eq 'HASH') {
5660: $toolstatus = $userenvref->{$context.'.'.$tool};
5661: $inststatus = $userenvref->{'inststatus'};
5662: } else {
5663: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5664: $toolstatus = $userenv{$context.'.'.$tool};
5665: $inststatus = $userenv{'inststatus'};
5666: }
1.976 raeburn 5667: }
5668:
5669: if ($toolstatus ne '') {
5670: if ($toolstatus) {
5671: $access = 1;
5672: } else {
5673: $access = 0;
5674: }
5675: return $access;
5676: }
5677:
1.1084 raeburn 5678: my ($is_adv,%domdef);
5679: if (ref($is_advref) eq 'HASH') {
5680: $is_adv = $is_advref->{'is_adv'};
5681: } else {
5682: $is_adv = &is_advanced_user($udom,$uname);
5683: }
5684: if (ref($domdefref) eq 'HASH') {
5685: %domdef = %{$domdefref};
5686: } else {
5687: %domdef = &get_domain_defaults($udom);
5688: }
1.976 raeburn 5689: if (ref($domdef{$tool}) eq 'HASH') {
5690: if ($is_adv) {
5691: if ($domdef{$tool}{'_LC_adv'} ne '') {
5692: if ($domdef{$tool}{'_LC_adv'}) {
5693: $access = 1;
5694: } else {
5695: $access = 0;
5696: }
5697: return $access;
5698: }
5699: }
5700: if ($inststatus ne '') {
5701: my ($hasaccess,$hasnoaccess);
5702: foreach my $affiliation (split(/:/,$inststatus)) {
5703: if ($domdef{$tool}{$affiliation} ne '') {
5704: if ($domdef{$tool}{$affiliation}) {
5705: $hasaccess = 1;
5706: } else {
5707: $hasnoaccess = 1;
5708: }
5709: }
5710: }
5711: if ($hasaccess || $hasnoaccess) {
5712: if ($hasaccess) {
5713: $access = 1;
5714: } elsif ($hasnoaccess) {
5715: $access = 0;
5716: }
5717: return $access;
5718: }
5719: } else {
5720: if ($domdef{$tool}{'default'} ne '') {
5721: if ($domdef{$tool}{'default'}) {
5722: $access = 1;
5723: } elsif ($domdef{$tool}{'default'} == 0) {
5724: $access = 0;
5725: }
5726: return $access;
5727: }
5728: }
5729: } else {
1.985 raeburn 5730: if ($context eq 'tools') {
5731: $access = 1;
5732: } else {
5733: $access = 0;
5734: }
1.976 raeburn 5735: return $access;
5736: }
5737: }
5738:
1.1050 raeburn 5739: sub is_course_owner {
5740: my ($cdom,$cnum,$udom,$uname) = @_;
5741: if (($udom eq '') || ($uname eq '')) {
5742: $udom = $env{'user.domain'};
5743: $uname = $env{'user.name'};
5744: }
5745: unless (($udom eq '') || ($uname eq '')) {
5746: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5747: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5748: return 1;
5749: } else {
5750: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5751: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5752: return 1;
5753: }
5754: }
5755: }
5756: }
5757: return;
5758: }
5759:
1.976 raeburn 5760: sub is_advanced_user {
5761: my ($udom,$uname) = @_;
1.1085 raeburn 5762: if ($udom ne '' && $uname ne '') {
5763: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5764: if (wantarray) {
5765: return ($env{'user.adv'},$env{'user.author'});
5766: } else {
5767: return $env{'user.adv'};
5768: }
1.1085 raeburn 5769: }
5770: }
1.976 raeburn 5771: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5772: my %allroles;
1.1128 raeburn 5773: my ($is_adv,$is_author);
1.976 raeburn 5774: foreach my $role (keys(%roleshash)) {
5775: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5776: my $area = '/'.$tdomain.'/'.$trest;
5777: if ($sec ne '') {
5778: $area .= '/'.$sec;
5779: }
5780: if (($area ne '') && ($trole ne '')) {
5781: my $spec=$trole.'.'.$area;
5782: if ($trole =~ /^cr\//) {
5783: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5784: } elsif ($trole ne 'gr') {
5785: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5786: }
1.1128 raeburn 5787: if ($trole eq 'au') {
5788: $is_author = 1;
5789: }
1.976 raeburn 5790: }
5791: }
5792: foreach my $role (keys(%allroles)) {
5793: last if ($is_adv);
5794: foreach my $item (split(/:/,$allroles{$role})) {
5795: if ($item ne '') {
5796: my ($privilege,$restrictions)=split(/&/,$item);
5797: if ($privilege eq 'adv') {
5798: $is_adv = 1;
5799: last;
5800: }
5801: }
5802: }
5803: }
1.1128 raeburn 5804: if (wantarray) {
5805: return ($is_adv,$is_author);
5806: }
1.976 raeburn 5807: return $is_adv;
5808: }
1.798 raeburn 5809:
1.1035 raeburn 5810: sub check_can_request {
1.1036 raeburn 5811: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5812: my $canreq = 0;
5813: my ($types,$typename) = &Apache::loncommon::course_types();
5814: my @options = ('approval','validate','autolimit');
5815: my $optregex = join('|',@options);
5816: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5817: foreach my $type (@{$types}) {
5818: if (&usertools_access($env{'user.name'},
5819: $env{'user.domain'},
5820: $type,undef,'requestcourses')) {
5821: $canreq ++;
1.1036 raeburn 5822: if (ref($request_domains) eq 'HASH') {
5823: push(@{$request_domains->{$type}},$env{'user.domain'});
5824: }
1.1035 raeburn 5825: if ($dom eq $env{'user.domain'}) {
5826: $can_request->{$type} = 1;
5827: }
5828: }
5829: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5830: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5831: if (@curr > 0) {
1.1036 raeburn 5832: foreach my $item (@curr) {
5833: if (ref($request_domains) eq 'HASH') {
5834: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5835: if ($otherdom ne '') {
5836: if (ref($request_domains->{$type}) eq 'ARRAY') {
5837: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5838: push(@{$request_domains->{$type}},$otherdom);
5839: }
5840: } else {
5841: push(@{$request_domains->{$type}},$otherdom);
5842: }
5843: }
5844: }
5845: }
5846: unless($dom eq $env{'user.domain'}) {
5847: $canreq ++;
1.1035 raeburn 5848: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5849: $can_request->{$type} = 1;
5850: }
5851: }
5852: }
5853: }
5854: }
5855: }
5856: return $canreq;
5857: }
5858:
1.341 www 5859: # ---------------------------------------------- Custom access rule evaluation
5860:
5861: sub customaccess {
5862: my ($priv,$uri)=@_;
1.807 albertel 5863: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5864: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5865: $udom = &LONCAPA::clean_domain($udom);
5866: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5867: my $access=0;
1.800 albertel 5868: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5869: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5870: if ($type eq 'user') {
5871: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5872: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5873: if ($tdom) {
5874: if ($tdom ne $env{'user.domain'}) { next; }
5875: }
1.896 albertel 5876: if ($tuname) {
5877: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5878: }
5879: $access=($effect eq 'allow');
5880: last;
5881: }
5882: } else {
5883: if ($role) {
5884: if ($role ne $urole) { next; }
5885: }
5886: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5887: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5888: if ($tdom) {
5889: if ($tdom ne $udom) { next; }
5890: }
5891: if ($tcrs) {
5892: if ($tcrs ne $ucrs) { next; }
5893: }
5894: if ($tsec) {
5895: if ($tsec ne $usec) { next; }
5896: }
5897: $access=($effect eq 'allow');
5898: last;
5899: }
5900: if ($realm eq '' && $role eq '') {
5901: $access=($effect eq 'allow');
5902: }
1.402 bowersj2 5903: }
1.341 www 5904: }
5905: return $access;
5906: }
5907:
1.103 harris41 5908: # ------------------------------------------------- Check for a user privilege
1.12 www 5909:
5910: sub allowed {
1.810 raeburn 5911: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5912: my $ver_orguri=$uri;
1.439 www 5913: $uri=&deversion($uri);
1.152 www 5914: my $orguri=$uri;
1.52 www 5915: $uri=&declutter($uri);
1.809 raeburn 5916:
1.810 raeburn 5917: if ($priv eq 'evb') {
5918: # Evade communication block restrictions for specified role in a course
5919: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5920: return $1;
5921: } else {
5922: return;
5923: }
5924: }
5925:
1.620 albertel 5926: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5927: # Free bre access to adm and meta resources
1.775 albertel 5928: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5929: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5930: && ($priv eq 'bre')) {
1.14 www 5931: return 'F';
1.159 www 5932: }
5933:
1.545 banghart 5934: # Free bre access to user's own portfolio contents
1.714 raeburn 5935: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5936: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5937: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5938: my %setters;
5939: my ($startblock,$endblock) =
5940: &Apache::loncommon::blockcheck(\%setters,'port');
5941: if ($startblock && $endblock) {
5942: return 'B';
5943: } else {
5944: return 'F';
5945: }
1.545 banghart 5946: }
5947:
1.762 raeburn 5948: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5949: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5950: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5951: if (exists($env{'request.course.id'})) {
5952: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5953: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5954: if (($domain eq $cdom) && ($name eq $cnum)) {
5955: my $courseprivid=$env{'request.course.id'};
5956: $courseprivid=~s/\_/\//;
5957: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5958: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5959: return $1;
1.762 raeburn 5960: } else {
5961: if ($env{'request.course.sec'}) {
5962: $courseprivid.='/'.$env{'request.course.sec'};
5963: }
5964: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5965: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5966: return $2;
5967: }
1.714 raeburn 5968: }
5969: }
5970: }
5971: }
5972:
1.159 www 5973: # Free bre to public access
5974:
5975: if ($priv eq 'bre') {
1.238 www 5976: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5977: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5978: return 'F';
5979: }
1.238 www 5980: if ($copyright eq 'priv') {
5981: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5982: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5983: return '';
5984: }
5985: }
5986: if ($copyright eq 'domain') {
5987: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5988: unless (($env{'user.domain'} eq $1) ||
5989: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5990: return '';
5991: }
1.262 matthew 5992: }
1.620 albertel 5993: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5994: # Library role, so allow browsing of resources in this domain.
5995: return 'F';
1.238 www 5996: }
1.341 www 5997: if ($copyright eq 'custom') {
5998: unless (&customaccess($priv,$uri)) { return ''; }
5999: }
1.14 www 6000: }
1.264 matthew 6001: # Domain coordinator is trying to create a course
1.620 albertel 6002: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6003: # uri is the requested domain in this case.
6004: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6005: # a role of dc for the domain in question.
1.620 albertel 6006: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6007: }
1.29 www 6008:
1.52 www 6009: my $thisallowed='';
6010: my $statecond=0;
6011: my $courseprivid='';
6012:
1.1039 raeburn 6013: my $ownaccess;
1.1043 raeburn 6014: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6015: if (($priv eq 'bro') && ($env{'user.author'})) {
6016: if ($uri eq '') {
6017: $ownaccess = 1;
6018: } else {
6019: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6020: my $udom = $env{'user.domain'};
6021: my $uname = $env{'user.name'};
6022: if ($uri =~ m{^\Q$udom\E/?$}) {
6023: $ownaccess = 1;
1.1040 raeburn 6024: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6025: unless ($uri =~ m{\.\./}) {
6026: $ownaccess = 1;
6027: }
6028: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6029: my $now = time;
6030: if ($uri =~ m{^([^/]+)/?$}) {
6031: my $adom = $1;
6032: foreach my $key (keys(%env)) {
1.1042 raeburn 6033: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6034: my ($start,$end) = split('.',$env{$key});
6035: if (($now >= $start) && (!$end || $end < $now)) {
6036: $ownaccess = 1;
6037: last;
6038: }
6039: }
6040: }
6041: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6042: my $adom = $1;
6043: my $aname = $2;
1.1042 raeburn 6044: foreach my $role ('ca','aa') {
6045: if ($env{"user.role.$role./$adom/$aname"}) {
6046: my ($start,$end) =
6047: split('.',$env{"user.role.$role./$adom/$aname"});
6048: if (($now >= $start) && (!$end || $end < $now)) {
6049: $ownaccess = 1;
6050: last;
6051: }
1.1039 raeburn 6052: }
6053: }
6054: }
6055: }
6056: }
6057: }
6058: }
6059:
1.52 www 6060: # Course
6061:
1.620 albertel 6062: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6063: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6064: $thisallowed.=$1;
6065: }
1.52 www 6066: }
1.29 www 6067:
1.52 www 6068: # Domain
6069:
1.620 albertel 6070: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6071: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6072: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6073: $thisallowed.=$1;
6074: }
1.12 www 6075: }
1.52 www 6076:
1.1141 raeburn 6077: # User who is not author or co-author might still be able to edit
6078: # resource of an author in the domain (e.g., if Domain Coordinator).
6079: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6080: (&allowed('mdc',$env{'request.course.id'}))) {
6081: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6082: $thisallowed.=$1;
6083: }
6084: }
6085:
1.52 www 6086: # Course: uri itself is a course
1.66 www 6087: my $courseuri=$uri;
6088: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6089: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6090:
1.620 albertel 6091: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6092: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6093: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6094: $thisallowed.=$1;
6095: }
1.12 www 6096: }
1.29 www 6097:
1.665 albertel 6098: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6099: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6100: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6101: $thisallowed='';
1.671 raeburn 6102: my ($match)=&is_on_map($uri);
6103: if ($match) {
6104: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6105: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6106: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6107: if (@blockers > 0) {
6108: $thisallowed = 'B';
6109: } else {
6110: $thisallowed.=$1;
6111: }
1.671 raeburn 6112: }
6113: } else {
1.705 albertel 6114: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6115: if ($refuri) {
6116: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6117: $thisallowed='F';
1.671 raeburn 6118: } else {
6119: $refuri=&declutter($refuri);
6120: my ($match) = &is_on_map($refuri);
6121: if ($match) {
1.1162 raeburn 6122: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6123: if (@blockers > 0) {
6124: $thisallowed = 'B';
6125: } else {
6126: $thisallowed='F';
6127: }
1.671 raeburn 6128: }
1.669 raeburn 6129: }
1.671 raeburn 6130: }
6131: }
1.314 www 6132: }
1.492 albertel 6133:
1.766 albertel 6134: if ($priv eq 'bre'
6135: && $thisallowed ne 'F'
6136: && $thisallowed ne '2'
6137: && &is_portfolio_url($uri)) {
6138: $thisallowed = &portfolio_access($uri);
6139: }
6140:
1.52 www 6141: # Full access at system, domain or course-wide level? Exit.
1.29 www 6142: if ($thisallowed=~/F/) {
6143: return 'F';
6144: }
6145:
1.52 www 6146: # If this is generating or modifying users, exit with special codes
1.29 www 6147:
1.643 www 6148: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6149: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6150: my ($audom,$auname)=split('/',$uri);
1.643 www 6151: # no author name given, so this just checks on the general right to make a co-author in this domain
6152: unless ($auname) { return $thisallowed; }
6153: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6154: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6155: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6156: ($audom ne $env{'request.role.domain'}))) { return ''; }
6157: }
1.52 www 6158: return $thisallowed;
6159: }
6160: #
1.103 harris41 6161: # Gathered so far: system, domain and course wide privileges
1.52 www 6162: #
6163: # Course: See if uri or referer is an individual resource that is part of
6164: # the course
6165:
1.620 albertel 6166: if ($env{'request.course.id'}) {
1.232 www 6167:
1.620 albertel 6168: $courseprivid=$env{'request.course.id'};
6169: if ($env{'request.course.sec'}) {
6170: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6171: }
6172: $courseprivid=~s/\_/\//;
6173: my $checkreferer=1;
1.232 www 6174: my ($match,$cond)=&is_on_map($uri);
6175: if ($match) {
6176: $statecond=$cond;
1.620 albertel 6177: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6178: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6179: my $value = $1;
6180: if ($priv eq 'bre') {
6181: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6182: if (@blockers > 0) {
6183: $thisallowed = 'B';
6184: } else {
6185: $thisallowed.=$value;
6186: }
6187: } else {
6188: $thisallowed.=$value;
6189: }
1.52 www 6190: $checkreferer=0;
6191: }
1.29 www 6192: }
1.83 www 6193:
1.148 www 6194: if ($checkreferer) {
1.620 albertel 6195: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6196: unless ($refuri) {
1.800 albertel 6197: foreach my $key (keys(%env)) {
6198: if ($key=~/^httpref\..*\*/) {
6199: my $pattern=$key;
1.156 www 6200: $pattern=~s/^httpref\.\/res\///;
1.148 www 6201: $pattern=~s/\*/\[\^\/\]\+/g;
6202: $pattern=~s/\//\\\//g;
1.152 www 6203: if ($orguri=~/$pattern/) {
1.800 albertel 6204: $refuri=$env{$key};
1.148 www 6205: }
6206: }
1.191 harris41 6207: }
1.148 www 6208: }
1.232 www 6209:
1.148 www 6210: if ($refuri) {
1.152 www 6211: $refuri=&declutter($refuri);
1.232 www 6212: my ($match,$cond)=&is_on_map($refuri);
6213: if ($match) {
6214: my $refstatecond=$cond;
1.620 albertel 6215: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6216: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6217: my $value = $1;
6218: if ($priv eq 'bre') {
6219: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6220: if (@blockers > 0) {
6221: $thisallowed = 'B';
6222: } else {
6223: $thisallowed.=$value;
6224: }
6225: } else {
6226: $thisallowed.=$value;
6227: }
1.53 www 6228: $uri=$refuri;
6229: $statecond=$refstatecond;
1.52 www 6230: }
6231: }
1.148 www 6232: }
1.29 www 6233: }
1.52 www 6234: }
1.29 www 6235:
1.52 www 6236: #
1.103 harris41 6237: # Gathered now: all privileges that could apply, and condition number
1.52 www 6238: #
6239: #
6240: # Full or no access?
6241: #
1.29 www 6242:
1.52 www 6243: if ($thisallowed=~/F/) {
6244: return 'F';
6245: }
1.29 www 6246:
1.52 www 6247: unless ($thisallowed) {
6248: return '';
6249: }
1.29 www 6250:
1.52 www 6251: # Restrictions exist, deal with them
6252: #
6253: # C:according to course preferences
6254: # R:according to resource settings
6255: # L:unless locked
6256: # X:according to user session state
6257: #
6258:
6259: # Possibly locked functionality, check all courses
1.54 www 6260: # Locks might take effect only after 10 minutes cache expiration for other
6261: # courses, and 2 minutes for current course
1.52 www 6262:
6263: my $envkey;
6264: if ($thisallowed=~/L/) {
1.1000 raeburn 6265: foreach $envkey (keys(%env)) {
1.54 www 6266: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6267: my $courseid=$2;
6268: my $roleid=$1.'.'.$2;
1.92 www 6269: $courseid=~s/^\///;
1.54 www 6270: my $expiretime=600;
1.620 albertel 6271: if ($env{'request.role'} eq $roleid) {
1.54 www 6272: $expiretime=120;
6273: }
6274: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6275: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6276: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6277: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6278: }
1.620 albertel 6279: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6280: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6281: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6282: &log($env{'user.domain'},$env{'user.name'},
6283: $env{'user.home'},
1.57 www 6284: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6285: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6286: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6287: return '';
6288: }
6289: }
1.620 albertel 6290: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6291: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6292: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6293: &log($env{'user.domain'},$env{'user.name'},
6294: $env{'user.home'},
1.57 www 6295: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6296: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6297: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6298: return '';
6299: }
6300: }
6301: }
1.29 www 6302: }
1.52 www 6303: }
6304:
6305: #
6306: # Rest of the restrictions depend on selected course
6307: #
6308:
1.620 albertel 6309: unless ($env{'request.course.id'}) {
1.766 albertel 6310: if ($thisallowed eq 'A') {
6311: return 'A';
1.814 raeburn 6312: } elsif ($thisallowed eq 'B') {
6313: return 'B';
1.766 albertel 6314: } else {
6315: return '1';
6316: }
1.52 www 6317: }
1.29 www 6318:
1.52 www 6319: #
6320: # Now user is definitely in a course
6321: #
1.53 www 6322:
6323:
6324: # Course preferences
6325:
6326: if ($thisallowed=~/C/) {
1.620 albertel 6327: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6328: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6329: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6330: =~/\Q$rolecode\E/) {
1.1103 raeburn 6331: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6332: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6333: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6334: $env{'request.course.id'});
6335: }
1.237 www 6336: return '';
6337: }
6338:
1.620 albertel 6339: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6340: =~/\Q$unamedom\E/) {
1.1103 raeburn 6341: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6342: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6343: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6344: $env{'request.course.id'});
6345: }
1.54 www 6346: return '';
6347: }
1.53 www 6348: }
6349:
6350: # Resource preferences
6351:
6352: if ($thisallowed=~/R/) {
1.620 albertel 6353: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6354: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6355: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6356: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6357: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6358: }
6359: return '';
1.54 www 6360: }
1.53 www 6361: }
1.30 www 6362:
1.246 www 6363: # Restricted by state or randomout?
1.30 www 6364:
1.52 www 6365: if ($thisallowed=~/X/) {
1.620 albertel 6366: if ($env{'acc.randomout'}) {
1.579 albertel 6367: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6368: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6369: return '';
6370: }
1.247 www 6371: }
6372: if (&condval($statecond)) {
1.52 www 6373: return '2';
6374: } else {
6375: return '';
6376: }
6377: }
1.30 www 6378:
1.766 albertel 6379: if ($thisallowed eq 'A') {
6380: return 'A';
1.814 raeburn 6381: } elsif ($thisallowed eq 'B') {
6382: return 'B';
1.766 albertel 6383: }
1.52 www 6384: return 'F';
1.232 www 6385: }
1.1162 raeburn 6386:
6387: sub get_comm_blocks {
6388: my ($cdom,$cnum) = @_;
6389: if ($cdom eq '' || $cnum eq '') {
6390: return unless ($env{'request.course.id'});
6391: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6392: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6393: }
6394: my %commblocks;
6395: my $hashid=$cdom.'_'.$cnum;
6396: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6397: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6398: %commblocks = %{$blocksref};
6399: } else {
6400: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6401: my $cachetime = 600;
6402: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6403: }
6404: return %commblocks;
6405: }
6406:
6407: sub has_comm_blocking {
6408: my ($priv,$symb,$uri,$blocks) = @_;
6409: return unless ($env{'request.course.id'});
6410: return unless ($priv eq 'bre');
6411: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6412: my %commblocks;
6413: if (ref($blocks) eq 'HASH') {
6414: %commblocks = %{$blocks};
6415: } else {
6416: %commblocks = &get_comm_blocks();
6417: }
6418: return unless (keys(%commblocks) > 0);
6419: if (!$symb) { $symb=&symbread($uri,1); }
6420: my ($map,$resid,undef)=&decode_symb($symb);
6421: my %tocheck = (
6422: maps => $map,
6423: resources => $symb,
6424: );
6425: my @blockers;
6426: my $now = time;
1.1163 raeburn 6427: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6428: foreach my $block (keys(%commblocks)) {
6429: if ($block =~ /^(\d+)____(\d+)$/) {
6430: my ($start,$end) = ($1,$2);
6431: if ($start <= $now && $end >= $now) {
6432: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6433: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6434: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6435: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6436: unless (grep(/^\Q$block\E$/,@blockers)) {
6437: push(@blockers,$block);
6438: }
6439: }
6440: }
6441: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6442: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6443: unless (grep(/^\Q$block\E$/,@blockers)) {
6444: push(@blockers,$block);
6445: }
6446: }
6447: }
6448: }
6449: }
6450: }
6451: } elsif ($block =~ /^firstaccess____(.+)$/) {
6452: my $item = $1;
1.1163 raeburn 6453: my @to_test;
1.1162 raeburn 6454: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6455: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6456: my $check_interval;
6457: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6458: my @interval;
6459: my $type = 'map';
6460: if ($item eq 'course') {
6461: $type = 'course';
6462: @interval=&EXT("resource.0.interval");
6463: } else {
6464: if ($item =~ /___\d+___/) {
6465: $type = 'resource';
6466: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6467: if (ref($navmap)) {
6468: my $res = $navmap->getBySymb($item);
6469: push(@to_test,$res);
6470: }
1.1162 raeburn 6471: } else {
6472: my $mapsymb = &symbread($item,1);
6473: if ($mapsymb) {
6474: if (ref($navmap)) {
6475: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6476: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6477: foreach my $res (@to_test) {
1.1162 raeburn 6478: my $symb = $res->symb();
6479: next if ($symb eq $mapsymb);
6480: if ($symb ne '') {
6481: @interval=&EXT("resource.0.interval",$symb);
6482: last;
6483: }
6484: }
6485: }
6486: }
6487: }
6488: }
6489: if ($interval[0] =~ /\d+/) {
6490: my $first_access;
6491: if ($type eq 'resource') {
6492: $first_access=&get_first_access($interval[1],$item);
6493: } elsif ($type eq 'map') {
6494: $first_access=&get_first_access($interval[1],undef,$item);
6495: } else {
6496: $first_access=&get_first_access($interval[1]);
6497: }
6498: if ($first_access) {
6499: my $timesup = $first_access+$interval[0];
6500: if ($timesup > $now) {
1.1163 raeburn 6501: foreach my $res (@to_test) {
6502: if ($res->is_problem()) {
6503: if ($res->completable()) {
6504: unless (grep(/^\Q$block\E$/,@blockers)) {
6505: push(@blockers,$block);
6506: }
6507: last;
6508: }
6509: }
1.1162 raeburn 6510: }
6511: }
6512: }
6513: }
6514: }
6515: }
6516: }
6517: }
6518: }
6519: return @blockers;
6520: }
6521:
6522: sub check_docs_block {
6523: my ($docsblock,$tocheck) =@_;
6524: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6525: return;
6526: }
6527: if (ref($docsblock->{'maps'}) eq 'HASH') {
6528: if ($tocheck->{'maps'}) {
6529: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6530: return 1;
6531: }
6532: }
6533: }
6534: if (ref($docsblock->{'resources'}) eq 'HASH') {
6535: if ($tocheck->{'resources'}) {
6536: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6537: return 1;
6538: }
6539: }
6540: }
6541: return;
6542: }
6543:
1.1133 foxr 6544: #
6545: # Removes the versino from a URI and
6546: # splits it in to its filename and path to the filename.
6547: # Seems like File::Basename could have done this more clearly.
6548: # Parameters:
6549: # $uri - input URI
6550: # Returns:
6551: # Two element list consisting of
6552: # $pathname - the URI up to and excluding the trailing /
6553: # $filename - The part of the URI following the last /
6554: # NOTE:
6555: # Another realization of this is simply:
6556: # use File::Basename;
6557: # ...
6558: # $uri = shift;
6559: # $filename = basename($uri);
6560: # $path = dirname($uri);
6561: # return ($filename, $path);
6562: #
6563: # The implementation below is probably faster however.
6564: #
1.710 albertel 6565: sub split_uri_for_cond {
6566: my $uri=&deversion(&declutter(shift));
6567: my @uriparts=split(/\//,$uri);
6568: my $filename=pop(@uriparts);
6569: my $pathname=join('/',@uriparts);
6570: return ($pathname,$filename);
6571: }
1.232 www 6572: # --------------------------------------------------- Is a resource on the map?
6573:
6574: sub is_on_map {
1.710 albertel 6575: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6576: #Trying to find the conditional for the file
1.620 albertel 6577: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6578: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6579: if ($match) {
1.289 bowersj2 6580: return (1,$1);
6581: } else {
1.434 www 6582: return (0,0);
1.289 bowersj2 6583: }
1.12 www 6584: }
6585:
1.427 www 6586: # --------------------------------------------------------- Get symb from alias
6587:
6588: sub get_symb_from_alias {
6589: my $symb=shift;
6590: my ($map,$resid,$url)=&decode_symb($symb);
6591: # Already is a symb
6592: if ($url) { return $symb; }
6593: # Must be an alias
6594: my $aliassymb='';
6595: my %bighash;
1.620 albertel 6596: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6597: &GDBM_READER(),0640)) {
6598: my $rid=$bighash{'mapalias_'.$symb};
6599: if ($rid) {
6600: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6601: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6602: $resid,$bighash{'src_'.$rid});
1.427 www 6603: }
6604: untie %bighash;
6605: }
6606: return $aliassymb;
6607: }
6608:
1.12 www 6609: # ----------------------------------------------------------------- Define Role
6610:
6611: sub definerole {
6612: if (allowed('mcr','/')) {
6613: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6614: foreach my $role (split(':',$sysrole)) {
6615: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6616: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6617: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6618: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6619: return "refused:s:$crole&$cqual";
6620: }
6621: }
1.191 harris41 6622: }
1.800 albertel 6623: foreach my $role (split(':',$domrole)) {
6624: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6625: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6626: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6627: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6628: return "refused:d:$crole&$cqual";
6629: }
6630: }
1.191 harris41 6631: }
1.800 albertel 6632: foreach my $role (split(':',$courole)) {
6633: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6634: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6635: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6636: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6637: return "refused:c:$crole&$cqual";
6638: }
6639: }
1.191 harris41 6640: }
1.620 albertel 6641: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6642: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6643: "rolesdef_$rolename=".
6644: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6645: return reply($command,$env{'user.home'});
1.12 www 6646: } else {
6647: return 'refused';
6648: }
1.105 harris41 6649: }
6650:
6651: # ---------------- Make a metadata query against the network of library servers
6652:
6653: sub metadata_query {
1.244 matthew 6654: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6655: my %rhash;
1.845 albertel 6656: my %libserv = &all_library();
1.244 matthew 6657: my @server_list = (defined($server_array) ? @$server_array
6658: : keys(%libserv) );
6659: for my $server (@server_list) {
1.118 harris41 6660: unless ($custom or $customshow) {
6661: my $reply=&reply("querysend:".&escape($query),$server);
6662: $rhash{$server}=$reply;
6663: }
6664: else {
6665: my $reply=&reply("querysend:".&escape($query).':'.
6666: &escape($custom).':'.&escape($customshow),
6667: $server);
6668: $rhash{$server}=$reply;
6669: }
1.112 harris41 6670: }
1.118 harris41 6671: return \%rhash;
1.240 www 6672: }
6673:
6674: # ----------------------------------------- Send log queries and wait for reply
6675:
6676: sub log_query {
6677: my ($uname,$udom,$query,%filters)=@_;
6678: my $uhome=&homeserver($uname,$udom);
6679: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6680: my $uhost=&hostname($uhome);
1.800 albertel 6681: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6682: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6683: $uhome);
1.479 albertel 6684: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6685: return get_query_reply($queryid);
6686: }
6687:
1.818 raeburn 6688: # -------------------------- Update MySQL table for portfolio file
6689:
6690: sub update_portfolio_table {
1.821 raeburn 6691: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6692: if ($group ne '') {
6693: $file_name =~s /^\Q$group\E//;
6694: }
1.818 raeburn 6695: my $homeserver = &homeserver($uname,$udom);
6696: my $queryid=
1.821 raeburn 6697: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6698: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6699: my $reply = &get_query_reply($queryid);
6700: return $reply;
6701: }
6702:
1.899 raeburn 6703: # -------------------------- Update MySQL allusers table
6704:
6705: sub update_allusers_table {
6706: my ($uname,$udom,$names) = @_;
6707: my $homeserver = &homeserver($uname,$udom);
6708: my $queryid=
6709: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6710: 'lastname='.&escape($names->{'lastname'}).'%%'.
6711: 'firstname='.&escape($names->{'firstname'}).'%%'.
6712: 'middlename='.&escape($names->{'middlename'}).'%%'.
6713: 'generation='.&escape($names->{'generation'}).'%%'.
6714: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6715: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6716: return;
1.899 raeburn 6717: }
6718:
1.508 raeburn 6719: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6720:
6721: sub fetch_enrollment_query {
1.511 raeburn 6722: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6723: my $homeserver;
1.547 raeburn 6724: my $maxtries = 1;
1.508 raeburn 6725: if ($context eq 'automated') {
6726: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6727: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6728: } else {
6729: $homeserver = &homeserver($cnum,$dom);
6730: }
1.838 albertel 6731: my $host=&hostname($homeserver);
1.506 raeburn 6732: my $cmd = '';
1.1000 raeburn 6733: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6734: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6735: }
6736: $cmd =~ s/%%$//;
6737: $cmd = &escape($cmd);
6738: my $query = 'fetchenrollment';
1.620 albertel 6739: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6740: unless ($queryid=~/^\Q$host\E\_/) {
6741: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6742: return 'error: '.$queryid;
6743: }
1.506 raeburn 6744: my $reply = &get_query_reply($queryid);
1.547 raeburn 6745: my $tries = 1;
6746: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6747: $reply = &get_query_reply($queryid);
6748: $tries ++;
6749: }
1.526 raeburn 6750: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6751: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6752: } else {
1.901 albertel 6753: my @responses = split(/:/,$reply);
1.515 raeburn 6754: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6755: foreach my $line (@responses) {
6756: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6757: $$replyref{$key} = $value;
6758: }
6759: } else {
1.1117 foxr 6760: my $pathname = LONCAPA::tempdir();
1.800 albertel 6761: foreach my $line (@responses) {
6762: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6763: $$replyref{$key} = $value;
6764: if ($value > 0) {
1.800 albertel 6765: foreach my $item (@{$$affiliatesref{$key}}) {
6766: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6767: my $destname = $pathname.'/'.$filename;
6768: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6769: if ($xml_classlist =~ /^error/) {
6770: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6771: } else {
1.506 raeburn 6772: if ( open(FILE,">$destname") ) {
6773: print FILE &unescape($xml_classlist);
6774: close(FILE);
1.526 raeburn 6775: } else {
6776: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6777: }
6778: }
6779: }
6780: }
6781: }
6782: }
6783: return 'ok';
6784: }
6785: return 'error';
6786: }
6787:
1.242 www 6788: sub get_query_reply {
6789: my $queryid=shift;
1.1117 foxr 6790: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6791: my $reply='';
6792: for (1..100) {
6793: sleep 2;
6794: if (-e $replyfile.'.end') {
1.448 albertel 6795: if (open(my $fh,$replyfile)) {
1.904 albertel 6796: $reply = join('',<$fh>);
6797: close($fh);
1.240 www 6798: } else { return 'error: reply_file_error'; }
1.242 www 6799: return &unescape($reply);
6800: }
1.240 www 6801: }
1.242 www 6802: return 'timeout:'.$queryid;
1.240 www 6803: }
6804:
6805: sub courselog_query {
1.241 www 6806: #
6807: # possible filters:
6808: # url: url or symb
6809: # username
6810: # domain
6811: # action: view, submit, grade
6812: # start: timestamp
6813: # end: timestamp
6814: #
1.240 www 6815: my (%filters)=@_;
1.620 albertel 6816: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6817: if ($filters{'url'}) {
6818: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6819: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6820: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6821: }
1.620 albertel 6822: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6823: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6824: return &log_query($cname,$cdom,'courselog',%filters);
6825: }
6826:
6827: sub userlog_query {
1.858 raeburn 6828: #
6829: # possible filters:
6830: # action: log check role
6831: # start: timestamp
6832: # end: timestamp
6833: #
1.240 www 6834: my ($uname,$udom,%filters)=@_;
6835: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6836: }
6837:
1.506 raeburn 6838: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6839:
6840: sub auto_run {
1.508 raeburn 6841: my ($cnum,$cdom) = @_;
1.876 raeburn 6842: my $response = 0;
6843: my $settings;
6844: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6845: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6846: $settings = $domconfig{'autoenroll'};
6847: if ($settings->{'run'} eq '1') {
6848: $response = 1;
6849: }
6850: } else {
1.934 raeburn 6851: my $homeserver;
6852: if (&is_course($cdom,$cnum)) {
6853: $homeserver = &homeserver($cnum,$cdom);
6854: } else {
6855: $homeserver = &domain($cdom,'primary');
6856: }
6857: if ($homeserver ne 'no_host') {
6858: $response = &reply('autorun:'.$cdom,$homeserver);
6859: }
1.876 raeburn 6860: }
1.506 raeburn 6861: return $response;
6862: }
1.776 albertel 6863:
1.506 raeburn 6864: sub auto_get_sections {
1.508 raeburn 6865: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6866: my $homeserver;
6867: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6868: $homeserver = &homeserver($cnum,$cdom);
6869: }
6870: if (!defined($homeserver)) {
6871: if ($cdom =~ /^$match_domain$/) {
6872: $homeserver = &domain($cdom,'primary');
6873: }
6874: }
6875: my @secs;
6876: if (defined($homeserver)) {
6877: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6878: unless ($response eq 'refused') {
6879: @secs = split(/:/,$response);
6880: }
1.506 raeburn 6881: }
6882: return @secs;
6883: }
1.776 albertel 6884:
1.506 raeburn 6885: sub auto_new_course {
1.1099 raeburn 6886: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6887: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6888: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6889: return $response;
6890: }
1.776 albertel 6891:
1.506 raeburn 6892: sub auto_validate_courseID {
1.508 raeburn 6893: my ($cnum,$cdom,$inst_course_id) = @_;
6894: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6895: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6896: return $response;
6897: }
1.776 albertel 6898:
1.1007 raeburn 6899: sub auto_validate_instcode {
1.1020 raeburn 6900: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6901: my ($homeserver,$response);
6902: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6903: $homeserver = &homeserver($cnum,$cdom);
6904: }
6905: if (!defined($homeserver)) {
6906: if ($cdom =~ /^$match_domain$/) {
6907: $homeserver = &domain($cdom,'primary');
6908: }
6909: }
1.1065 raeburn 6910: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6911: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6912: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6913: return ($outcome,$description);
1.1007 raeburn 6914: }
6915:
1.506 raeburn 6916: sub auto_create_password {
1.873 raeburn 6917: my ($cnum,$cdom,$authparam,$udom) = @_;
6918: my ($homeserver,$response);
1.506 raeburn 6919: my $create_passwd = 0;
6920: my $authchk = '';
1.873 raeburn 6921: if ($udom =~ /^$match_domain$/) {
6922: $homeserver = &domain($udom,'primary');
6923: }
6924: if ($homeserver eq '') {
6925: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6926: $homeserver = &homeserver($cnum,$cdom);
6927: }
6928: }
6929: if ($homeserver eq '') {
6930: $authchk = 'nodomain';
1.506 raeburn 6931: } else {
1.873 raeburn 6932: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6933: if ($response eq 'refused') {
6934: $authchk = 'refused';
6935: } else {
1.901 albertel 6936: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6937: }
1.506 raeburn 6938: }
6939: return ($authparam,$create_passwd,$authchk);
6940: }
6941:
1.706 raeburn 6942: sub auto_photo_permission {
6943: my ($cnum,$cdom,$students) = @_;
6944: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6945: my ($outcome,$perm_reqd,$conditions) =
6946: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6947: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6948: return (undef,undef);
6949: }
1.706 raeburn 6950: return ($outcome,$perm_reqd,$conditions);
6951: }
6952:
6953: sub auto_checkphotos {
6954: my ($uname,$udom,$pid) = @_;
6955: my $homeserver = &homeserver($uname,$udom);
6956: my ($result,$resulttype);
6957: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6958: &escape($uname).':'.&escape($pid),
6959: $homeserver));
1.709 albertel 6960: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6961: return (undef,undef);
6962: }
1.706 raeburn 6963: if ($outcome) {
6964: ($result,$resulttype) = split(/:/,$outcome);
6965: }
6966: return ($result,$resulttype);
6967: }
6968:
6969: sub auto_photochoice {
6970: my ($cnum,$cdom) = @_;
6971: my $homeserver = &homeserver($cnum,$cdom);
6972: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6973: &escape($cdom),
6974: $homeserver)));
1.709 albertel 6975: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6976: return (undef,undef);
6977: }
1.706 raeburn 6978: return ($update,$comment);
6979: }
6980:
6981: sub auto_photoupdate {
6982: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6983: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6984: my $host=&hostname($homeserver);
1.706 raeburn 6985: my $cmd = '';
6986: my $maxtries = 1;
1.800 albertel 6987: foreach my $affiliate (keys(%{$affiliatesref})) {
6988: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6989: }
6990: $cmd =~ s/%%$//;
6991: $cmd = &escape($cmd);
6992: my $query = 'institutionalphotos';
6993: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6994: unless ($queryid=~/^\Q$host\E\_/) {
6995: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6996: return 'error: '.$queryid;
6997: }
6998: my $reply = &get_query_reply($queryid);
6999: my $tries = 1;
7000: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7001: $reply = &get_query_reply($queryid);
7002: $tries ++;
7003: }
7004: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7005: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7006: } else {
7007: my @responses = split(/:/,$reply);
7008: my $outcome = shift(@responses);
7009: foreach my $item (@responses) {
7010: my ($key,$value) = split(/=/,$item);
7011: $$photo{$key} = $value;
7012: }
7013: return $outcome;
7014: }
7015: return 'error';
7016: }
7017:
1.521 raeburn 7018: sub auto_instcode_format {
1.793 albertel 7019: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7020: $cat_order) = @_;
1.521 raeburn 7021: my $courses = '';
1.772 raeburn 7022: my @homeservers;
1.521 raeburn 7023: if ($caller eq 'global') {
1.841 albertel 7024: my %servers = &get_servers($codedom,'library');
7025: foreach my $tryserver (keys(%servers)) {
7026: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7027: push(@homeservers,$tryserver);
7028: }
1.584 raeburn 7029: }
1.1022 raeburn 7030: } elsif ($caller eq 'requests') {
7031: if ($codedom =~ /^$match_domain$/) {
7032: my $chome = &domain($codedom,'primary');
7033: unless ($chome eq 'no_host') {
7034: push(@homeservers,$chome);
7035: }
7036: }
1.521 raeburn 7037: } else {
1.772 raeburn 7038: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7039: }
1.793 albertel 7040: foreach my $code (keys(%{$instcodes})) {
7041: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7042: }
7043: chop($courses);
1.772 raeburn 7044: my $ok_response = 0;
7045: my $response;
7046: while (@homeservers > 0 && $ok_response == 0) {
7047: my $server = shift(@homeservers);
7048: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7049: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7050: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7051: split(/:/,$response);
1.772 raeburn 7052: %{$codes} = (%{$codes},&str2hash($codes_str));
7053: push(@{$codetitles},&str2array($codetitles_str));
7054: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7055: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7056: $ok_response = 1;
7057: }
7058: }
7059: if ($ok_response) {
1.521 raeburn 7060: return 'ok';
1.772 raeburn 7061: } else {
7062: return $response;
1.521 raeburn 7063: }
7064: }
7065:
1.792 raeburn 7066: sub auto_instcode_defaults {
7067: my ($domain,$returnhash,$code_order) = @_;
7068: my @homeservers;
1.841 albertel 7069:
7070: my %servers = &get_servers($domain,'library');
7071: foreach my $tryserver (keys(%servers)) {
7072: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7073: push(@homeservers,$tryserver);
7074: }
1.792 raeburn 7075: }
1.841 albertel 7076:
1.792 raeburn 7077: my $response;
1.841 albertel 7078: foreach my $server (@homeservers) {
1.792 raeburn 7079: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7080: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7081:
7082: foreach my $pair (split(/\&/,$response)) {
7083: my ($name,$value)=split(/\=/,$pair);
7084: if ($name eq 'code_order') {
7085: @{$code_order} = split(/\&/,&unescape($value));
7086: } else {
7087: $returnhash->{&unescape($name)}=&unescape($value);
7088: }
7089: }
7090: return 'ok';
1.792 raeburn 7091: }
1.841 albertel 7092:
7093: return $response;
1.1003 raeburn 7094: }
7095:
7096: sub auto_possible_instcodes {
1.1007 raeburn 7097: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7098: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7099: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7100: return;
7101: }
1.1003 raeburn 7102: my (@homeservers,$uhome);
7103: if (defined(&domain($domain,'primary'))) {
7104: $uhome=&domain($domain,'primary');
7105: push(@homeservers,&domain($domain,'primary'));
7106: } else {
7107: my %servers = &get_servers($domain,'library');
7108: foreach my $tryserver (keys(%servers)) {
7109: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7110: push(@homeservers,$tryserver);
7111: }
7112: }
7113: }
7114: my $response;
7115: foreach my $server (@homeservers) {
7116: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7117: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7118: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7119: split(':',$response);
7120: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7121: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7122: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7123: my ($name,$value)=split('=',$item);
7124: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7125: }
7126: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7127: my ($name,$value)=split('=',$item);
7128: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7129: }
7130: return 'ok';
7131: }
7132: return $response;
7133: }
1.792 raeburn 7134:
1.1010 raeburn 7135: sub auto_courserequest_checks {
7136: my ($dom) = @_;
1.1020 raeburn 7137: my ($homeserver,%validations);
7138: if ($dom =~ /^$match_domain$/) {
7139: $homeserver = &domain($dom,'primary');
7140: }
7141: unless ($homeserver eq 'no_host') {
7142: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7143: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7144: my @items = split(/&/,$response);
7145: foreach my $item (@items) {
7146: my ($key,$value) = split('=',$item);
7147: $validations{&unescape($key)} = &thaw_unescape($value);
7148: }
7149: }
7150: }
1.1010 raeburn 7151: return %validations;
7152: }
7153:
1.1020 raeburn 7154: sub auto_courserequest_validation {
7155: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7156: my ($homeserver,$response);
7157: if ($dom =~ /^$match_domain$/) {
7158: $homeserver = &domain($dom,'primary');
7159: }
7160: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7161:
1.1020 raeburn 7162: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7163: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7164: ':'.&escape($instcode).':'.&escape($instseclist),
7165: $homeserver));
7166: }
7167: return $response;
7168: }
7169:
1.777 albertel 7170: sub auto_validate_class_sec {
1.918 raeburn 7171: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7172: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7173: my $ownerlist;
7174: if (ref($owners) eq 'ARRAY') {
7175: $ownerlist = join(',',@{$owners});
7176: } else {
7177: $ownerlist = $owners;
7178: }
1.773 raeburn 7179: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7180: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7181: return $response;
7182: }
7183:
1.679 raeburn 7184: # ------------------------------------------------------- Course Group routines
7185:
7186: sub get_coursegroups {
1.809 raeburn 7187: my ($cdom,$cnum,$group,$namespace) = @_;
7188: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7189: }
7190:
1.679 raeburn 7191: sub modify_coursegroup {
7192: my ($cdom,$cnum,$groupsettings) = @_;
7193: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7194: }
7195:
1.809 raeburn 7196: sub toggle_coursegroup_status {
7197: my ($cdom,$cnum,$group,$action) = @_;
7198: my ($from_namespace,$to_namespace);
7199: if ($action eq 'delete') {
7200: $from_namespace = 'coursegroups';
7201: $to_namespace = 'deleted_groups';
7202: } else {
7203: $from_namespace = 'deleted_groups';
7204: $to_namespace = 'coursegroups';
7205: }
7206: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7207: if (my $tmp = &error(%curr_group)) {
7208: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7209: return ('read error',$tmp);
7210: } else {
7211: my %savedsettings = %curr_group;
1.809 raeburn 7212: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7213: my $deloutcome;
7214: if ($result eq 'ok') {
1.809 raeburn 7215: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7216: } else {
7217: return ('write error',$result);
7218: }
7219: if ($deloutcome eq 'ok') {
7220: return 'ok';
7221: } else {
7222: return ('delete error',$deloutcome);
7223: }
7224: }
7225: }
7226:
1.679 raeburn 7227: sub modify_group_roles {
1.957 raeburn 7228: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7229: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7230: my $role = 'gr/'.&escape($userprivs);
7231: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7232: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7233: if ($result eq 'ok') {
7234: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7235: }
1.679 raeburn 7236: return $result;
7237: }
7238:
7239: sub modify_coursegroup_membership {
7240: my ($cdom,$cnum,$membership) = @_;
7241: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7242: return $result;
7243: }
7244:
1.682 raeburn 7245: sub get_active_groups {
7246: my ($udom,$uname,$cdom,$cnum) = @_;
7247: my $now = time;
7248: my %groups = ();
7249: foreach my $key (keys(%env)) {
1.811 albertel 7250: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7251: my ($start,$end) = split(/\./,$env{$key});
7252: if (($end!=0) && ($end<$now)) { next; }
7253: if (($start!=0) && ($start>$now)) { next; }
7254: if ($1 eq $cdom && $2 eq $cnum) {
7255: $groups{$3} = $env{$key} ;
7256: }
7257: }
7258: }
7259: return %groups;
7260: }
7261:
1.683 raeburn 7262: sub get_group_membership {
7263: my ($cdom,$cnum,$group) = @_;
7264: return(&dump('groupmembership',$cdom,$cnum,$group));
7265: }
7266:
7267: sub get_users_groups {
7268: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7269: my @usersgroups;
1.683 raeburn 7270: my $cachetime=1800;
7271:
7272: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7273: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7274: if (defined($cached)) {
1.734 albertel 7275: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7276: } else {
7277: $grouplist = '';
1.816 raeburn 7278: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7279: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7280: my $access_end = $env{'course.'.$courseid.
7281: '.default_enrollment_end_date'};
7282: my $now = time;
7283: foreach my $key (keys(%roleshash)) {
7284: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7285: my $group = $1;
7286: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7287: my $start = $2;
7288: my $end = $1;
7289: if ($start == -1) { next; } # deleted from group
7290: if (($start!=0) && ($start>$now)) { next; }
7291: if (($end!=0) && ($end<$now)) {
7292: if ($access_end && $access_end < $now) {
7293: if ($access_end - $end < 86400) {
7294: push(@usersgroups,$group);
1.733 raeburn 7295: }
7296: }
1.817 raeburn 7297: next;
1.733 raeburn 7298: }
1.817 raeburn 7299: push(@usersgroups,$group);
1.683 raeburn 7300: }
7301: }
7302: }
1.817 raeburn 7303: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7304: $grouplist = join(':',@usersgroups);
7305: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7306: }
1.733 raeburn 7307: return @usersgroups;
1.683 raeburn 7308: }
7309:
7310: sub devalidate_getgroups_cache {
7311: my ($udom,$uname,$cdom,$cnum)=@_;
7312: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7313:
1.683 raeburn 7314: my $hashid="$udom:$uname:$courseid";
7315: &devalidate_cache_new('getgroups',$hashid);
7316: }
7317:
1.12 www 7318: # ------------------------------------------------------------------ Plain Text
7319:
7320: sub plaintext {
1.988 raeburn 7321: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7322: if ($short =~ m{^cr/}) {
1.758 albertel 7323: return (split('/',$short))[-1];
7324: }
1.742 raeburn 7325: if (!defined($cid)) {
7326: $cid = $env{'request.course.id'};
7327: }
7328: my %rolenames = (
1.1008 raeburn 7329: Course => 'std',
7330: Community => 'alt1',
1.742 raeburn 7331: );
1.1037 raeburn 7332: if ($cid ne '') {
7333: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7334: unless ($forcedefault) {
7335: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7336: &Apache::lonlocal::mt_escape(\$roletext);
7337: return &Apache::lonlocal::mt($roletext);
7338: }
7339: }
7340: }
7341: if ((defined($type)) && (defined($rolenames{$type})) &&
7342: (defined($rolenames{$type})) &&
7343: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7344: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7345: } elsif ($cid ne '') {
7346: my $crstype = $env{'course.'.$cid.'.type'};
7347: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7348: (defined($prp{$short}{$rolenames{$crstype}}))) {
7349: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7350: }
1.742 raeburn 7351: }
1.1037 raeburn 7352: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7353: }
7354:
7355: # ----------------------------------------------------------------- Assign Role
7356:
7357: sub assignrole {
1.957 raeburn 7358: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7359: $context)=@_;
1.21 www 7360: my $mrole;
7361: if ($role =~ /^cr\//) {
1.393 www 7362: my $cwosec=$url;
1.811 albertel 7363: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7364: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7365: my $refused = 1;
7366: if ($context eq 'requestcourses') {
7367: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7368: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7369: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7370: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7371: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7372: if ($crsenv{'internal.courseowner'} eq
7373: $env{'user.name'}.':'.$env{'user.domain'}) {
7374: $refused = '';
7375: }
7376: }
7377: }
7378: }
7379: }
7380: if ($refused) {
7381: &logthis('Refused custom assignrole: '.
7382: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7383: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7384: return 'refused';
7385: }
1.104 www 7386: }
1.21 www 7387: $mrole='cr';
1.678 raeburn 7388: } elsif ($role =~ /^gr\//) {
7389: my $cwogrp=$url;
1.811 albertel 7390: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7391: unless (&allowed('mdg',$cwogrp)) {
7392: &logthis('Refused group assignrole: '.
7393: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7394: $env{'user.name'}.' at '.$env{'user.domain'});
7395: return 'refused';
7396: }
7397: $mrole='gr';
1.21 www 7398: } else {
1.82 www 7399: my $cwosec=$url;
1.811 albertel 7400: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7401: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7402: my $refused;
7403: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7404: if (!(&allowed('c'.$role,$url))) {
7405: $refused = 1;
7406: }
7407: } else {
7408: $refused = 1;
7409: }
1.947 raeburn 7410: if ($refused) {
1.1045 raeburn 7411: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7412: if (!$selfenroll && $context eq 'course') {
7413: my %crsenv;
7414: if ($role eq 'cc' || $role eq 'co') {
7415: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7416: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7417: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7418: if ($crsenv{'internal.courseowner'} eq
7419: $env{'user.name'}.':'.$env{'user.domain'}) {
7420: $refused = '';
7421: }
7422: }
7423: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7424: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7425: if ($crsenv{'internal.courseowner'} eq
7426: $env{'user.name'}.':'.$env{'user.domain'}) {
7427: $refused = '';
7428: }
7429: }
7430: }
7431: }
7432: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7433: $refused = '';
1.1017 raeburn 7434: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7435: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7436: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7437: my $wrongcc;
7438: if ($cnum =~ /^$match_community$/) {
7439: $wrongcc = 1 if ($role eq 'cc');
7440: } else {
7441: $wrongcc = 1 if ($role eq 'co');
7442: }
7443: unless ($wrongcc) {
7444: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7445: if ($crsenv{'internal.courseowner'} eq
7446: $env{'user.name'}.':'.$env{'user.domain'}) {
7447: $refused = '';
7448: }
1.1017 raeburn 7449: }
7450: }
7451: }
7452: if ($refused) {
1.947 raeburn 7453: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7454: ' '.$role.' '.$end.' '.$start.' by '.
7455: $env{'user.name'}.' at '.$env{'user.domain'});
7456: return 'refused';
7457: }
1.932 raeburn 7458: }
1.1131 raeburn 7459: } elsif ($role eq 'au') {
7460: if ($url ne '/'.$udom.'/') {
7461: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7462: ' to assign author role for '.$uname.':'.$udom.
7463: ' in domain: '.$url.' refused (wrong domain).');
7464: return 'refused';
7465: }
1.104 www 7466: }
1.21 www 7467: $mrole=$role;
7468: }
1.620 albertel 7469: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7470: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7471: if ($end) { $command.='_'.$end; }
1.21 www 7472: if ($start) {
7473: if ($end) {
1.81 www 7474: $command.='_'.$start;
1.21 www 7475: } else {
1.81 www 7476: $command.='_0_'.$start;
1.21 www 7477: }
7478: }
1.739 raeburn 7479: my $origstart = $start;
7480: my $origend = $end;
1.957 raeburn 7481: my $delflag;
1.357 www 7482: # actually delete
7483: if ($deleteflag) {
1.373 www 7484: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7485: # modify command to delete the role
1.620 albertel 7486: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7487: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7488: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7489: # set start and finish to negative values for userrolelog
7490: $start=-1;
7491: $end=-1;
1.957 raeburn 7492: $delflag = 1;
1.357 www 7493: }
7494: }
7495: # send command
1.349 www 7496: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7497: # log new user role if status is ok
1.349 www 7498: if ($answer eq 'ok') {
1.663 raeburn 7499: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7500: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7501: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7502: unless ($role =~ /^gr/) {
7503: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7504: $origstart,$selfenroll,$context);
1.739 raeburn 7505: }
1.1053 raeburn 7506: if ($role eq 'cc') {
7507: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7508: }
1.349 www 7509: }
7510: return $answer;
1.169 harris41 7511: }
7512:
1.1053 raeburn 7513: sub autoupdate_coowners {
7514: my ($url,$end,$start,$uname,$udom) = @_;
7515: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7516: if (($cdom ne '') && ($cnum ne '')) {
7517: my $now = time;
7518: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7519: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7520: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7521: my $instcode = $coursehash{'internal.coursecode'};
7522: if ($instcode ne '') {
1.1056 raeburn 7523: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7524: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7525: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7526: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7527: if ($result eq 'valid') {
7528: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7529: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7530: push(@newcoowners,$coowner);
7531: }
7532: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7533: push(@newcoowners,$uname.':'.$udom);
7534: }
7535: @newcoowners = sort(@newcoowners);
7536: } else {
7537: push(@newcoowners,$uname.':'.$udom);
7538: }
7539: } else {
7540: if ($coursehash{'internal.co-owners'}) {
7541: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7542: unless ($coowner eq $uname.':'.$udom) {
7543: push(@newcoowners,$coowner);
7544: }
7545: }
7546: unless (@newcoowners > 0) {
7547: $delcoowners = 1;
7548: $coowners = '';
7549: }
7550: }
7551: }
7552: if (@newcoowners || $delcoowners) {
7553: &store_coowners($cdom,$cnum,$coursehash{'home'},
7554: $delcoowners,@newcoowners);
7555: }
7556: }
7557: }
7558: }
7559: }
7560: }
7561: }
7562:
7563: sub store_coowners {
7564: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7565: my $cid = $cdom.'_'.$cnum;
7566: my ($coowners,$delresult,$putresult);
7567: if (@newcoowners) {
7568: $coowners = join(',',@newcoowners);
7569: my %coownershash = (
7570: 'internal.co-owners' => $coowners,
7571: );
7572: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7573: if ($putresult eq 'ok') {
7574: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7575: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7576: }
7577: }
7578: }
7579: if ($delcoowners) {
7580: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7581: if ($delresult eq 'ok') {
7582: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7583: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7584: }
7585: }
7586: }
7587: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7588: my %crsinfo =
7589: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7590: if (ref($crsinfo{$cid}) eq 'HASH') {
7591: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7592: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7593: }
7594: }
7595: }
7596:
1.169 harris41 7597: # -------------------------------------------------- Modify user authentication
1.197 www 7598: # Overrides without validation
7599:
1.169 harris41 7600: sub modifyuserauth {
7601: my ($udom,$uname,$umode,$upass)=@_;
7602: my $uhome=&homeserver($uname,$udom);
1.197 www 7603: unless (&allowed('mau',$udom)) { return 'refused'; }
7604: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7605: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7606: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7607: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7608: &escape($upass),$uhome);
1.620 albertel 7609: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7610: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7611: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7612: &log($udom,,$uname,$uhome,
1.620 albertel 7613: 'Authentication changed by '.$env{'user.domain'}.', '.
7614: $env{'user.name'}.', '.$umode.
1.197 www 7615: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7616: unless ($reply eq 'ok') {
1.197 www 7617: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7618: return 'error: '.$reply;
7619: }
1.170 harris41 7620: return 'ok';
1.80 www 7621: }
7622:
1.81 www 7623: # --------------------------------------------------------------- Modify a user
1.80 www 7624:
1.81 www 7625: sub modifyuser {
1.206 matthew 7626: my ($udom, $uname, $uid,
7627: $umode, $upass, $first,
7628: $middle, $last, $gene,
1.1058 raeburn 7629: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7630: $udom= &LONCAPA::clean_domain($udom);
7631: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7632: my $showcandelete = 'none';
7633: if (ref($candelete) eq 'ARRAY') {
7634: if (@{$candelete} > 0) {
7635: $showcandelete = join(', ',@{$candelete});
7636: }
7637: }
1.81 www 7638: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7639: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7640: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7641: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7642: ' desiredhome not specified').
1.620 albertel 7643: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7644: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7645: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7646: my $newuser;
7647: if ($uhome eq 'no_host') {
7648: $newuser = 1;
7649: }
1.80 www 7650: # ----------------------------------------------------------------- Create User
1.406 albertel 7651: if (($uhome eq 'no_host') &&
7652: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7653: my $unhome='';
1.844 albertel 7654: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7655: $unhome = $desiredhome;
1.620 albertel 7656: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7657: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7658: } else { # load balancing routine for determining $unhome
1.81 www 7659: my $loadm=10000000;
1.841 albertel 7660: my %servers = &get_servers($udom,'library');
7661: foreach my $tryserver (keys(%servers)) {
7662: my $answer=reply('load',$tryserver);
7663: if (($answer=~/\d+/) && ($answer<$loadm)) {
7664: $loadm=$answer;
7665: $unhome=$tryserver;
7666: }
1.80 www 7667: }
7668: }
7669: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7670: return 'error: unable to find a home server for '.$uname.
7671: ' in domain '.$udom;
1.80 www 7672: }
7673: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7674: &escape($upass),$unhome);
7675: unless ($reply eq 'ok') {
7676: return 'error: '.$reply;
7677: }
1.230 stredwic 7678: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7679: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7680: return 'error: unable verify users home machine.';
1.80 www 7681: }
1.209 matthew 7682: } # End of creation of new user
1.80 www 7683: # ---------------------------------------------------------------------- Add ID
7684: if ($uid) {
7685: $uid=~tr/A-Z/a-z/;
7686: my %uidhash=&idrget($udom,$uname);
1.196 www 7687: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7688: && (!$forceid)) {
1.80 www 7689: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7690: return 'error: user id "'.$uid.'" does not match '.
7691: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7692: }
7693: } else {
7694: &idput($udom,($uname => $uid));
7695: }
7696: }
7697: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7698: my @tmp=&get('environment',
1.899 raeburn 7699: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7700: 'permanentemail','inststatus'],
1.134 albertel 7701: $udom,$uname);
1.1075 raeburn 7702: my (%names,%oldnames);
1.313 matthew 7703: if ($tmp[0] =~ m/^error:.*/) {
7704: %names=();
7705: } else {
7706: %names = @tmp;
1.1075 raeburn 7707: %oldnames = %names;
1.313 matthew 7708: }
1.388 www 7709: #
1.1058 raeburn 7710: # If name, email and/or uid are blank (e.g., because an uploaded file
7711: # of users did not contain them), do not overwrite existing values
7712: # unless field is in $candelete array ref.
7713: #
7714:
7715: my @fields = ('firstname','middlename','lastname','generation',
7716: 'permanentemail','id');
7717: my %newvalues;
7718: if (ref($candelete) eq 'ARRAY') {
7719: foreach my $field (@fields) {
7720: if (grep(/^\Q$field\E$/,@{$candelete})) {
7721: if ($field eq 'firstname') {
7722: $names{$field} = $first;
7723: } elsif ($field eq 'middlename') {
7724: $names{$field} = $middle;
7725: } elsif ($field eq 'lastname') {
7726: $names{$field} = $last;
7727: } elsif ($field eq 'generation') {
7728: $names{$field} = $gene;
7729: } elsif ($field eq 'permanentemail') {
7730: $names{$field} = $email;
7731: } elsif ($field eq 'id') {
7732: $names{$field} = $uid;
7733: }
7734: }
7735: }
7736: }
1.388 www 7737: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7738: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7739: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7740: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7741: if ($email) {
7742: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7743: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7744: }
1.899 raeburn 7745: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7746: if (defined($inststatus)) {
7747: $names{'inststatus'} = '';
7748: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7749: if (ref($usertypes) eq 'HASH') {
7750: my @okstatuses;
7751: foreach my $item (split(/:/,$inststatus)) {
7752: if (defined($usertypes->{$item})) {
7753: push(@okstatuses,$item);
7754: }
7755: }
7756: if (@okstatuses) {
7757: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7758: }
7759: }
7760: }
1.1075 raeburn 7761: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7762: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7763: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7764: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7765: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7766: } else {
7767: $logmsg .= ' during self creation';
7768: }
1.1075 raeburn 7769: my $changed;
7770: if ($newuser) {
7771: $changed = 1;
7772: } else {
7773: foreach my $field (@fields) {
7774: if ($names{$field} ne $oldnames{$field}) {
7775: $changed = 1;
7776: last;
7777: }
7778: }
7779: }
7780: unless ($changed) {
7781: $logmsg = 'No changes in user information needed for: '.$logmsg;
7782: &logthis($logmsg);
7783: return 'ok';
7784: }
7785: my $reply = &put('environment', \%names, $udom,$uname);
7786: if ($reply ne 'ok') {
7787: return 'error: '.$reply;
7788: }
1.1087 raeburn 7789: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7790: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7791: }
1.1075 raeburn 7792: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7793: &devalidate_cache_new('namescache',$uname.':'.$udom);
7794: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7795: &logthis($logmsg);
1.134 albertel 7796: return 'ok';
1.80 www 7797: }
7798:
1.81 www 7799: # -------------------------------------------------------------- Modify student
1.80 www 7800:
1.81 www 7801: sub modifystudent {
7802: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7803: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7804: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7805: if (!$cid) {
1.620 albertel 7806: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7807: return 'not_in_class';
7808: }
1.80 www 7809: }
7810: # --------------------------------------------------------------- Make the user
1.81 www 7811: my $reply=&modifyuser
1.209 matthew 7812: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7813: $desiredhome,$email,$inststatus);
1.80 www 7814: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7815: # This will cause &modify_student_enrollment to get the uid from the
7816: # students environment
7817: $uid = undef if (!$forceid);
1.455 albertel 7818: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7819: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7820: return $reply;
7821: }
7822:
7823: sub modify_student_enrollment {
1.957 raeburn 7824: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7825: my ($cdom,$cnum,$chome);
7826: if (!$cid) {
1.620 albertel 7827: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7828: return 'not_in_class';
7829: }
1.620 albertel 7830: $cdom=$env{'course.'.$cid.'.domain'};
7831: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7832: } else {
7833: ($cdom,$cnum)=split(/_/,$cid);
7834: }
1.620 albertel 7835: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7836: if (!$chome) {
1.457 raeburn 7837: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7838: }
1.455 albertel 7839: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7840: # Make sure the user exists
1.81 www 7841: my $uhome=&homeserver($uname,$udom);
7842: if (($uhome eq '') || ($uhome eq 'no_host')) {
7843: return 'error: no such user';
7844: }
1.297 matthew 7845: # Get student data if we were not given enough information
7846: if (!defined($first) || $first eq '' ||
7847: !defined($last) || $last eq '' ||
7848: !defined($uid) || $uid eq '' ||
7849: !defined($middle) || $middle eq '' ||
7850: !defined($gene) || $gene eq '') {
1.294 matthew 7851: # They did not supply us with enough data to enroll the student, so
7852: # we need to pick up more information.
1.297 matthew 7853: my %tmp = &get('environment',
1.294 matthew 7854: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7855: ,$udom,$uname);
7856:
1.800 albertel 7857: #foreach my $key (keys(%tmp)) {
7858: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7859: #}
1.294 matthew 7860: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7861: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7862: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7863: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7864: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7865: }
1.556 albertel 7866: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7867: my $user = "$uname:$udom";
7868: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7869: my $reply=cput('classlist',
1.1148 raeburn 7870: {$user =>
1.515 raeburn 7871: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7872: $cdom,$cnum);
1.1148 raeburn 7873: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7874: &devalidate_getsection_cache($udom,$uname,$cid);
7875: } else {
1.81 www 7876: return 'error: '.$reply;
7877: }
1.297 matthew 7878: # Add student role to user
1.83 www 7879: my $uurl='/'.$cid;
1.81 www 7880: $uurl=~s/\_/\//g;
7881: if ($usec) {
7882: $uurl.='/'.$usec;
7883: }
1.1148 raeburn 7884: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7885: $selfenroll,$context);
7886: if ($result ne 'ok') {
7887: if ($old_entry{$user} ne '') {
7888: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7889: } else {
7890: $reply = &del('classlist',[$user],$cdom,$cnum);
7891: }
7892: }
7893: return $result;
1.21 www 7894: }
7895:
1.556 albertel 7896: sub format_name {
7897: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7898: my $name;
7899: if ($first ne 'lastname') {
7900: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7901: } else {
7902: if ($lastname=~/\S/) {
7903: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7904: $name=~s/\s+,/,/;
7905: } else {
7906: $name.= $firstname.' '.$middlename.' '.$generation;
7907: }
7908: }
7909: $name=~s/^\s+//;
7910: $name=~s/\s+$//;
7911: $name=~s/\s+/ /g;
7912: return $name;
7913: }
7914:
1.84 www 7915: # ------------------------------------------------- Write to course preferences
7916:
7917: sub writecoursepref {
7918: my ($courseid,%prefs)=@_;
7919: $courseid=~s/^\///;
7920: $courseid=~s/\_/\//g;
7921: my ($cdomain,$cnum)=split(/\//,$courseid);
7922: my $chome=homeserver($cnum,$cdomain);
7923: if (($chome eq '') || ($chome eq 'no_host')) {
7924: return 'error: no such course';
7925: }
7926: my $cstring='';
1.800 albertel 7927: foreach my $pref (keys(%prefs)) {
7928: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7929: }
1.84 www 7930: $cstring=~s/\&$//;
7931: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7932: }
7933:
7934: # ---------------------------------------------------------- Make/modify course
7935:
7936: sub createcourse {
1.741 raeburn 7937: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7938: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7939: $url=&declutter($url);
7940: my $cid='';
1.1028 raeburn 7941: if ($context eq 'requestcourses') {
7942: my $can_create = 0;
7943: my ($ownername,$ownerdom) = split(':',$course_owner);
7944: if ($udom eq $ownerdom) {
7945: if (&usertools_access($ownername,$ownerdom,$category,undef,
7946: $context)) {
7947: $can_create = 1;
7948: }
7949: } else {
7950: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7951: $category);
7952: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7953: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7954: if (@curr > 0) {
7955: my @options = qw(approval validate autolimit);
7956: my $optregex = join('|',@options);
7957: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7958: $can_create = 1;
7959: }
7960: }
7961: }
7962: }
7963: if ($can_create) {
7964: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7965: unless (&allowed('ccc',$udom)) {
7966: return 'refused';
7967: }
1.1017 raeburn 7968: }
7969: } else {
7970: return 'refused';
7971: }
1.1028 raeburn 7972: } elsif (!&allowed('ccc',$udom)) {
7973: return 'refused';
1.84 www 7974: }
1.1011 raeburn 7975: # --------------------------------------------------------------- Get Unique ID
7976: my $uname;
7977: if ($cnum =~ /^$match_courseid$/) {
7978: my $chome=&homeserver($cnum,$udom,'true');
7979: if (($chome eq '') || ($chome eq 'no_host')) {
7980: $uname = $cnum;
7981: } else {
1.1038 raeburn 7982: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7983: }
7984: } else {
1.1038 raeburn 7985: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7986: }
7987: return $uname if ($uname =~ /^error/);
7988: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7989: if (!defined($course_server)) {
7990: if (defined(&domain($udom,'primary'))) {
7991: $course_server = &domain($udom,'primary');
7992: } else {
7993: $course_server = $env{'user.home'};
7994: }
7995: }
7996: my %host_servers =
7997: &Apache::lonnet::get_servers($udom,'library');
7998: unless ($host_servers{$course_server}) {
7999: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8000: }
1.84 www 8001: # ------------------------------------------------------------- Make the course
8002: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8003: $course_server);
1.84 www 8004: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8005: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8006: if (($uhome eq '') || ($uhome eq 'no_host')) {
8007: return 'error: no such course';
8008: }
1.271 www 8009: # ----------------------------------------------------------------- Course made
1.516 raeburn 8010: # log existence
1.1029 raeburn 8011: my $now = time;
1.918 raeburn 8012: my $newcourse = {
8013: $udom.'_'.$uname => {
1.921 raeburn 8014: description => $description,
8015: inst_code => $inst_code,
8016: owner => $course_owner,
8017: type => $crstype,
1.1029 raeburn 8018: creator => $env{'user.name'}.':'.
8019: $env{'user.domain'},
8020: created => $now,
8021: context => $context,
1.918 raeburn 8022: },
8023: };
1.921 raeburn 8024: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8025: # set toplevel url
1.271 www 8026: my $topurl=$url;
8027: unless ($nonstandard) {
8028: # ------------------------------------------ For standard courses, make top url
8029: my $mapurl=&clutter($url);
1.278 www 8030: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8031: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8032: <map>
8033: <resource id="1" type="start"></resource>
8034: <resource id="2" src="$mapurl"></resource>
8035: <resource id="3" type="finish"></resource>
8036: <link index="1" from="1" to="2"></link>
8037: <link index="2" from="2" to="3"></link>
8038: </map>
8039: ENDINITMAP
8040: $topurl=&declutter(
1.638 albertel 8041: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8042: );
8043: }
8044: # ----------------------------------------------------------- Write preferences
1.84 www 8045: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8046: ('description' => $description,
8047: 'url' => $topurl,
8048: 'internal.creator' => $env{'user.name'}.':'.
8049: $env{'user.domain'},
8050: 'internal.created' => $now,
8051: 'internal.creationcontext' => $context)
8052: );
1.84 www 8053: return '/'.$udom.'/'.$uname;
8054: }
8055:
1.1011 raeburn 8056: # ------------------------------------------------------------------- Create ID
8057: sub generate_coursenum {
1.1038 raeburn 8058: my ($udom,$crstype) = @_;
1.1011 raeburn 8059: my $domdesc = &domain($udom);
8060: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8061: my $first;
8062: if ($crstype eq 'Community') {
8063: $first = '0';
8064: } else {
8065: $first = int(1+rand(9));
8066: }
8067: my $uname=$first.
1.1011 raeburn 8068: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8069: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8070: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8071: # ----------------------------------------------- Make sure that does not exist
8072: my $uhome=&homeserver($uname,$udom,'true');
8073: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8074: if ($crstype eq 'Community') {
8075: $first = '0';
8076: } else {
8077: $first = int(1+rand(9));
8078: }
8079: $uname=$first.
1.1011 raeburn 8080: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8081: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8082: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8083: $uhome=&homeserver($uname,$udom,'true');
8084: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8085: return 'error: unable to generate unique course-ID';
8086: }
8087: }
8088: return $uname;
8089: }
8090:
1.813 albertel 8091: sub is_course {
1.1167 droeschl 8092: my ($cdom, $cnum) = scalar(@_) == 1 ?
8093: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8094:
8095: return unless $cdom and $cnum;
8096:
8097: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8098: '.');
8099:
8100: return unless exists($courses{$cdom.'_'.$cnum});
8101: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8102: }
8103:
1.1015 raeburn 8104: sub store_userdata {
8105: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8106: my $result;
1.1016 raeburn 8107: if ($datakey ne '') {
1.1013 raeburn 8108: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8109: if ($udom eq '' || $uname eq '') {
8110: $udom = $env{'user.domain'};
8111: $uname = $env{'user.name'};
8112: }
8113: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8114: if (($uhome eq '') || ($uhome eq 'no_host')) {
8115: $result = 'error: no_host';
8116: } else {
8117: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8118: $storehash->{'host'} = $perlvar{'lonHostID'};
8119:
8120: my $namevalue='';
8121: foreach my $key (keys(%{$storehash})) {
8122: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8123: }
8124: $namevalue=~s/\&$//;
1.1105 raeburn 8125: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8126: $namevalue,$uhome);
1.1013 raeburn 8127: }
8128: } else {
8129: $result = 'error: data to store was not a hash reference';
8130: }
8131: } else {
8132: $result= 'error: invalid requestkey';
8133: }
8134: return $result;
8135: }
8136:
1.21 www 8137: # ---------------------------------------------------------- Assign Custom Role
8138:
8139: sub assigncustomrole {
1.957 raeburn 8140: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8141: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8142: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8143: }
8144:
8145: # ----------------------------------------------------------------- Revoke Role
8146:
8147: sub revokerole {
1.957 raeburn 8148: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8149: my $now=time;
1.965 raeburn 8150: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8151: }
8152:
8153: # ---------------------------------------------------------- Revoke Custom Role
8154:
8155: sub revokecustomrole {
1.957 raeburn 8156: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8157: my $now=time;
1.357 www 8158: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8159: $deleteflag,$selfenroll,$context);
1.17 www 8160: }
8161:
1.533 banghart 8162: # ------------------------------------------------------------ Disk usage
1.535 albertel 8163: sub diskusage {
1.955 raeburn 8164: my ($udom,$uname,$directorypath,$getpropath)=@_;
8165: $directorypath =~ s/\/$//;
8166: my $listing=&reply('du2:'.&escape($directorypath).':'
8167: .&escape($getpropath).':'.&escape($uname).':'
8168: .&escape($udom),homeserver($uname,$udom));
8169: if ($listing eq 'unknown_cmd') {
8170: if ($getpropath) {
8171: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8172: }
8173: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8174: }
1.514 albertel 8175: return $listing;
1.512 banghart 8176: }
8177:
1.566 banghart 8178: sub is_locked {
1.1096 raeburn 8179: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8180: my @check;
8181: my $is_locked;
1.1093 raeburn 8182: push (@check,$file_name);
1.613 albertel 8183: my %locked = &get('file_permissions',\@check,
1.620 albertel 8184: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8185: my ($tmp)=keys(%locked);
8186: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8187:
1.566 banghart 8188: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8189: $is_locked = 'false';
8190: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8191: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8192: $is_locked = 'true';
1.1096 raeburn 8193: if (ref($which) eq 'ARRAY') {
8194: push(@{$which},$entry);
8195: } else {
8196: last;
8197: }
1.745 raeburn 8198: }
8199: }
1.566 banghart 8200: } else {
8201: $is_locked = 'false';
8202: }
1.1093 raeburn 8203: return $is_locked;
1.566 banghart 8204: }
8205:
1.759 albertel 8206: sub declutter_portfile {
8207: my ($file) = @_;
1.833 albertel 8208: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8209: return $file;
8210: }
8211:
1.559 banghart 8212: # ------------------------------------------------------------- Mark as Read Only
8213:
8214: sub mark_as_readonly {
8215: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8216: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8217: my ($tmp)=keys(%current_permissions);
8218: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8219: foreach my $file (@{$files}) {
1.759 albertel 8220: $file = &declutter_portfile($file);
1.561 banghart 8221: push(@{$current_permissions{$file}},$what);
1.559 banghart 8222: }
1.613 albertel 8223: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8224: return;
8225: }
8226:
1.572 banghart 8227: # ------------------------------------------------------------Save Selected Files
8228:
8229: sub save_selected_files {
8230: my ($user, $path, @files) = @_;
8231: my $filename = $user."savedfiles";
1.573 banghart 8232: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8233: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8234: foreach my $file (@files) {
1.620 albertel 8235: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8236: }
8237: foreach my $file (@other_files) {
1.574 banghart 8238: print (OUT $file."\n");
1.572 banghart 8239: }
1.574 banghart 8240: close (OUT);
1.572 banghart 8241: return 'ok';
8242: }
8243:
1.574 banghart 8244: sub clear_selected_files {
8245: my ($user) = @_;
8246: my $filename = $user."savedfiles";
1.1117 foxr 8247: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8248: print (OUT undef);
8249: close (OUT);
8250: return ("ok");
8251: }
8252:
1.572 banghart 8253: sub files_in_path {
8254: my ($user, $path) = @_;
8255: my $filename = $user."savedfiles";
8256: my %return_files;
1.1117 foxr 8257: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8258: while (my $line_in = <IN>) {
1.574 banghart 8259: chomp ($line_in);
8260: my @paths_and_file = split (m!/!, $line_in);
8261: my $file_part = pop (@paths_and_file);
8262: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8263: $path_part.='/';
8264: my $path_and_file = $path_part.$file_part;
8265: if ($path_part eq $path) {
8266: $return_files{$file_part}= 'selected';
8267: }
8268: }
1.574 banghart 8269: close (IN);
8270: return (\%return_files);
1.572 banghart 8271: }
8272:
8273: # called in portfolio select mode, to show files selected NOT in current directory
8274: sub files_not_in_path {
8275: my ($user, $path) = @_;
8276: my $filename = $user."savedfiles";
8277: my @return_files;
8278: my $path_part;
1.1117 foxr 8279: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8280: while (my $line = <IN>) {
1.572 banghart 8281: #ok, I know it's clunky, but I want it to work
1.800 albertel 8282: my @paths_and_file = split(m|/|, $line);
8283: my $file_part = pop(@paths_and_file);
8284: chomp($file_part);
8285: my $path_part = join('/', @paths_and_file);
1.572 banghart 8286: $path_part .= '/';
8287: my $path_and_file = $path_part.$file_part;
8288: if ($path_part ne $path) {
1.800 albertel 8289: push(@return_files, ($path_and_file));
1.572 banghart 8290: }
8291: }
1.800 albertel 8292: close(OUT);
1.574 banghart 8293: return (@return_files);
1.572 banghart 8294: }
8295:
1.745 raeburn 8296: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8297:
1.745 raeburn 8298: sub get_portfile_permissions {
8299: my ($domain,$user) = @_;
1.613 albertel 8300: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8301: my ($tmp)=keys(%current_permissions);
8302: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8303: return \%current_permissions;
8304: }
8305:
8306: #---------------------------------------------Get portfolio file access controls
8307:
1.749 raeburn 8308: sub get_access_controls {
1.745 raeburn 8309: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8310: my %access;
8311: my $real_file = $file;
8312: $file =~ s/\.meta$//;
1.745 raeburn 8313: if (defined($file)) {
1.749 raeburn 8314: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8315: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8316: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8317: }
8318: }
1.745 raeburn 8319: } else {
1.749 raeburn 8320: foreach my $key (keys(%{$current_permissions})) {
8321: if ($key =~ /\0accesscontrol$/) {
8322: if (defined($group)) {
8323: if ($key !~ m-^\Q$group\E/-) {
8324: next;
8325: }
8326: }
8327: my ($fullpath) = split(/\0/,$key);
8328: if (ref($$current_permissions{$key}) eq 'HASH') {
8329: foreach my $control (keys(%{$$current_permissions{$key}})) {
8330: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8331: }
8332: }
8333: }
8334: }
8335: }
8336: return %access;
8337: }
8338:
8339: sub modify_access_controls {
8340: my ($file_name,$changes,$domain,$user)=@_;
8341: my ($outcome,$deloutcome);
8342: my %store_permissions;
8343: my %new_values;
8344: my %new_control;
8345: my %translation;
8346: my @deletions = ();
8347: my $now = time;
8348: if (exists($$changes{'activate'})) {
8349: if (ref($$changes{'activate'}) eq 'HASH') {
8350: my @newitems = sort(keys(%{$$changes{'activate'}}));
8351: my $numnew = scalar(@newitems);
8352: for (my $i=0; $i<$numnew; $i++) {
8353: my $newkey = $newitems[$i];
8354: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8355: if ($newkey =~ /^\d+:/) {
8356: $newkey =~ s/^(\d+)/$newid/;
8357: $translation{$1} = $newid;
8358: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8359: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8360: $translation{$1} = $newid;
8361: }
1.749 raeburn 8362: $new_values{$file_name."\0".$newkey} =
8363: $$changes{'activate'}{$newitems[$i]};
8364: $new_control{$newkey} = $now;
8365: }
8366: }
8367: }
8368: my %todelete;
8369: my %changed_items;
8370: foreach my $action ('delete','update') {
8371: if (exists($$changes{$action})) {
8372: if (ref($$changes{$action}) eq 'HASH') {
8373: foreach my $key (keys(%{$$changes{$action}})) {
8374: my ($itemnum) = ($key =~ /^([^:]+):/);
8375: if ($action eq 'delete') {
8376: $todelete{$itemnum} = 1;
8377: } else {
8378: $changed_items{$itemnum} = $key;
8379: }
8380: }
1.745 raeburn 8381: }
8382: }
1.749 raeburn 8383: }
8384: # get lock on access controls for file.
8385: my $lockhash = {
8386: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8387: ':'.$env{'user.domain'},
8388: };
8389: my $tries = 0;
8390: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8391:
8392: while (($gotlock ne 'ok') && $tries <3) {
8393: $tries ++;
8394: sleep 1;
8395: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8396: }
8397: if ($gotlock eq 'ok') {
8398: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8399: my ($tmp)=keys(%curr_permissions);
8400: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8401: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8402: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8403: if (ref($curr_controls) eq 'HASH') {
8404: foreach my $control_item (keys(%{$curr_controls})) {
8405: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8406: if (defined($todelete{$itemnum})) {
8407: push(@deletions,$file_name."\0".$control_item);
8408: } else {
8409: if (defined($changed_items{$itemnum})) {
8410: $new_control{$changed_items{$itemnum}} = $now;
8411: push(@deletions,$file_name."\0".$control_item);
8412: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8413: } else {
8414: $new_control{$control_item} = $$curr_controls{$control_item};
8415: }
8416: }
1.745 raeburn 8417: }
8418: }
8419: }
1.970 raeburn 8420: my ($group);
8421: if (&is_course($domain,$user)) {
8422: ($group,my $file) = split(/\//,$file_name,2);
8423: }
1.749 raeburn 8424: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8425: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8426: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8427: # remove lock
8428: my @del_lock = ($file_name."\0".'locked_access_records');
8429: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8430: my $sqlresult =
1.970 raeburn 8431: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8432: $group);
1.749 raeburn 8433: } else {
8434: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8435: }
1.749 raeburn 8436: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8437: }
8438:
1.827 raeburn 8439: sub make_public_indefinitely {
8440: my ($requrl) = @_;
8441: my $now = time;
8442: my $action = 'activate';
8443: my $aclnum = 0;
8444: if (&is_portfolio_url($requrl)) {
8445: my (undef,$udom,$unum,$file_name,$group) =
8446: &parse_portfolio_url($requrl);
8447: my $current_perms = &get_portfile_permissions($udom,$unum);
8448: my %access_controls = &get_access_controls($current_perms,
8449: $group,$file_name);
8450: foreach my $key (keys(%{$access_controls{$file_name}})) {
8451: my ($num,$scope,$end,$start) =
8452: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8453: if ($scope eq 'public') {
8454: if ($start <= $now && $end == 0) {
8455: $action = 'none';
8456: } else {
8457: $action = 'update';
8458: $aclnum = $num;
8459: }
8460: last;
8461: }
8462: }
8463: if ($action eq 'none') {
8464: return 'ok';
8465: } else {
8466: my %changes;
8467: my $newend = 0;
8468: my $newstart = $now;
8469: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8470: $changes{$action}{$newkey} = {
8471: type => 'public',
8472: time => {
8473: start => $newstart,
8474: end => $newend,
8475: },
8476: };
8477: my ($outcome,$deloutcome,$new_values,$translation) =
8478: &modify_access_controls($file_name,\%changes,$udom,$unum);
8479: return $outcome;
8480: }
8481: } else {
8482: return 'invalid';
8483: }
8484: }
8485:
1.745 raeburn 8486: #------------------------------------------------------Get Marked as Read Only
8487:
8488: sub get_marked_as_readonly {
8489: my ($domain,$user,$what,$group) = @_;
8490: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8491: my @readonly_files;
1.629 banghart 8492: my $cmp1=$what;
8493: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8494: while (my ($file_name,$value) = each(%{$current_permissions})) {
8495: if (defined($group)) {
8496: if ($file_name !~ m-^\Q$group\E/-) {
8497: next;
8498: }
8499: }
1.561 banghart 8500: if (ref($value) eq "ARRAY"){
8501: foreach my $stored_what (@{$value}) {
1.629 banghart 8502: my $cmp2=$stored_what;
1.759 albertel 8503: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8504: $cmp2=join('',@{$stored_what});
1.745 raeburn 8505: }
1.629 banghart 8506: if ($cmp1 eq $cmp2) {
1.561 banghart 8507: push(@readonly_files, $file_name);
1.745 raeburn 8508: last;
1.563 banghart 8509: } elsif (!defined($what)) {
8510: push(@readonly_files, $file_name);
1.745 raeburn 8511: last;
1.561 banghart 8512: }
8513: }
1.745 raeburn 8514: }
1.561 banghart 8515: }
8516: return @readonly_files;
8517: }
1.577 banghart 8518: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8519:
1.577 banghart 8520: sub get_marked_as_readonly_hash {
1.745 raeburn 8521: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8522: my %readonly_files;
1.745 raeburn 8523: while (my ($file_name,$value) = each(%{$current_permissions})) {
8524: if (defined($group)) {
8525: if ($file_name !~ m-^\Q$group\E/-) {
8526: next;
8527: }
8528: }
1.577 banghart 8529: if (ref($value) eq "ARRAY"){
8530: foreach my $stored_what (@{$value}) {
1.745 raeburn 8531: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8532: foreach my $lock_descriptor(@{$stored_what}) {
8533: if ($lock_descriptor eq 'graded') {
8534: $readonly_files{$file_name} = 'graded';
8535: } elsif ($lock_descriptor eq 'handback') {
8536: $readonly_files{$file_name} = 'handback';
8537: } else {
8538: if (!exists($readonly_files{$file_name})) {
8539: $readonly_files{$file_name} = 'locked';
8540: }
8541: }
1.745 raeburn 8542: }
1.750 banghart 8543: }
1.577 banghart 8544: }
8545: }
8546: }
8547: return %readonly_files;
8548: }
1.559 banghart 8549: # ------------------------------------------------------------ Unmark as Read Only
8550:
8551: sub unmark_as_readonly {
1.629 banghart 8552: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8553: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8554: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8555: $file_name = &declutter_portfile($file_name);
1.634 albertel 8556: my $symb_crs = $what;
8557: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8558: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8559: my ($tmp)=keys(%current_permissions);
8560: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8561: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8562: foreach my $file (@readonly_files) {
1.759 albertel 8563: my $clean_file = &declutter_portfile($file);
8564: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8565: my $current_locks = $current_permissions{$file};
1.563 banghart 8566: my @new_locks;
8567: my @del_keys;
8568: if (ref($current_locks) eq "ARRAY"){
8569: foreach my $locker (@{$current_locks}) {
1.632 albertel 8570: my $compare=$locker;
1.749 raeburn 8571: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8572: $compare=join('',@{$locker});
1.746 raeburn 8573: if ($compare ne $symb_crs) {
8574: push(@new_locks, $locker);
8575: }
1.563 banghart 8576: }
8577: }
1.650 albertel 8578: if (scalar(@new_locks) > 0) {
1.563 banghart 8579: $current_permissions{$file} = \@new_locks;
8580: } else {
8581: push(@del_keys, $file);
1.613 albertel 8582: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8583: delete($current_permissions{$file});
1.563 banghart 8584: }
8585: }
1.561 banghart 8586: }
1.613 albertel 8587: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8588: return;
8589: }
1.512 banghart 8590:
1.17 www 8591: # ------------------------------------------------------------ Directory lister
8592:
8593: sub dirlist {
1.955 raeburn 8594: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8595: $uri=~s/^\///;
8596: $uri=~s/\/$//;
1.253 stredwic 8597: my ($udom, $uname);
1.955 raeburn 8598: if ($getuserdir) {
1.253 stredwic 8599: $udom = $userdomain;
8600: $uname = $username;
1.955 raeburn 8601: } else {
8602: (undef,$udom,$uname)=split(/\//,$uri);
8603: if(defined($userdomain)) {
8604: $udom = $userdomain;
8605: }
8606: if(defined($username)) {
8607: $uname = $username;
8608: }
1.253 stredwic 8609: }
1.955 raeburn 8610: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8611:
1.955 raeburn 8612: $dirRoot = $perlvar{'lonDocRoot'};
8613: if (defined($getpropath)) {
8614: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8615: $dirRoot =~ s/\/$//;
1.955 raeburn 8616: } elsif (defined($getuserdir)) {
8617: my $subdir=$uname.'__';
8618: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8619: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8620: ."/$udom/$subdir/$uname";
8621: } elsif (defined($alternateRoot)) {
8622: $dirRoot = $alternateRoot;
1.751 banghart 8623: }
1.253 stredwic 8624:
8625: if($udom) {
8626: if($uname) {
1.1135 raeburn 8627: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8628: if ($uhome eq 'no_host') {
8629: return ([],'no_host');
8630: }
1.955 raeburn 8631: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8632: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8633: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8634: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8635: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8636: } else {
8637: @listing_results = map { &unescape($_); } split(/:/,$listing);
8638: }
1.605 matthew 8639: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8640: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8641: @listing_results = split(/:/,$listing);
8642: } else {
8643: @listing_results = map { &unescape($_); } split(/:/,$listing);
8644: }
1.1135 raeburn 8645: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8646: ($listing eq 'rejected') || ($listing eq 'refused') ||
8647: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8648: return ([],$listing);
8649: } else {
8650: return (\@listing_results);
1.1135 raeburn 8651: }
1.955 raeburn 8652: } elsif(!$alternateRoot) {
1.1136 raeburn 8653: my (%allusers,%listerror);
1.841 albertel 8654: my %servers = &get_servers($udom,'library');
1.955 raeburn 8655: foreach my $tryserver (keys(%servers)) {
8656: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8657: &escape($udom),$tryserver);
8658: if ($listing eq 'unknown_cmd') {
8659: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8660: $udom, $tryserver);
8661: } else {
8662: @listing_results = map { &unescape($_); } split(/:/,$listing);
8663: }
1.841 albertel 8664: if ($listing eq 'unknown_cmd') {
8665: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8666: $udom, $tryserver);
8667: @listing_results = split(/:/,$listing);
8668: } else {
8669: @listing_results =
8670: map { &unescape($_); } split(/:/,$listing);
8671: }
1.1136 raeburn 8672: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8673: ($listing eq 'rejected') || ($listing eq 'refused') ||
8674: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8675: $listerror{$tryserver} = $listing;
8676: } else {
1.841 albertel 8677: foreach my $line (@listing_results) {
8678: my ($entry) = split(/&/,$line,2);
8679: $allusers{$entry} = 1;
8680: }
8681: }
1.253 stredwic 8682: }
1.1136 raeburn 8683: my @alluserslist=();
1.800 albertel 8684: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8685: push(@alluserslist,$user.'&user');
1.253 stredwic 8686: }
1.1136 raeburn 8687: return (\@alluserslist);
1.253 stredwic 8688: } else {
1.1136 raeburn 8689: return ([],'missing username');
1.253 stredwic 8690: }
1.955 raeburn 8691: } elsif(!defined($getpropath)) {
1.1136 raeburn 8692: my $path = $perlvar{'lonDocRoot'}.'/res/';
8693: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8694: return (\@all_domains);
1.955 raeburn 8695: } else {
1.1136 raeburn 8696: return ([],'missing domain');
1.275 stredwic 8697: }
8698: }
8699:
8700: # --------------------------------------------- GetFileTimestamp
8701: # This function utilizes dirlist and returns the date stamp for
8702: # when it was last modified. It will also return an error of -1
8703: # if an error occurs
8704:
8705: sub GetFileTimestamp {
1.955 raeburn 8706: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8707: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8708: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8709: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8710: undef,$getuserdir);
8711: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8712: return -1;
8713: }
8714: if (ref($fileref) eq 'ARRAY') {
8715: my @stats = split('&',$fileref->[0]);
1.375 matthew 8716: # @stats contains first the filename, then the stat output
8717: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8718: } else {
8719: return -1;
1.253 stredwic 8720: }
1.26 www 8721: }
8722:
1.712 albertel 8723: sub stat_file {
8724: my ($uri) = @_;
1.787 albertel 8725: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8726:
1.955 raeburn 8727: my ($udom,$uname,$file);
1.712 albertel 8728: if ($uri =~ m-^/(uploaded|editupload)/-) {
8729: ($udom,$uname,$file) =
1.811 albertel 8730: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8731: $file = 'userfiles/'.$file;
8732: }
8733: if ($uri =~ m-^/res/-) {
8734: ($udom,$uname) =
1.807 albertel 8735: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8736: $file = $uri;
8737: }
8738:
8739: if (!$udom || !$uname || !$file) {
8740: # unable to handle the uri
8741: return ();
8742: }
1.956 raeburn 8743: my $getpropath;
8744: if ($file =~ /^userfiles\//) {
8745: $getpropath = 1;
8746: }
1.1136 raeburn 8747: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8748: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8749: return ();
8750: } else {
8751: if (ref($listref) eq 'ARRAY') {
8752: my @stats = split('&',$listref->[0]);
8753: shift(@stats); #filename is first
8754: return @stats;
8755: }
1.712 albertel 8756: }
8757: return ();
8758: }
8759:
1.26 www 8760: # -------------------------------------------------------- Value of a Condition
8761:
1.713 albertel 8762: # gets the value of a specific preevaluated condition
8763: # stored in the string $env{user.state.<cid>}
8764: # or looks up a condition reference in the bighash and if if hasn't
8765: # already been evaluated recurses into docondval to get the value of
8766: # the condition, then memoizing it to
8767: # $env{user.state.<cid>.<condition>}
1.40 www 8768: sub directcondval {
8769: my $number=shift;
1.620 albertel 8770: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8771: &Apache::lonuserstate::evalstate();
8772: }
1.713 albertel 8773: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8774: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8775: } elsif ($number =~ /^_/) {
8776: my $sub_condition;
8777: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8778: &GDBM_READER(),0640)) {
8779: $sub_condition=$bighash{'conditions'.$number};
8780: untie(%bighash);
8781: }
8782: my $value = &docondval($sub_condition);
1.949 raeburn 8783: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8784: return $value;
8785: }
1.620 albertel 8786: if ($env{'user.state.'.$env{'request.course.id'}}) {
8787: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8788: } else {
8789: return 2;
8790: }
8791: }
8792:
1.713 albertel 8793: # get the collection of conditions for this resource
1.26 www 8794: sub condval {
8795: my $condidx=shift;
1.54 www 8796: my $allpathcond='';
1.713 albertel 8797: foreach my $cond (split(/\|/,$condidx)) {
8798: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8799: $allpathcond.=
8800: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8801: }
1.191 harris41 8802: }
1.54 www 8803: $allpathcond=~s/\|$//;
1.713 albertel 8804: return &docondval($allpathcond);
8805: }
8806:
8807: #evaluates an expression of conditions
8808: sub docondval {
8809: my ($allpathcond) = @_;
8810: my $result=0;
8811: if ($env{'request.course.id'}
8812: && defined($allpathcond)) {
8813: my $operand='|';
8814: my @stack;
8815: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8816: if ($chunk eq '(') {
8817: push @stack,($operand,$result);
8818: } elsif ($chunk eq ')') {
8819: my $before=pop @stack;
8820: if (pop @stack eq '&') {
8821: $result=$result>$before?$before:$result;
8822: } else {
8823: $result=$result>$before?$result:$before;
8824: }
8825: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8826: $operand=$chunk;
8827: } else {
8828: my $new=directcondval($chunk);
8829: if ($operand eq '&') {
8830: $result=$result>$new?$new:$result;
8831: } else {
8832: $result=$result>$new?$result:$new;
8833: }
8834: }
8835: }
1.26 www 8836: }
8837: return $result;
1.421 albertel 8838: }
8839:
8840: # ---------------------------------------------------- Devalidate courseresdata
8841:
8842: sub devalidatecourseresdata {
8843: my ($coursenum,$coursedomain)=@_;
8844: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8845: &devalidate_cache_new('courseres',$hashid);
1.28 www 8846: }
8847:
1.763 www 8848:
1.200 www 8849: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8850: #
8851: # Parameters:
8852: # $coursenum - Number of the course.
8853: # $coursedomain - Domain at which the course was created.
8854: # Returns:
8855: # A hash of the course parameters along (I think) with timestamps
8856: # and version info.
1.877 foxr 8857:
1.624 albertel 8858: sub get_courseresdata {
8859: my ($coursenum,$coursedomain)=@_;
1.200 www 8860: my $coursehom=&homeserver($coursenum,$coursedomain);
8861: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8862: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8863: my %dumpreply;
1.417 albertel 8864: unless (defined($cached)) {
1.624 albertel 8865: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8866: $result=\%dumpreply;
1.251 albertel 8867: my ($tmp) = keys(%dumpreply);
8868: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8869: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8870: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8871: return $tmp;
1.416 albertel 8872: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8873: $result=undef;
1.599 albertel 8874: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8875: }
8876: }
1.624 albertel 8877: return $result;
8878: }
8879:
1.633 albertel 8880: sub devalidateuserresdata {
8881: my ($uname,$udom)=@_;
8882: my $hashid="$udom:$uname";
8883: &devalidate_cache_new('userres',$hashid);
8884: }
8885:
1.624 albertel 8886: sub get_userresdata {
8887: my ($uname,$udom)=@_;
8888: #most student don\'t have any data set, check if there is some data
8889: if (&EXT_cache_status($udom,$uname)) { return undef; }
8890:
8891: my $hashid="$udom:$uname";
8892: my ($result,$cached)=&is_cached_new('userres',$hashid);
8893: if (!defined($cached)) {
8894: my %resourcedata=&dump('resourcedata',$udom,$uname);
8895: $result=\%resourcedata;
8896: &do_cache_new('userres',$hashid,$result,600);
8897: }
8898: my ($tmp)=keys(%$result);
8899: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8900: return $result;
8901: }
8902: #error 2 occurs when the .db doesn't exist
8903: if ($tmp!~/error: 2 /) {
1.672 albertel 8904: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8905: " Trying to get resource data for ".
8906: $uname." at ".$udom.": ".
8907: $tmp."</font>");
8908: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8909: #&EXT_cache_set($udom,$uname);
8910: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8911: undef($tmp); # not really an error so don't send it back
1.624 albertel 8912: }
8913: return $tmp;
8914: }
1.879 foxr 8915: #----------------------------------------------- resdata - return resource data
8916: # Purpose:
8917: # Return resource data for either users or for a course.
8918: # Parameters:
8919: # $name - Course/user name.
8920: # $domain - Name of the domain the user/course is registered on.
8921: # $type - Type of thing $name is (must be 'course' or 'user'
8922: # @which - Array of names of resources desired.
8923: # Returns:
8924: # The value of the first reasource in @which that is found in the
8925: # resource hash.
8926: # Exceptional Conditions:
8927: # If the $type passed in is not valid (not the string 'course' or
8928: # 'user', an undefined reference is returned.
8929: # If none of the resources are found, an undef is returned
1.624 albertel 8930: sub resdata {
8931: my ($name,$domain,$type,@which)=@_;
8932: my $result;
8933: if ($type eq 'course') {
8934: $result=&get_courseresdata($name,$domain);
8935: } elsif ($type eq 'user') {
8936: $result=&get_userresdata($name,$domain);
8937: }
8938: if (!ref($result)) { return $result; }
1.251 albertel 8939: foreach my $item (@which) {
1.927 albertel 8940: if (defined($result->{$item->[0]})) {
8941: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8942: }
1.250 albertel 8943: }
1.291 albertel 8944: return undef;
1.200 www 8945: }
8946:
1.379 matthew 8947: #
8948: # EXT resource caching routines
8949: #
8950:
8951: sub clear_EXT_cache_status {
1.383 albertel 8952: &delenv('cache.EXT.');
1.379 matthew 8953: }
8954:
8955: sub EXT_cache_status {
8956: my ($target_domain,$target_user) = @_;
1.383 albertel 8957: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8958: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8959: # We know already the user has no data
8960: return 1;
8961: } else {
8962: return 0;
8963: }
8964: }
8965:
8966: sub EXT_cache_set {
8967: my ($target_domain,$target_user) = @_;
1.383 albertel 8968: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8969: #&appenv({$cachename => time});
1.379 matthew 8970: }
8971:
1.28 www 8972: # --------------------------------------------------------- Value of a Variable
1.58 www 8973: sub EXT {
1.715 albertel 8974:
1.395 albertel 8975: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8976: unless ($varname) { return ''; }
1.218 albertel 8977: #get real user name/domain, courseid and symb
8978: my $courseid;
1.359 albertel 8979: my $publicuser;
1.427 www 8980: if ($symbparm) {
8981: $symbparm=&get_symb_from_alias($symbparm);
8982: }
1.218 albertel 8983: if (!($uname && $udom)) {
1.790 albertel 8984: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8985: if (!$symbparm) { $symbparm=$cursymb; }
8986: } else {
1.620 albertel 8987: $courseid=$env{'request.course.id'};
1.218 albertel 8988: }
1.48 www 8989: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8990: my $rest;
1.320 albertel 8991: if (defined($therest[0])) {
1.48 www 8992: $rest=join('.',@therest);
8993: } else {
8994: $rest='';
8995: }
1.320 albertel 8996:
1.57 www 8997: my $qualifierrest=$qualifier;
8998: if ($rest) { $qualifierrest.='.'.$rest; }
8999: my $spacequalifierrest=$space;
9000: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9001: if ($realm eq 'user') {
1.48 www 9002: # --------------------------------------------------------------- user.resource
9003: if ($space eq 'resource') {
1.651 albertel 9004: if ( (defined($Apache::lonhomework::parsing_a_problem)
9005: || defined($Apache::lonhomework::parsing_a_task))
9006: &&
1.744 albertel 9007: ($symbparm eq &symbread()) ) {
9008: # if we are in the middle of processing the resource the
9009: # get the value we are planning on committing
9010: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9011: return $Apache::lonhomework::results{$qualifierrest};
9012: } else {
9013: return $Apache::lonhomework::history{$qualifierrest};
9014: }
1.335 albertel 9015: } else {
1.359 albertel 9016: my %restored;
1.620 albertel 9017: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9018: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9019: } else {
9020: %restored=&restore($symbparm,$courseid,$udom,$uname);
9021: }
1.335 albertel 9022: return $restored{$qualifierrest};
9023: }
1.48 www 9024: # ----------------------------------------------------------------- user.access
9025: } elsif ($space eq 'access') {
1.218 albertel 9026: # FIXME - not supporting calls for a specific user
1.48 www 9027: return &allowed($qualifier,$rest);
9028: # ------------------------------------------ user.preferences, user.environment
9029: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9030: if (($uname eq $env{'user.name'}) &&
9031: ($udom eq $env{'user.domain'})) {
9032: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9033: } else {
1.359 albertel 9034: my %returnhash;
9035: if (!$publicuser) {
9036: %returnhash=&userenvironment($udom,$uname,
9037: $qualifierrest);
9038: }
1.218 albertel 9039: return $returnhash{$qualifierrest};
9040: }
1.48 www 9041: # ----------------------------------------------------------------- user.course
9042: } elsif ($space eq 'course') {
1.218 albertel 9043: # FIXME - not supporting calls for a specific user
1.620 albertel 9044: return $env{join('.',('request.course',$qualifier))};
1.48 www 9045: # ------------------------------------------------------------------- user.role
9046: } elsif ($space eq 'role') {
1.218 albertel 9047: # FIXME - not supporting calls for a specific user
1.620 albertel 9048: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9049: if ($qualifier eq 'value') {
9050: return $role;
9051: } elsif ($qualifier eq 'extent') {
9052: return $where;
9053: }
9054: # ----------------------------------------------------------------- user.domain
9055: } elsif ($space eq 'domain') {
1.218 albertel 9056: return $udom;
1.48 www 9057: # ------------------------------------------------------------------- user.name
9058: } elsif ($space eq 'name') {
1.218 albertel 9059: return $uname;
1.48 www 9060: # ---------------------------------------------------- Any other user namespace
1.29 www 9061: } else {
1.359 albertel 9062: my %reply;
9063: if (!$publicuser) {
9064: %reply=&get($space,[$qualifierrest],$udom,$uname);
9065: }
9066: return $reply{$qualifierrest};
1.48 www 9067: }
1.236 www 9068: } elsif ($realm eq 'query') {
9069: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9070: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9071: [$spacequalifierrest]);
1.620 albertel 9072: return $env{'form.'.$spacequalifierrest};
1.236 www 9073: } elsif ($realm eq 'request') {
1.48 www 9074: # ------------------------------------------------------------- request.browser
9075: if ($space eq 'browser') {
1.1145 bisitz 9076: return $env{'browser.'.$qualifier};
1.57 www 9077: # ------------------------------------------------------------ request.filename
9078: } else {
1.620 albertel 9079: return $env{'request.'.$spacequalifierrest};
1.29 www 9080: }
1.28 www 9081: } elsif ($realm eq 'course') {
1.48 www 9082: # ---------------------------------------------------------- course.description
1.620 albertel 9083: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9084: } elsif ($realm eq 'resource') {
1.165 www 9085:
1.620 albertel 9086: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9087: if (!$symbparm) { $symbparm=&symbread(); }
9088: }
1.693 albertel 9089:
9090: if ($space eq 'title') {
9091: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9092: return &gettitle($symbparm);
9093: }
9094:
9095: if ($space eq 'map') {
9096: my ($map) = &decode_symb($symbparm);
9097: return &symbread($map);
9098: }
1.905 albertel 9099: if ($space eq 'filename') {
9100: if ($symbparm) {
9101: return &clutter((&decode_symb($symbparm))[2]);
9102: }
9103: return &hreflocation('',$env{'request.filename'});
9104: }
1.693 albertel 9105:
9106: my ($section, $group, @groups);
1.593 albertel 9107: my ($courselevelm,$courselevel);
1.539 albertel 9108: if ($symbparm && defined($courseid) &&
1.620 albertel 9109: $courseid eq $env{'request.course.id'}) {
1.165 www 9110:
1.218 albertel 9111: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9112:
1.60 www 9113: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9114: my $symbp=$symbparm;
1.735 albertel 9115: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9116:
9117: my $symbparm=$symbp.'.'.$spacequalifierrest;
9118: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9119:
1.620 albertel 9120: if (($env{'user.name'} eq $uname) &&
9121: ($env{'user.domain'} eq $udom)) {
9122: $section=$env{'request.course.sec'};
1.733 raeburn 9123: @groups = split(/:/,$env{'request.course.groups'});
9124: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9125: } else {
1.539 albertel 9126: if (! defined($usection)) {
1.551 albertel 9127: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9128: } else {
9129: $section = $usection;
9130: }
1.733 raeburn 9131: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9132: }
9133:
9134: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9135: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9136: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9137:
1.593 albertel 9138: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9139: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9140: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9141:
1.60 www 9142: # ----------------------------------------------------------- first, check user
1.624 albertel 9143:
9144: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9145: ([$courselevelr,'resource'],
9146: [$courselevelm,'map' ],
9147: [$courselevel, 'course' ]));
1.931 albertel 9148: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9149:
1.594 albertel 9150: # ------------------------------------------------ second, check some of course
1.684 raeburn 9151: my $coursereply;
1.691 raeburn 9152: if (@groups > 0) {
9153: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9154: $mapparm,$spacequalifierrest);
1.927 albertel 9155: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9156: }
1.96 www 9157:
1.684 raeburn 9158: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9159: $env{'course.'.$courseid.'.domain'},
9160: 'course',
9161: ([$seclevelr, 'resource'],
9162: [$seclevelm, 'map' ],
9163: [$seclevel, 'course' ],
9164: [$courselevelr,'resource']));
9165: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9166:
1.60 www 9167: # ------------------------------------------------------ third, check map parms
1.218 albertel 9168: my %parmhash=();
9169: my $thisparm='';
9170: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9171: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9172: &GDBM_READER(),0640)) {
1.218 albertel 9173: $thisparm=$parmhash{$symbparm};
9174: untie(%parmhash);
9175: }
1.927 albertel 9176: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9177: }
1.594 albertel 9178: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9179:
1.218 albertel 9180: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9181: my $filename;
9182: if (!$symbparm) { $symbparm=&symbread(); }
9183: if ($symbparm) {
1.409 www 9184: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9185: } else {
1.620 albertel 9186: $filename=$env{'request.filename'};
1.282 albertel 9187: }
9188: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9189: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9190: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9191: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9192:
1.927 albertel 9193: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9194: if ($symbparm && defined($courseid) &&
1.620 albertel 9195: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9196: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9197: $env{'course.'.$courseid.'.domain'},
9198: 'course',
1.927 albertel 9199: ([$courselevelm,'map' ],
9200: [$courselevel, 'course']));
9201: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9202: }
1.145 www 9203: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9204: unless ($space eq '0') {
1.336 albertel 9205: my @parts=split(/_/,$space);
9206: my $id=pop(@parts);
9207: my $part=join('_',@parts);
9208: if ($part eq '') { $part='0'; }
1.927 albertel 9209: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9210: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9211: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9212: }
1.395 albertel 9213: if ($recurse) { return undef; }
9214: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9215: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9216: # ---------------------------------------------------- Any other user namespace
9217: } elsif ($realm eq 'environment') {
9218: # ----------------------------------------------------------------- environment
1.620 albertel 9219: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9220: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9221: } else {
1.770 albertel 9222: if ($uname eq 'anonymous' && $udom eq '') {
9223: return '';
9224: }
1.219 albertel 9225: my %returnhash=&userenvironment($udom,$uname,
9226: $spacequalifierrest);
9227: return $returnhash{$spacequalifierrest};
9228: }
1.28 www 9229: } elsif ($realm eq 'system') {
1.48 www 9230: # ----------------------------------------------------------------- system.time
9231: if ($space eq 'time') {
9232: return time;
9233: }
1.696 albertel 9234: } elsif ($realm eq 'server') {
9235: # ----------------------------------------------------------------- system.time
9236: if ($space eq 'name') {
9237: return $ENV{'SERVER_NAME'};
9238: }
1.28 www 9239: }
1.48 www 9240: return '';
1.61 www 9241: }
9242:
1.927 albertel 9243: sub get_reply {
9244: my ($reply_value) = @_;
1.940 raeburn 9245: if (ref($reply_value) eq 'ARRAY') {
9246: if (wantarray) {
9247: return @$reply_value;
9248: }
9249: return $reply_value->[0];
9250: } else {
9251: return $reply_value;
1.927 albertel 9252: }
9253: }
9254:
1.691 raeburn 9255: sub check_group_parms {
9256: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9257: my @groupitems = ();
9258: my $resultitem;
1.927 albertel 9259: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9260: foreach my $group (@{$groups}) {
9261: foreach my $level (@levels) {
1.927 albertel 9262: my $item = $courseid.'.['.$group.'].'.$level->[0];
9263: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9264: }
9265: }
9266: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9267: $env{'course.'.$courseid.'.domain'},
9268: 'course',@groupitems);
9269: return $coursereply;
9270: }
9271:
9272: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9273: my ($courseid,@groups) = @_;
9274: @groups = sort(@groups);
1.691 raeburn 9275: return @groups;
9276: }
9277:
1.395 albertel 9278: sub packages_tab_default {
9279: my ($uri,$varname)=@_;
9280: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9281:
9282: my (@extension,@specifics,$do_default);
9283: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9284: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9285: if ($pack_type eq 'default') {
9286: $do_default=1;
9287: } elsif ($pack_type eq 'extension') {
9288: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9289: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9290: # only look at packages defaults for packages that this id is
1.738 albertel 9291: push(@specifics,[$package,$pack_type,$pack_part]);
9292: }
9293: }
9294: # first look for a package that matches the requested part id
9295: foreach my $package (@specifics) {
9296: my (undef,$pack_type,$pack_part)=@{$package};
9297: next if ($pack_part ne $part);
9298: if (defined($packagetab{"$pack_type&$name&default"})) {
9299: return $packagetab{"$pack_type&$name&default"};
9300: }
9301: }
9302: # look for any possible matching non extension_ package
9303: foreach my $package (@specifics) {
9304: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9305: if (defined($packagetab{"$pack_type&$name&default"})) {
9306: return $packagetab{"$pack_type&$name&default"};
9307: }
1.585 albertel 9308: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9309: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9310: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9311: }
9312: }
1.738 albertel 9313: # look for any posible extension_ match
9314: foreach my $package (@extension) {
9315: my ($package,$pack_type)=@{$package};
9316: if (defined($packagetab{"$pack_type&$name&default"})) {
9317: return $packagetab{"$pack_type&$name&default"};
9318: }
9319: if (defined($packagetab{$package."&$name&default"})) {
9320: return $packagetab{$package."&$name&default"};
9321: }
9322: }
9323: # look for a global default setting
9324: if ($do_default && defined($packagetab{"default&$name&default"})) {
9325: return $packagetab{"default&$name&default"};
9326: }
1.395 albertel 9327: return undef;
9328: }
9329:
1.334 albertel 9330: sub add_prefix_and_part {
9331: my ($prefix,$part)=@_;
9332: my $keyroot;
9333: if (defined($prefix) && $prefix !~ /^__/) {
9334: # prefix that has a part already
9335: $keyroot=$prefix;
9336: } elsif (defined($prefix)) {
9337: # prefix that is missing a part
9338: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9339: } else {
9340: # no prefix at all
9341: if (defined($part)) { $keyroot='_'.$part; }
9342: }
9343: return $keyroot;
9344: }
9345:
1.71 www 9346: # ---------------------------------------------------------------- Get metadata
9347:
1.599 albertel 9348: my %metaentry;
1.1070 www 9349: my %importedpartids;
1.71 www 9350: sub metadata {
1.176 www 9351: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9352: $uri=&declutter($uri);
1.288 albertel 9353: # if it is a non metadata possible uri return quickly
1.529 albertel 9354: if (($uri eq '') ||
9355: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9356: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9357: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9358: return undef;
9359: }
1.1140 www 9360: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9361: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9362: return undef;
1.288 albertel 9363: }
1.73 www 9364: my $filename=$uri;
9365: $uri=~s/\.meta$//;
1.172 www 9366: #
9367: # Is the metadata already cached?
1.177 www 9368: # Look at timestamp of caching
1.172 www 9369: # Everything is cached by the main uri, libraries are never directly cached
9370: #
1.428 albertel 9371: if (!defined($liburi)) {
1.599 albertel 9372: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9373: if (defined($cached)) { return $result->{':'.$what}; }
9374: }
9375: {
1.1069 www 9376: # Imported parts would go here
1.1070 www 9377: my %importedids=();
9378: my @origfileimportpartids=();
1.1069 www 9379: my $importedparts=0;
1.172 www 9380: #
9381: # Is this a recursive call for a library?
9382: #
1.599 albertel 9383: # if (! exists($metacache{$uri})) {
9384: # $metacache{$uri}={};
9385: # }
1.924 albertel 9386: my $cachetime = 60*60;
1.171 www 9387: if ($liburi) {
9388: $liburi=&declutter($liburi);
9389: $filename=$liburi;
1.401 bowersj2 9390: } else {
1.599 albertel 9391: &devalidate_cache_new('meta',$uri);
9392: undef(%metaentry);
1.401 bowersj2 9393: }
1.140 www 9394: my %metathesekeys=();
1.73 www 9395: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9396: my $metastring;
1.1140 www 9397: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9398: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9399: $metastring =
1.929 albertel 9400: &Apache::lonnet::ssi_body($which,
1.924 albertel 9401: ('grade_target' => 'meta'));
9402: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9403: } elsif (($uri !~ m -^(editupload)/-) &&
9404: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9405: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9406: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9407: $metastring=&getfile($file);
1.489 albertel 9408: }
1.208 albertel 9409: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9410: my $token;
1.140 www 9411: undef %metathesekeys;
1.71 www 9412: while ($token=$parser->get_token) {
1.339 albertel 9413: if ($token->[0] eq 'S') {
9414: if (defined($token->[2]->{'package'})) {
1.172 www 9415: #
9416: # This is a package - get package info
9417: #
1.339 albertel 9418: my $package=$token->[2]->{'package'};
9419: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9420: if (defined($token->[2]->{'id'})) {
9421: $keyroot.='_'.$token->[2]->{'id'};
9422: }
1.599 albertel 9423: if ($metaentry{':packages'}) {
9424: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9425: } else {
1.599 albertel 9426: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9427: }
1.736 albertel 9428: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9429: my $part=$keyroot;
9430: $part=~s/^\_//;
1.736 albertel 9431: if ($pack_entry=~/^\Q$package\E\&/ ||
9432: $pack_entry=~/^\Q$package\E_0\&/) {
9433: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9434: # ignore package.tab specified default values
9435: # here &package_tab_default() will fetch those
9436: if ($subp eq 'default') { next; }
1.736 albertel 9437: my $value=$packagetab{$pack_entry};
1.432 albertel 9438: my $unikey;
9439: if ($pack =~ /_0$/) {
9440: $unikey='parameter_0_'.$name;
9441: $part=0;
9442: } else {
9443: $unikey='parameter'.$keyroot.'_'.$name;
9444: }
1.339 albertel 9445: if ($subp eq 'display') {
9446: $value.=' [Part: '.$part.']';
9447: }
1.599 albertel 9448: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9449: $metathesekeys{$unikey}=1;
1.599 albertel 9450: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9451: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9452: }
1.599 albertel 9453: if (defined($metaentry{':'.$unikey.'.default'})) {
9454: $metaentry{':'.$unikey}=
9455: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9456: }
1.339 albertel 9457: }
9458: }
9459: } else {
1.172 www 9460: #
9461: # This is not a package - some other kind of start tag
1.339 albertel 9462: #
9463: my $entry=$token->[1];
1.1068 www 9464: my $unikey='';
1.175 www 9465:
1.339 albertel 9466: if ($entry eq 'import') {
1.175 www 9467: #
9468: # Importing a library here
1.339 albertel 9469: #
1.1067 www 9470: my $location=$parser->get_text('/import');
9471: my $dir=$filename;
9472: $dir=~s|[^/]*$||;
9473: $location=&filelocation($dir,$location);
1.1069 www 9474:
1.1068 www 9475: my $importmode=$token->[2]->{'importmode'};
9476: if ($importmode eq 'problem') {
1.1069 www 9477: # Import as problem/response
1.1068 www 9478: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9479: } elsif ($importmode eq 'part') {
9480: # Import as part(s)
1.1069 www 9481: $importedparts=1;
9482: # We need to get the original file and the imported file to get the part order correct
9483: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9484: # Load and inspect original file
1.1070 www 9485: if ($#origfileimportpartids<0) {
9486: undef(%importedpartids);
9487: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9488: my $origfile=&getfile($origfilelocation);
9489: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9490: }
9491:
1.1069 www 9492: # Load and inspect imported file
9493: my $impfile=&getfile($location);
9494: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9495: if ($#impfilepartids>=0) {
9496: # This problem had parts
1.1070 www 9497: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9498: } else {
9499: # Importing by turning a single problem into a problem part
9500: # It gets the import-tags ID as part-ID
9501: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9502: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9503: }
1.1068 www 9504: } else {
9505: # Normal import
9506: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9507: if (defined($token->[2]->{'id'})) {
9508: $unikey.='_'.$token->[2]->{'id'};
9509: }
1.1067 www 9510: }
9511:
1.339 albertel 9512: if ($depthcount<20) {
1.736 albertel 9513: my $metadata =
9514: &metadata($uri,'keys', $location,$unikey,
9515: $depthcount+1);
9516: foreach my $meta (split(',',$metadata)) {
9517: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9518: $metathesekeys{$meta}=1;
1.339 albertel 9519: }
1.1068 www 9520:
9521: }
1.1067 www 9522: } else {
9523: #
9524: # Not importing, some other kind of non-package, non-library start tag
9525: #
9526: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9527: if (defined($token->[2]->{'id'})) {
9528: $unikey.='_'.$token->[2]->{'id'};
9529: }
1.339 albertel 9530: if (defined($token->[2]->{'name'})) {
9531: $unikey.='_'.$token->[2]->{'name'};
9532: }
9533: $metathesekeys{$unikey}=1;
1.736 albertel 9534: foreach my $param (@{$token->[3]}) {
9535: $metaentry{':'.$unikey.'.'.$param} =
9536: $token->[2]->{$param};
1.339 albertel 9537: }
9538: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9539: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9540: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9541: # only ws inside the tag, and not in default, so use default
9542: # as value
1.599 albertel 9543: $metaentry{':'.$unikey}=$default;
1.908 albertel 9544: } elsif ( $internaltext =~ /\S/ ) {
9545: # something interesting inside the tag
9546: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9547: } else {
1.908 albertel 9548: # no interesting values, don't set a default
1.339 albertel 9549: }
1.172 www 9550: # end of not-a-package not-a-library import
1.339 albertel 9551: }
1.172 www 9552: # end of not-a-package start tag
1.339 albertel 9553: }
1.172 www 9554: # the next is the end of "start tag"
1.339 albertel 9555: }
9556: }
1.483 albertel 9557: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9558: $extension = lc($extension);
9559: if ($extension eq 'htm') { $extension='html'; }
9560:
1.737 albertel 9561: foreach my $key (keys(%packagetab)) {
1.483 albertel 9562: #no specific packages #how's our extension
9563: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9564: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9565: \%metathesekeys);
9566: }
1.883 albertel 9567:
9568: if (!exists($metaentry{':packages'})
9569: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9570: foreach my $key (keys(%packagetab)) {
1.483 albertel 9571: #no specific packages well let's get default then
9572: if ($key!~/^default&/) { next; }
1.488 albertel 9573: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9574: \%metathesekeys);
9575: }
9576: }
1.338 www 9577: # are there custom rights to evaluate
1.599 albertel 9578: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9579:
1.338 www 9580: #
9581: # Importing a rights file here
1.339 albertel 9582: #
9583: unless ($depthcount) {
1.599 albertel 9584: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9585: my $dir=$filename;
9586: $dir=~s|[^/]*$||;
9587: $location=&filelocation($dir,$location);
1.736 albertel 9588: my $rights_metadata =
9589: &metadata($uri,'keys',$location,'_rights',
9590: $depthcount+1);
9591: foreach my $rights (split(',',$rights_metadata)) {
9592: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9593: $metathesekeys{$rights}=1;
1.339 albertel 9594: }
9595: }
9596: }
1.737 albertel 9597: # uniqifiy package listing
9598: my %seen;
9599: my @uniq_packages =
9600: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9601: $metaentry{':packages'} = join(',',@uniq_packages);
9602:
1.1070 www 9603: if ($importedparts) {
9604: # We had imported parts and need to rebuild partorder
9605: $metaentry{':partorder'}='';
9606: $metathesekeys{'partorder'}=1;
9607: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9608: if ($origfileimportpartids[$index] eq 'part') {
9609: # original part, part of the problem
9610: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9611: } else {
9612: # we have imported parts at this position
9613: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9614: }
9615: }
9616: $metaentry{':partorder'}=~s/^\,//;
9617: }
9618:
1.737 albertel 9619: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9620: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9621: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9622: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9623: # this is the end of "was not already recently cached
1.71 www 9624: }
1.599 albertel 9625: return $metaentry{':'.$what};
1.261 albertel 9626: }
9627:
1.488 albertel 9628: sub metadata_create_package_def {
1.483 albertel 9629: my ($uri,$key,$package,$metathesekeys)=@_;
9630: my ($pack,$name,$subp)=split(/\&/,$key);
9631: if ($subp eq 'default') { next; }
9632:
1.599 albertel 9633: if (defined($metaentry{':packages'})) {
9634: $metaentry{':packages'}.=','.$package;
1.483 albertel 9635: } else {
1.599 albertel 9636: $metaentry{':packages'}=$package;
1.483 albertel 9637: }
9638: my $value=$packagetab{$key};
9639: my $unikey;
9640: $unikey='parameter_0_'.$name;
1.599 albertel 9641: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9642: $$metathesekeys{$unikey}=1;
1.599 albertel 9643: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9644: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9645: }
1.599 albertel 9646: if (defined($metaentry{':'.$unikey.'.default'})) {
9647: $metaentry{':'.$unikey}=
9648: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9649: }
9650: }
9651:
1.261 albertel 9652: sub metadata_generate_part0 {
9653: my ($metadata,$metacache,$uri) = @_;
9654: my %allnames;
1.737 albertel 9655: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9656: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9657: my $part=$$metacache{':'.$metakey.'.part'};
9658: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9659: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9660: $allnames{$name}=$part;
9661: }
9662: }
9663: }
9664: foreach my $name (keys(%allnames)) {
9665: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9666: my $key=":parameter_0_$name";
1.261 albertel 9667: $$metacache{"$key.part"}='0';
9668: $$metacache{"$key.name"}=$name;
1.428 albertel 9669: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9670: $allnames{$name}.'_'.$name.
9671: '.type'};
1.428 albertel 9672: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9673: '.display'};
1.644 www 9674: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9675: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9676: $$metacache{"$key.display"}=$olddis;
9677: }
1.71 www 9678: }
9679:
1.764 albertel 9680: # ------------------------------------------------------ Devalidate title cache
9681:
9682: sub devalidate_title_cache {
9683: my ($url)=@_;
9684: if (!$env{'request.course.id'}) { return; }
9685: my $symb=&symbread($url);
9686: if (!$symb) { return; }
9687: my $key=$env{'request.course.id'}."\0".$symb;
9688: &devalidate_cache_new('title',$key);
9689: }
9690:
1.1014 droeschl 9691: # ------------------------------------------------- Get the title of a course
9692:
9693: sub current_course_title {
9694: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9695: }
1.301 www 9696: # ------------------------------------------------- Get the title of a resource
9697:
9698: sub gettitle {
9699: my $urlsymb=shift;
9700: my $symb=&symbread($urlsymb);
1.534 albertel 9701: if ($symb) {
1.620 albertel 9702: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9703: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9704: if (defined($cached)) {
9705: return $result;
9706: }
1.534 albertel 9707: my ($map,$resid,$url)=&decode_symb($symb);
9708: my $title='';
1.907 albertel 9709: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9710: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9711: } else {
9712: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9713: &GDBM_READER(),0640)) {
9714: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9715: $title=$bighash{'title_'.$mapid.'.'.$resid};
9716: untie(%bighash);
9717: }
1.534 albertel 9718: }
9719: $title=~s/\&colon\;/\:/gs;
9720: if ($title) {
1.1159 www 9721: # Remember both $symb and $title for dynamic metadata
9722: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9723: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9724: # Cache this title and then return it
1.599 albertel 9725: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9726: }
9727: $urlsymb=$url;
9728: }
9729: my $title=&metadata($urlsymb,'title');
9730: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9731: return $title;
1.301 www 9732: }
1.613 albertel 9733:
1.614 albertel 9734: sub get_slot {
9735: my ($which,$cnum,$cdom)=@_;
9736: if (!$cnum || !$cdom) {
1.790 albertel 9737: (undef,my $courseid)=&whichuser();
1.620 albertel 9738: $cdom=$env{'course.'.$courseid.'.domain'};
9739: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9740: }
1.703 albertel 9741: my $key=join("\0",'slots',$cdom,$cnum,$which);
9742: my %slotinfo;
9743: if (exists($remembered{$key})) {
9744: $slotinfo{$which} = $remembered{$key};
9745: } else {
9746: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9747: &Apache::lonhomework::showhash(%slotinfo);
9748: my ($tmp)=keys(%slotinfo);
9749: if ($tmp=~/^error:/) { return (); }
9750: $remembered{$key} = $slotinfo{$which};
9751: }
1.616 albertel 9752: if (ref($slotinfo{$which}) eq 'HASH') {
9753: return %{$slotinfo{$which}};
9754: }
9755: return $slotinfo{$which};
1.614 albertel 9756: }
1.1150 raeburn 9757:
9758: sub get_reservable_slots {
9759: my ($cnum,$cdom,$uname,$udom) = @_;
9760: my $now = time;
9761: my $reservable_info;
9762: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9763: if (exists($remembered{$key})) {
9764: $reservable_info = $remembered{$key};
9765: } else {
9766: my %resv;
9767: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9768: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9769: $reservable_info = \%resv;
9770: $remembered{$key} = $reservable_info;
9771: }
9772: return $reservable_info;
9773: }
9774:
9775: sub get_course_slots {
9776: my ($cnum,$cdom) = @_;
9777: my $hashid=$cnum.':'.$cdom;
9778: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9779: if (defined($cached)) {
9780: if (ref($result) eq 'HASH') {
9781: return %{$result};
9782: }
9783: } else {
9784: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9785: my ($tmp) = keys(%slots);
9786: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9787: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9788: return %slots;
9789: }
9790: }
9791: return;
9792: }
9793:
9794: sub devalidate_slots_cache {
9795: my ($cnum,$cdom)=@_;
9796: my $hashid=$cnum.':'.$cdom;
9797: &devalidate_cache_new('allslots',$hashid);
9798: }
9799:
1.31 www 9800: # ------------------------------------------------- Update symbolic store links
9801:
9802: sub symblist {
9803: my ($mapname,%newhash)=@_;
1.438 www 9804: $mapname=&deversion(&declutter($mapname));
1.31 www 9805: my %hash;
1.620 albertel 9806: if (($env{'request.course.fn'}) && (%newhash)) {
9807: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9808: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9809: foreach my $url (keys(%newhash)) {
1.711 albertel 9810: next if ($url eq 'last_known'
9811: && $env{'form.no_update_last_known'});
9812: $hash{declutter($url)}=&encode_symb($mapname,
9813: $newhash{$url}->[1],
9814: $newhash{$url}->[0]);
1.191 harris41 9815: }
1.31 www 9816: if (untie(%hash)) {
9817: return 'ok';
9818: }
9819: }
9820: }
9821: return 'error';
1.212 www 9822: }
9823:
9824: # --------------------------------------------------------------- Verify a symb
9825:
9826: sub symbverify {
1.510 www 9827: my ($symb,$thisurl)=@_;
9828: my $thisfn=$thisurl;
1.439 www 9829: $thisfn=&declutter($thisfn);
1.215 www 9830: # direct jump to resource in page or to a sequence - will construct own symbs
9831: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9832: # check URL part
1.409 www 9833: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9834:
1.431 www 9835: unless ($url eq $thisfn) { return 0; }
1.213 www 9836:
1.216 www 9837: $symb=&symbclean($symb);
1.510 www 9838: $thisurl=&deversion($thisurl);
1.439 www 9839: $thisfn=&deversion($thisfn);
1.213 www 9840:
9841: my %bighash;
9842: my $okay=0;
1.431 www 9843:
1.620 albertel 9844: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9845: &GDBM_READER(),0640)) {
1.1032 raeburn 9846: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9847: $thisurl =~ s/\?.+$//;
9848: }
1.510 www 9849: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9850: unless ($ids) {
9851: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9852: $ids=$bighash{$idkey};
1.216 www 9853: }
9854: if ($ids) {
9855: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9856: foreach my $id (split(/\,/,$ids)) {
9857: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9858: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9859: $symb =~ s/\?.+$//;
9860: }
1.216 www 9861: if (
9862: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9863: eq $symb) {
1.620 albertel 9864: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9865: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9866: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9867: $okay=1;
9868: }
9869: }
1.216 www 9870: }
9871: }
1.213 www 9872: untie(%bighash);
9873: }
9874: return $okay;
1.31 www 9875: }
9876:
1.210 www 9877: # --------------------------------------------------------------- Clean-up symb
9878:
9879: sub symbclean {
9880: my $symb=shift;
1.568 albertel 9881: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9882: # remove version from map
9883: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9884:
1.210 www 9885: # remove version from URL
9886: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9887:
1.507 www 9888: # remove wrapper
9889:
1.510 www 9890: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9891: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9892: return $symb;
1.409 www 9893: }
9894:
9895: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9896:
9897: sub encode_symb {
9898: my ($map,$resid,$url)=@_;
9899: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9900: }
1.409 www 9901:
9902: sub decode_symb {
1.568 albertel 9903: my $symb=shift;
9904: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9905: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9906: return (&fixversion($map),$resid,&fixversion($url));
9907: }
9908:
9909: sub fixversion {
9910: my $fn=shift;
1.609 banghart 9911: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9912: my %bighash;
9913: my $uri=&clutter($fn);
1.620 albertel 9914: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9915: # is this cached?
1.599 albertel 9916: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9917: if (defined($cached)) { return $result; }
9918: # unfortunately not cached, or expired
1.620 albertel 9919: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9920: &GDBM_READER(),0640)) {
9921: if ($bighash{'version_'.$uri}) {
9922: my $version=$bighash{'version_'.$uri};
1.444 www 9923: unless (($version eq 'mostrecent') ||
9924: ($version==&getversion($uri))) {
1.440 www 9925: $uri=~s/\.(\w+)$/\.$version\.$1/;
9926: }
9927: }
9928: untie %bighash;
1.413 www 9929: }
1.599 albertel 9930: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9931: }
9932:
9933: sub deversion {
9934: my $url=shift;
9935: $url=~s/\.\d+\.(\w+)$/\.$1/;
9936: return $url;
1.210 www 9937: }
9938:
1.31 www 9939: # ------------------------------------------------------ Return symb list entry
9940:
9941: sub symbread {
1.249 www 9942: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9943: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9944: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9945: # no filename provided? try from environment
1.44 www 9946: unless ($thisfn) {
1.620 albertel 9947: if ($env{'request.symb'}) {
9948: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9949: }
1.620 albertel 9950: $thisfn=$env{'request.filename'};
1.44 www 9951: }
1.569 albertel 9952: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9953: # is that filename actually a symb? Verify, clean, and return
9954: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9955: if (&symbverify($thisfn,$1)) {
1.620 albertel 9956: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9957: }
1.242 www 9958: }
1.44 www 9959: $thisfn=declutter($thisfn);
1.31 www 9960: my %hash;
1.37 www 9961: my %bighash;
9962: my $syval='';
1.620 albertel 9963: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9964: my $targetfn = $thisfn;
1.609 banghart 9965: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9966: $targetfn = 'adm/wrapper/'.$thisfn;
9967: }
1.687 albertel 9968: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9969: $targetfn=$1;
9970: }
1.620 albertel 9971: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9972: &GDBM_READER(),0640)) {
1.481 raeburn 9973: $syval=$hash{$targetfn};
1.37 www 9974: untie(%hash);
9975: }
9976: # ---------------------------------------------------------- There was an entry
9977: if ($syval) {
1.601 albertel 9978: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9979: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9980: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9981: #return $env{$cache_str}='';
1.601 albertel 9982: #}
9983: #$syval.=$1;
9984: #}
1.37 www 9985: } else {
9986: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9987: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9988: &GDBM_READER(),0640)) {
1.37 www 9989: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9990: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9991: unless ($ids) {
9992: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9993: }
9994: unless ($ids) {
9995: # alias?
9996: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9997: }
1.37 www 9998: if ($ids) {
9999: # ------------------------------------------------------------------- Has ID(s)
10000: my @possibilities=split(/\,/,$ids);
1.39 www 10001: if ($#possibilities==0) {
10002: # ----------------------------------------------- There is only one possibility
1.37 www 10003: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10004: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10005: $resid,$thisfn);
1.249 www 10006: } elsif (!$donotrecurse) {
1.39 www 10007: # ------------------------------------------ There is more than one possibility
10008: my $realpossible=0;
1.800 albertel 10009: foreach my $id (@possibilities) {
10010: my $file=$bighash{'src_'.$id};
1.39 www 10011: if (&allowed('bre',$file)) {
1.800 albertel 10012: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10013: if ($bighash{'map_type_'.$mapid} ne 'page') {
10014: $realpossible++;
1.626 albertel 10015: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10016: $resid,$thisfn);
1.39 www 10017: }
10018: }
1.191 harris41 10019: }
1.39 www 10020: if ($realpossible!=1) { $syval=''; }
1.249 www 10021: } else {
10022: $syval='';
1.37 www 10023: }
10024: }
10025: untie(%bighash)
1.481 raeburn 10026: }
1.31 www 10027: }
1.62 www 10028: if ($syval) {
1.620 albertel 10029: return $env{$cache_str}=$syval;
1.62 www 10030: }
1.31 www 10031: }
1.949 raeburn 10032: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10033: return $env{$cache_str}='';
1.31 www 10034: }
10035:
10036: # ---------------------------------------------------------- Return random seed
10037:
1.32 www 10038: sub numval {
10039: my $txt=shift;
10040: $txt=~tr/A-J/0-9/;
10041: $txt=~tr/a-j/0-9/;
10042: $txt=~tr/K-T/0-9/;
10043: $txt=~tr/k-t/0-9/;
10044: $txt=~tr/U-Z/0-5/;
10045: $txt=~tr/u-z/0-5/;
10046: $txt=~s/\D//g;
1.564 albertel 10047: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10048: return int($txt);
1.368 albertel 10049: }
10050:
1.484 albertel 10051: sub numval2 {
10052: my $txt=shift;
10053: $txt=~tr/A-J/0-9/;
10054: $txt=~tr/a-j/0-9/;
10055: $txt=~tr/K-T/0-9/;
10056: $txt=~tr/k-t/0-9/;
10057: $txt=~tr/U-Z/0-5/;
10058: $txt=~tr/u-z/0-5/;
10059: $txt=~s/\D//g;
10060: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10061: my $total;
10062: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10063: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10064: return int($total);
10065: }
10066:
1.575 albertel 10067: sub numval3 {
10068: use integer;
10069: my $txt=shift;
10070: $txt=~tr/A-J/0-9/;
10071: $txt=~tr/a-j/0-9/;
10072: $txt=~tr/K-T/0-9/;
10073: $txt=~tr/k-t/0-9/;
10074: $txt=~tr/U-Z/0-5/;
10075: $txt=~tr/u-z/0-5/;
10076: $txt=~s/\D//g;
10077: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10078: my $total;
10079: foreach my $val (@txts) { $total+=$val; }
10080: if ($_64bit) { $total=(($total<<32)>>32); }
10081: return $total;
10082: }
10083:
1.675 albertel 10084: sub digest {
10085: my ($data)=@_;
10086: my $digest=&Digest::MD5::md5($data);
10087: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10088: my ($e,$f);
10089: {
10090: use integer;
10091: $e=($a+$b);
10092: $f=($c+$d);
10093: if ($_64bit) {
10094: $e=(($e<<32)>>32);
10095: $f=(($f<<32)>>32);
10096: }
10097: }
10098: if (wantarray) {
10099: return ($e,$f);
10100: } else {
10101: my $g;
10102: {
10103: use integer;
10104: $g=($e+$f);
10105: if ($_64bit) {
10106: $g=(($g<<32)>>32);
10107: }
10108: }
10109: return $g;
10110: }
10111: }
10112:
1.368 albertel 10113: sub latest_rnd_algorithm_id {
1.675 albertel 10114: return '64bit5';
1.366 albertel 10115: }
1.32 www 10116:
1.503 albertel 10117: sub get_rand_alg {
10118: my ($courseid)=@_;
1.790 albertel 10119: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10120: if ($courseid) {
1.620 albertel 10121: return $env{"course.$courseid.rndseed"};
1.503 albertel 10122: }
10123: return &latest_rnd_algorithm_id();
10124: }
10125:
1.562 albertel 10126: sub validCODE {
10127: my ($CODE)=@_;
10128: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10129: return 0;
10130: }
10131:
1.491 albertel 10132: sub getCODE {
1.620 albertel 10133: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10134: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10135: defined($Apache::lonhomework::parsing_a_task) ) &&
10136: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10137: return $Apache::lonhomework::history{'resource.CODE'};
10138: }
10139: return undef;
10140: }
1.1133 foxr 10141: #
10142: # Determines the random seed for a specific context:
10143: #
10144: # parameters:
10145: # symb - in course context the symb for the seed.
10146: # course_id - The course id of the form domain_coursenum.
10147: # domain - Domain for the user.
10148: # course - Course for the user.
10149: # cenv - environment of the course.
10150: #
10151: # NOTE:
10152: # All parameters are picked out of the environment if missing
10153: # or not defined.
10154: # If a symb cannot be determined the current time is used instead.
10155: #
10156: # For a given well defined symb, courside, domain, username,
10157: # and course environment, the seed is reproducible.
10158: #
1.31 www 10159: sub rndseed {
1.1133 foxr 10160: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10161: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10162: if (!defined($symb)) {
1.366 albertel 10163: unless ($symb=$wsymb) { return time; }
10164: }
1.1146 foxr 10165: if (!defined $courseid) {
10166: $courseid=$wcourseid;
10167: }
10168: if (!defined $domain) { $domain=$wdomain; }
10169: if (!defined $username) { $username=$wusername }
1.1133 foxr 10170:
10171: my $which;
10172: if (defined($cenv->{'rndseed'})) {
10173: $which = $cenv->{'rndseed'};
10174: } else {
10175: $which =&get_rand_alg($courseid);
10176: }
1.491 albertel 10177: if (defined(&getCODE())) {
1.1133 foxr 10178:
1.675 albertel 10179: if ($which eq '64bit5') {
10180: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10181: } elsif ($which eq '64bit4') {
1.575 albertel 10182: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10183: } else {
10184: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10185: }
1.675 albertel 10186: } elsif ($which eq '64bit5') {
10187: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10188: } elsif ($which eq '64bit4') {
10189: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10190: } elsif ($which eq '64bit3') {
10191: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10192: } elsif ($which eq '64bit2') {
10193: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10194: } elsif ($which eq '64bit') {
10195: return &rndseed_64bit($symb,$courseid,$domain,$username);
10196: }
10197: return &rndseed_32bit($symb,$courseid,$domain,$username);
10198: }
10199:
10200: sub rndseed_32bit {
10201: my ($symb,$courseid,$domain,$username)=@_;
10202: {
10203: use integer;
10204: my $symbchck=unpack("%32C*",$symb) << 27;
10205: my $symbseed=numval($symb) << 22;
10206: my $namechck=unpack("%32C*",$username) << 17;
10207: my $nameseed=numval($username) << 12;
10208: my $domainseed=unpack("%32C*",$domain) << 7;
10209: my $courseseed=unpack("%32C*",$courseid);
10210: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10211: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10212: #&logthis("rndseed :$num:$symb");
1.564 albertel 10213: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10214: return $num;
10215: }
10216: }
10217:
10218: sub rndseed_64bit {
10219: my ($symb,$courseid,$domain,$username)=@_;
10220: {
10221: use integer;
10222: my $symbchck=unpack("%32S*",$symb) << 21;
10223: my $symbseed=numval($symb) << 10;
10224: my $namechck=unpack("%32S*",$username);
10225:
10226: my $nameseed=numval($username) << 21;
10227: my $domainseed=unpack("%32S*",$domain) << 10;
10228: my $courseseed=unpack("%32S*",$courseid);
10229:
10230: my $num1=$symbchck+$symbseed+$namechck;
10231: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10232: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10233: #&logthis("rndseed :$num:$symb");
1.564 albertel 10234: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10235: return "$num1,$num2";
1.155 albertel 10236: }
1.366 albertel 10237: }
10238:
1.443 albertel 10239: sub rndseed_64bit2 {
10240: my ($symb,$courseid,$domain,$username)=@_;
10241: {
10242: use integer;
10243: # strings need to be an even # of cahracters long, it it is odd the
10244: # last characters gets thrown away
10245: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10246: my $symbseed=numval($symb) << 10;
10247: my $namechck=unpack("%32S*",$username.' ');
10248:
10249: my $nameseed=numval($username) << 21;
1.501 albertel 10250: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10251: my $courseseed=unpack("%32S*",$courseid.' ');
10252:
10253: my $num1=$symbchck+$symbseed+$namechck;
10254: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10255: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10256: #&logthis("rndseed :$num:$symb");
1.803 albertel 10257: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10258: return "$num1,$num2";
10259: }
10260: }
10261:
10262: sub rndseed_64bit3 {
10263: my ($symb,$courseid,$domain,$username)=@_;
10264: {
10265: use integer;
10266: # strings need to be an even # of cahracters long, it it is odd the
10267: # last characters gets thrown away
10268: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10269: my $symbseed=numval2($symb) << 10;
10270: my $namechck=unpack("%32S*",$username.' ');
10271:
10272: my $nameseed=numval2($username) << 21;
1.443 albertel 10273: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10274: my $courseseed=unpack("%32S*",$courseid.' ');
10275:
10276: my $num1=$symbchck+$symbseed+$namechck;
10277: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10278: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10279: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10280: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10281:
1.503 albertel 10282: return "$num1:$num2";
1.443 albertel 10283: }
10284: }
10285:
1.575 albertel 10286: sub rndseed_64bit4 {
10287: my ($symb,$courseid,$domain,$username)=@_;
10288: {
10289: use integer;
10290: # strings need to be an even # of cahracters long, it it is odd the
10291: # last characters gets thrown away
10292: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10293: my $symbseed=numval3($symb) << 10;
10294: my $namechck=unpack("%32S*",$username.' ');
10295:
10296: my $nameseed=numval3($username) << 21;
10297: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10298: my $courseseed=unpack("%32S*",$courseid.' ');
10299:
10300: my $num1=$symbchck+$symbseed+$namechck;
10301: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10302: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10303: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10304: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10305:
1.575 albertel 10306: return "$num1:$num2";
10307: }
10308: }
10309:
1.675 albertel 10310: sub rndseed_64bit5 {
10311: my ($symb,$courseid,$domain,$username)=@_;
10312: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10313: return "$num1:$num2";
10314: }
10315:
1.366 albertel 10316: sub rndseed_CODE_64bit {
10317: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10318: {
1.366 albertel 10319: use integer;
1.443 albertel 10320: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10321: my $symbseed=numval2($symb);
1.491 albertel 10322: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10323: my $CODEseed=numval(&getCODE());
1.443 albertel 10324: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10325: my $num1=$symbseed+$CODEchck;
10326: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10327: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10328: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10329: if ($_64bit) { $num1=(($num1<<32)>>32); }
10330: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10331: return "$num1:$num2";
1.366 albertel 10332: }
10333: }
10334:
1.575 albertel 10335: sub rndseed_CODE_64bit4 {
10336: my ($symb,$courseid,$domain,$username)=@_;
10337: {
10338: use integer;
10339: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10340: my $symbseed=numval3($symb);
10341: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10342: my $CODEseed=numval3(&getCODE());
10343: my $courseseed=unpack("%32S*",$courseid.' ');
10344: my $num1=$symbseed+$CODEchck;
10345: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10346: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10347: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10348: if ($_64bit) { $num1=(($num1<<32)>>32); }
10349: if ($_64bit) { $num2=(($num2<<32)>>32); }
10350: return "$num1:$num2";
10351: }
10352: }
10353:
1.675 albertel 10354: sub rndseed_CODE_64bit5 {
10355: my ($symb,$courseid,$domain,$username)=@_;
10356: my $code = &getCODE();
10357: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10358: return "$num1:$num2";
10359: }
10360:
1.366 albertel 10361: sub setup_random_from_rndseed {
10362: my ($rndseed)=@_;
1.503 albertel 10363: if ($rndseed =~/([,:])/) {
10364: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10365: &Math::Random::random_set_seed(abs($num1),abs($num2));
10366: } else {
10367: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10368: }
1.36 albertel 10369: }
10370:
1.474 albertel 10371: sub latest_receipt_algorithm_id {
1.835 albertel 10372: return 'receipt3';
1.474 albertel 10373: }
10374:
1.480 www 10375: sub recunique {
10376: my $fucourseid=shift;
10377: my $unique;
1.835 albertel 10378: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10379: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10380: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10381: } else {
10382: $unique=$perlvar{'lonReceipt'};
10383: }
10384: return unpack("%32C*",$unique);
10385: }
10386:
10387: sub recprefix {
10388: my $fucourseid=shift;
10389: my $prefix;
1.835 albertel 10390: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10391: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10392: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10393: } else {
10394: $prefix=$perlvar{'lonHostID'};
10395: }
10396: return unpack("%32C*",$prefix);
10397: }
10398:
1.76 www 10399: sub ireceipt {
1.474 albertel 10400: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10401:
10402: my $return =&recprefix($fucourseid).'-';
10403:
10404: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10405: $env{'request.state'} eq 'construct') {
10406: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10407: return $return;
10408: }
10409:
1.76 www 10410: my $cuname=unpack("%32C*",$funame);
10411: my $cudom=unpack("%32C*",$fudom);
10412: my $cucourseid=unpack("%32C*",$fucourseid);
10413: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10414: my $cunique=&recunique($fucourseid);
1.474 albertel 10415: my $cpart=unpack("%32S*",$part);
1.835 albertel 10416: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10417:
1.790 albertel 10418: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10419:
10420: $return.= ($cunique%$cuname+
10421: $cunique%$cudom+
10422: $cusymb%$cuname+
10423: $cusymb%$cudom+
10424: $cucourseid%$cuname+
10425: $cucourseid%$cudom+
10426: $cpart%$cuname+
10427: $cpart%$cudom);
10428: } else {
10429: $return.= ($cunique%$cuname+
10430: $cunique%$cudom+
10431: $cusymb%$cuname+
10432: $cusymb%$cudom+
10433: $cucourseid%$cuname+
10434: $cucourseid%$cudom);
10435: }
10436: return $return;
1.76 www 10437: }
10438:
10439: sub receipt {
1.474 albertel 10440: my ($part)=@_;
1.790 albertel 10441: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10442: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10443: }
1.260 ng 10444:
1.790 albertel 10445: sub whichuser {
10446: my ($passedsymb)=@_;
10447: my ($symb,$courseid,$domain,$name,$publicuser);
10448: if (defined($env{'form.grade_symb'})) {
10449: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10450: my $allowed=&allowed('vgr',$tmp_courseid);
10451: if (!$allowed &&
10452: exists($env{'request.course.sec'}) &&
10453: $env{'request.course.sec'} !~ /^\s*$/) {
10454: $allowed=&allowed('vgr',$tmp_courseid.
10455: '/'.$env{'request.course.sec'});
10456: }
10457: if ($allowed) {
10458: ($symb)=&get_env_multiple('form.grade_symb');
10459: $courseid=$tmp_courseid;
10460: ($domain)=&get_env_multiple('form.grade_domain');
10461: ($name)=&get_env_multiple('form.grade_username');
10462: return ($symb,$courseid,$domain,$name,$publicuser);
10463: }
10464: }
10465: if (!$passedsymb) {
10466: $symb=&symbread();
10467: } else {
10468: $symb=$passedsymb;
10469: }
10470: $courseid=$env{'request.course.id'};
10471: $domain=$env{'user.domain'};
10472: $name=$env{'user.name'};
10473: if ($name eq 'public' && $domain eq 'public') {
10474: if (!defined($env{'form.username'})) {
10475: $env{'form.username'}.=time.rand(10000000);
10476: }
10477: $name.=$env{'form.username'};
10478: }
10479: return ($symb,$courseid,$domain,$name,$publicuser);
10480:
10481: }
10482:
1.36 albertel 10483: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10484: # returns either the contents of the file or
10485: # -1 if the file doesn't exist
1.481 raeburn 10486: #
10487: # if the target is a file that was uploaded via DOCS,
10488: # a check will be made to see if a current copy exists on the local server,
10489: # if it does this will be served, otherwise a copy will be retrieved from
10490: # the home server for the course and stored in /home/httpd/html/userfiles on
10491: # the local server.
1.472 albertel 10492:
1.36 albertel 10493: sub getfile {
1.538 albertel 10494: my ($file) = @_;
1.609 banghart 10495: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10496: &repcopy($file);
10497: return &readfile($file);
10498: }
10499:
10500: sub repcopy_userfile {
10501: my ($file)=@_;
1.1142 raeburn 10502: my $londocroot = $perlvar{'lonDocRoot'};
10503: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10504: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10505: my ($cdom,$cnum,$filename) =
1.811 albertel 10506: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10507: my $uri="/uploaded/$cdom/$cnum/$filename";
10508: if (-e "$file") {
1.828 www 10509: # we already have a local copy, check it out
1.538 albertel 10510: my @fileinfo = stat($file);
1.828 www 10511: my $rtncode;
10512: my $info;
1.538 albertel 10513: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10514: if ($lwpresp ne 'ok') {
1.828 www 10515: # there is no such file anymore, even though we had a local copy
1.482 albertel 10516: if ($rtncode eq '404') {
1.538 albertel 10517: unlink($file);
1.482 albertel 10518: }
10519: return -1;
10520: }
10521: if ($info < $fileinfo[9]) {
1.828 www 10522: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10523: return 'ok';
1.828 www 10524: } else {
10525: # the file is outdated, get rid of it
10526: unlink($file);
1.482 albertel 10527: }
1.828 www 10528: }
10529: # one way or the other, at this point, we don't have the file
10530: # construct the correct path for the file
10531: my @parts = ($cdom,$cnum);
10532: if ($filename =~ m|^(.+)/[^/]+$|) {
10533: push @parts, split(/\//,$1);
10534: }
10535: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10536: foreach my $part (@parts) {
10537: $path .= '/'.$part;
10538: if (!-e $path) {
10539: mkdir($path,0770);
1.482 albertel 10540: }
10541: }
1.828 www 10542: # now the path exists for sure
10543: # get a user agent
10544: my $ua=new LWP::UserAgent;
10545: my $transferfile=$file.'.in.transfer';
10546: # FIXME: this should flock
10547: if (-e $transferfile) { return 'ok'; }
10548: my $request;
10549: $uri=~s/^\///;
1.980 raeburn 10550: my $homeserver = &homeserver($cnum,$cdom);
10551: my $protocol = $protocol{$homeserver};
10552: $protocol = 'http' if ($protocol ne 'https');
10553: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10554: my $response=$ua->request($request,$transferfile);
10555: # did it work?
10556: if ($response->is_error()) {
10557: unlink($transferfile);
10558: &logthis("Userfile repcopy failed for $uri");
10559: return -1;
10560: }
10561: # worked, rename the transfer file
10562: rename($transferfile,$file);
1.607 raeburn 10563: return 'ok';
1.481 raeburn 10564: }
10565:
1.517 albertel 10566: sub tokenwrapper {
10567: my $uri=shift;
1.980 raeburn 10568: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10569: $uri=~s|^/||;
1.620 albertel 10570: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10571: my $token=$1;
1.552 albertel 10572: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10573: if ($udom && $uname && $file) {
10574: $file=~s|(\?\.*)*$||;
1.949 raeburn 10575: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10576: my $homeserver = &homeserver($uname,$udom);
10577: my $protocol = $protocol{$homeserver};
10578: $protocol = 'http' if ($protocol ne 'https');
10579: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10580: (($uri=~/\?/)?'&':'?').'token='.$token.
10581: '&tokenissued='.$perlvar{'lonHostID'};
10582: } else {
10583: return '/adm/notfound.html';
10584: }
10585: }
10586:
1.828 www 10587: # call with reqtype HEAD: get last modification time
10588: # call with reqtype GET: get the file contents
10589: # Do not call this with reqtype GET for large files! It loads everything into memory
10590: #
1.481 raeburn 10591: sub getuploaded {
10592: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10593: $uri=~s/^\///;
1.980 raeburn 10594: my $homeserver = &homeserver($cnum,$cdom);
10595: my $protocol = $protocol{$homeserver};
10596: $protocol = 'http' if ($protocol ne 'https');
10597: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10598: my $ua=new LWP::UserAgent;
10599: my $request=new HTTP::Request($reqtype,$uri);
10600: my $response=$ua->request($request);
10601: $$rtncode = $response->code;
1.482 albertel 10602: if (! $response->is_success()) {
10603: return 'failed';
10604: }
10605: if ($reqtype eq 'HEAD') {
1.486 www 10606: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10607: } elsif ($reqtype eq 'GET') {
10608: $$info = $response->content;
1.472 albertel 10609: }
1.482 albertel 10610: return 'ok';
1.36 albertel 10611: }
10612:
1.481 raeburn 10613: sub readfile {
10614: my $file = shift;
10615: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10616: my $fh;
10617: open($fh,"<$file");
10618: my $a='';
1.800 albertel 10619: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10620: return $a;
10621: }
10622:
1.36 albertel 10623: sub filelocation {
1.590 banghart 10624: my ($dir,$file) = @_;
10625: my $location;
10626: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10627:
10628: if ($file =~ m-^/adm/-) {
10629: $file=~s-^/adm/wrapper/-/-;
10630: $file=~s-^/adm/coursedocs/showdoc/-/-;
10631: }
1.882 albertel 10632:
1.1139 www 10633: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10634: $location = $file;
1.609 banghart 10635: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10636: my ($udom,$uname,$filename)=
1.811 albertel 10637: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10638: my $home=&homeserver($uname,$udom);
10639: my $is_me=0;
10640: my @ids=¤t_machine_ids();
10641: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10642: if ($is_me) {
1.1117 foxr 10643: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10644: } else {
10645: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10646: $udom.'/'.$uname.'/'.$filename;
10647: }
1.882 albertel 10648: } elsif ($file =~ m-^/adm/-) {
10649: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10650: } else {
10651: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10652: $file=~s:^/(res|priv)/:/:;
10653: my $space=$1;
1.590 banghart 10654: if ( !( $file =~ m:^/:) ) {
10655: $location = $dir. '/'.$file;
10656: } else {
1.1142 raeburn 10657: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10658: }
1.59 albertel 10659: }
1.590 banghart 10660: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10661: while ($location=~m{/\.\./}) {
10662: if ($location =~ m{/[^/]+/\.\./}) {
10663: $location=~ s{/[^/]+/\.\./}{/}g;
10664: } else {
10665: $location=~ s{/\.\./}{/}g;
10666: }
10667: } #remove dir/..
1.590 banghart 10668: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10669: return $location;
1.46 www 10670: }
1.36 albertel 10671:
1.46 www 10672: sub hreflocation {
10673: my ($dir,$file)=@_;
1.980 raeburn 10674: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10675: $file=filelocation($dir,$file);
1.700 albertel 10676: } elsif ($file=~m-^/adm/-) {
10677: $file=~s-^/adm/wrapper/-/-;
10678: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10679: }
10680: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10681: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10682: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10683: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10684: {/uploaded/$1/$2/}x;
1.46 www 10685: }
1.913 albertel 10686: if ($file=~ m{^/userfiles/}) {
10687: $file =~ s{^/userfiles/}{/uploaded/};
10688: }
1.462 albertel 10689: return $file;
1.465 albertel 10690: }
10691:
1.1139 www 10692:
10693:
10694:
10695:
1.465 albertel 10696: sub current_machine_domains {
1.853 albertel 10697: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10698: }
10699:
10700: sub machine_domains {
10701: my ($hostname) = @_;
1.465 albertel 10702: my @domains;
1.838 albertel 10703: my %hostname = &all_hostnames();
1.465 albertel 10704: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10705: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10706: if ($hostname eq $name) {
1.844 albertel 10707: push(@domains,&host_domain($id));
1.465 albertel 10708: }
10709: }
10710: return @domains;
10711: }
10712:
10713: sub current_machine_ids {
1.853 albertel 10714: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10715: }
10716:
10717: sub machine_ids {
10718: my ($hostname) = @_;
10719: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10720: my @ids;
1.888 albertel 10721: my %name_to_host = &all_names();
1.889 albertel 10722: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10723: return @{ $name_to_host{$hostname} };
10724: }
10725: return;
1.31 www 10726: }
10727:
1.824 raeburn 10728: sub additional_machine_domains {
10729: my @domains;
10730: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10731: while( my $line = <$fh>) {
10732: $line =~ s/\s//g;
10733: push(@domains,$line);
10734: }
10735: return @domains;
10736: }
10737:
10738: sub default_login_domain {
10739: my $domain = $perlvar{'lonDefDomain'};
10740: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10741: foreach my $posdom (¤t_machine_domains(),
10742: &additional_machine_domains()) {
10743: if (lc($posdom) eq lc($testdomain)) {
10744: $domain=$posdom;
10745: last;
10746: }
10747: }
10748: return $domain;
10749: }
10750:
1.31 www 10751: # ------------------------------------------------------------- Declutters URLs
10752:
10753: sub declutter {
10754: my $thisfn=shift;
1.569 albertel 10755: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10756: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10757: $thisfn=~s/^\///;
1.697 albertel 10758: $thisfn=~s|^adm/wrapper/||;
10759: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10760: $thisfn=~s/^res\///;
1.1172 bisitz 10761: $thisfn=~s/^priv\///;
1.1032 raeburn 10762: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10763: $thisfn=~s/\?.+$//;
10764: }
1.268 www 10765: return $thisfn;
10766: }
10767:
10768: # ------------------------------------------------------------- Clutter up URLs
10769:
10770: sub clutter {
10771: my $thisfn='/'.&declutter(shift);
1.887 albertel 10772: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10773: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10774: $thisfn='/res'.$thisfn;
10775: }
1.1031 raeburn 10776: if ($thisfn !~m|^/adm|) {
10777: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10778: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10779: } else {
10780: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10781: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10782: if ($embstyle eq 'ssi'
10783: || ($embstyle eq 'hdn')
10784: || ($embstyle eq 'rat')
10785: || ($embstyle eq 'prv')
10786: || ($embstyle eq 'ign')) {
10787: #do nothing with these
10788: } elsif (($embstyle eq 'img')
1.695 albertel 10789: || ($embstyle eq 'emb')
10790: || ($embstyle eq 'wrp')) {
10791: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10792: } elsif ($embstyle eq 'unk'
10793: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10794: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10795: } else {
1.718 www 10796: # &logthis("Got a blank emb style");
1.695 albertel 10797: }
1.694 albertel 10798: }
10799: }
1.31 www 10800: return $thisfn;
1.12 www 10801: }
10802:
1.787 albertel 10803: sub clutter_with_no_wrapper {
10804: my $uri = &clutter(shift);
10805: if ($uri =~ m-^/adm/-) {
10806: $uri =~ s-^/adm/wrapper/-/-;
10807: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10808: }
10809: return $uri;
10810: }
10811:
1.557 albertel 10812: sub freeze_escape {
10813: my ($value)=@_;
10814: if (ref($value)) {
10815: $value=&nfreeze($value);
10816: return '__FROZEN__'.&escape($value);
10817: }
10818: return &escape($value);
10819: }
10820:
1.11 www 10821:
1.557 albertel 10822: sub thaw_unescape {
10823: my ($value)=@_;
10824: if ($value =~ /^__FROZEN__/) {
10825: substr($value,0,10,undef);
10826: $value=&unescape($value);
10827: return &thaw($value);
10828: }
10829: return &unescape($value);
10830: }
10831:
1.436 albertel 10832: sub correct_line_ends {
10833: my ($result)=@_;
10834: $$result =~s/\r\n/\n/mg;
10835: $$result =~s/\r/\n/mg;
1.415 albertel 10836: }
1.1 albertel 10837: # ================================================================ Main Program
10838:
1.184 www 10839: sub goodbye {
1.204 albertel 10840: &logthis("Starting Shut down");
1.443 albertel 10841: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10842: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10843: #converted
1.599 albertel 10844: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10845: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10846: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10847: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10848: #1.1 only
1.870 albertel 10849: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10850: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10851: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10852: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10853: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10854: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10855: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10856: &flushcourselogs();
10857: &logthis("Shutting down");
10858: }
10859:
1.852 albertel 10860: sub get_dns {
1.869 albertel 10861: my ($url,$func,$ignore_cache) = @_;
10862: if (!$ignore_cache) {
10863: my ($content,$cached)=
10864: &Apache::lonnet::is_cached_new('dns',$url);
10865: if ($cached) {
10866: &$func($content);
10867: return;
10868: }
10869: }
10870:
10871: my %alldns;
1.852 albertel 10872: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10873: foreach my $dns (<$config>) {
10874: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10875: my $line = $1;
10876: my ($host,$protocol) = split(/:/,$line);
10877: if ($protocol ne 'https') {
10878: $protocol = 'http';
10879: }
10880: $alldns{$host} = $protocol;
1.869 albertel 10881: }
10882: while (%alldns) {
10883: my ($dns) = keys(%alldns);
1.852 albertel 10884: my $ua=new LWP::UserAgent;
1.1134 raeburn 10885: $ua->timeout(30);
1.979 raeburn 10886: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10887: my $response=$ua->request($request);
1.979 raeburn 10888: delete($alldns{$dns});
1.852 albertel 10889: next if ($response->is_error());
10890: my @content = split("\n",$response->content);
1.869 albertel 10891: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10892: &$func(\@content);
1.869 albertel 10893: return;
1.852 albertel 10894: }
10895: close($config);
1.871 albertel 10896: my $which = (split('/',$url))[3];
10897: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10898: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10899: my @content = <$config>;
10900: &$func(\@content);
10901: return;
1.852 albertel 10902: }
1.327 albertel 10903: # ------------------------------------------------------------ Read domain file
10904: {
1.852 albertel 10905: my $loaded;
1.846 albertel 10906: my %domain;
10907:
1.852 albertel 10908: sub parse_domain_tab {
10909: my ($lines) = @_;
10910: foreach my $line (@$lines) {
10911: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10912:
1.846 albertel 10913: chomp($line);
1.852 albertel 10914: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10915: my %this_domain;
10916: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10917: 'lang_def', 'city', 'longi', 'lati',
10918: 'primary') {
10919: $this_domain{$field} = shift(@elements);
10920: }
10921: $domain{$name} = \%this_domain;
1.852 albertel 10922: }
10923: }
1.864 albertel 10924:
10925: sub reset_domain_info {
10926: undef($loaded);
10927: undef(%domain);
10928: }
10929:
1.852 albertel 10930: sub load_domain_tab {
1.869 albertel 10931: my ($ignore_cache) = @_;
10932: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10933: my $fh;
10934: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10935: my @lines = <$fh>;
10936: &parse_domain_tab(\@lines);
1.448 albertel 10937: }
1.852 albertel 10938: close($fh);
10939: $loaded = 1;
1.327 albertel 10940: }
1.846 albertel 10941:
10942: sub domain {
1.852 albertel 10943: &load_domain_tab() if (!$loaded);
10944:
1.846 albertel 10945: my ($name,$what) = @_;
10946: return if ( !exists($domain{$name}) );
10947:
10948: if (!$what) {
10949: return $domain{$name}{'description'};
10950: }
10951: return $domain{$name}{$what};
10952: }
1.974 raeburn 10953:
10954: sub domain_info {
10955: &load_domain_tab() if (!$loaded);
10956: return %domain;
10957: }
10958:
1.327 albertel 10959: }
10960:
10961:
1.1 albertel 10962: # ------------------------------------------------------------- Read hosts file
10963: {
1.838 albertel 10964: my %hostname;
1.844 albertel 10965: my %hostdom;
1.845 albertel 10966: my %libserv;
1.852 albertel 10967: my $loaded;
1.888 albertel 10968: my %name_to_host;
1.1074 raeburn 10969: my %internetdom;
1.1107 raeburn 10970: my %LC_dns_serv;
1.852 albertel 10971:
10972: sub parse_hosts_tab {
10973: my ($file) = @_;
10974: foreach my $configline (@$file) {
10975: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10976: chomp($configline);
10977: if ($configline =~ /^\^/) {
10978: if ($configline =~ /^\^([\w.\-]+)/) {
10979: $LC_dns_serv{$1} = 1;
10980: }
10981: next;
10982: }
1.1074 raeburn 10983: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10984: $name=~s/\s//g;
10985: if ($id && $domain && $role && $name) {
10986: $hostname{$id}=$name;
1.888 albertel 10987: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10988: $hostdom{$id}=$domain;
10989: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10990: if (defined($protocol)) {
10991: if ($protocol eq 'https') {
10992: $protocol{$id} = $protocol;
10993: } else {
10994: $protocol{$id} = 'http';
10995: }
1.968 raeburn 10996: } else {
1.969 raeburn 10997: $protocol{$id} = 'http';
1.968 raeburn 10998: }
1.1074 raeburn 10999: if (defined($intdom)) {
11000: $internetdom{$id} = $intdom;
11001: }
1.852 albertel 11002: }
11003: }
11004: }
1.864 albertel 11005:
11006: sub reset_hosts_info {
1.897 albertel 11007: &purge_remembered();
1.864 albertel 11008: &reset_domain_info();
11009: &reset_hosts_ip_info();
1.892 albertel 11010: undef(%name_to_host);
1.864 albertel 11011: undef(%hostname);
11012: undef(%hostdom);
11013: undef(%libserv);
11014: undef($loaded);
11015: }
1.1 albertel 11016:
1.852 albertel 11017: sub load_hosts_tab {
1.869 albertel 11018: my ($ignore_cache) = @_;
11019: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11020: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11021: my @config = <$config>;
11022: &parse_hosts_tab(\@config);
11023: close($config);
11024: $loaded=1;
1.1 albertel 11025: }
1.852 albertel 11026:
1.838 albertel 11027: sub hostname {
1.852 albertel 11028: &load_hosts_tab() if (!$loaded);
11029:
1.838 albertel 11030: my ($lonid) = @_;
11031: return $hostname{$lonid};
11032: }
1.845 albertel 11033:
1.838 albertel 11034: sub all_hostnames {
1.852 albertel 11035: &load_hosts_tab() if (!$loaded);
11036:
1.838 albertel 11037: return %hostname;
11038: }
1.845 albertel 11039:
1.888 albertel 11040: sub all_names {
11041: &load_hosts_tab() if (!$loaded);
11042:
11043: return %name_to_host;
11044: }
11045:
1.974 raeburn 11046: sub all_host_domain {
11047: &load_hosts_tab() if (!$loaded);
11048: return %hostdom;
11049: }
11050:
1.845 albertel 11051: sub is_library {
1.852 albertel 11052: &load_hosts_tab() if (!$loaded);
11053:
1.845 albertel 11054: return exists($libserv{$_[0]});
11055: }
11056:
11057: sub all_library {
1.852 albertel 11058: &load_hosts_tab() if (!$loaded);
11059:
1.845 albertel 11060: return %libserv;
11061: }
11062:
1.1062 droeschl 11063: sub unique_library {
11064: #2x reverse removes all hostnames that appear more than once
11065: my %unique = reverse &all_library();
11066: return reverse %unique;
11067: }
11068:
1.841 albertel 11069: sub get_servers {
1.852 albertel 11070: &load_hosts_tab() if (!$loaded);
11071:
1.841 albertel 11072: my ($domain,$type) = @_;
11073: my %possible_hosts = ($type eq 'library') ? %libserv
11074: : %hostname;
11075: my %result;
1.842 albertel 11076: if (ref($domain) eq 'ARRAY') {
11077: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11078: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11079: $result{$host} = $hostname;
11080: }
11081: }
11082: } else {
11083: while ( my ($host,$hostname) = each(%possible_hosts)) {
11084: if ($hostdom{$host} eq $domain) {
11085: $result{$host} = $hostname;
11086: }
1.841 albertel 11087: }
11088: }
11089: return %result;
11090: }
1.845 albertel 11091:
1.1062 droeschl 11092: sub get_unique_servers {
11093: my %unique = reverse &get_servers(@_);
11094: return reverse %unique;
11095: }
11096:
1.844 albertel 11097: sub host_domain {
1.852 albertel 11098: &load_hosts_tab() if (!$loaded);
11099:
1.844 albertel 11100: my ($lonid) = @_;
11101: return $hostdom{$lonid};
11102: }
11103:
1.841 albertel 11104: sub all_domains {
1.852 albertel 11105: &load_hosts_tab() if (!$loaded);
11106:
1.841 albertel 11107: my %seen;
11108: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11109: return @uniq;
11110: }
1.1074 raeburn 11111:
11112: sub internet_dom {
11113: &load_hosts_tab() if (!$loaded);
11114:
11115: my ($lonid) = @_;
11116: return $internetdom{$lonid};
11117: }
1.1107 raeburn 11118:
11119: sub is_LC_dns {
11120: &load_hosts_tab() if (!$loaded);
11121:
11122: my ($hostname) = @_;
11123: return exists($LC_dns_serv{$hostname});
11124: }
11125:
1.1 albertel 11126: }
11127:
1.847 albertel 11128: {
11129: my %iphost;
1.856 albertel 11130: my %name_to_ip;
11131: my %lonid_to_ip;
1.869 albertel 11132:
1.847 albertel 11133: sub get_hosts_from_ip {
11134: my ($ip) = @_;
11135: my %iphosts = &get_iphost();
11136: if (ref($iphosts{$ip})) {
11137: return @{$iphosts{$ip}};
11138: }
11139: return;
1.839 albertel 11140: }
1.864 albertel 11141:
11142: sub reset_hosts_ip_info {
11143: undef(%iphost);
11144: undef(%name_to_ip);
11145: undef(%lonid_to_ip);
11146: }
1.856 albertel 11147:
11148: sub get_host_ip {
11149: my ($lonid) = @_;
11150: if (exists($lonid_to_ip{$lonid})) {
11151: return $lonid_to_ip{$lonid};
11152: }
11153: my $name=&hostname($lonid);
11154: my $ip = gethostbyname($name);
11155: return if (!$ip || length($ip) ne 4);
11156: $ip=inet_ntoa($ip);
11157: $name_to_ip{$name} = $ip;
11158: $lonid_to_ip{$lonid} = $ip;
11159: return $ip;
11160: }
1.847 albertel 11161:
11162: sub get_iphost {
1.869 albertel 11163: my ($ignore_cache) = @_;
1.894 albertel 11164:
1.869 albertel 11165: if (!$ignore_cache) {
11166: if (%iphost) {
11167: return %iphost;
11168: }
11169: my ($ip_info,$cached)=
11170: &Apache::lonnet::is_cached_new('iphost','iphost');
11171: if ($cached) {
11172: %iphost = %{$ip_info->[0]};
11173: %name_to_ip = %{$ip_info->[1]};
11174: %lonid_to_ip = %{$ip_info->[2]};
11175: return %iphost;
11176: }
11177: }
1.894 albertel 11178:
11179: # get yesterday's info for fallback
11180: my %old_name_to_ip;
11181: my ($ip_info,$cached)=
11182: &Apache::lonnet::is_cached_new('iphost','iphost');
11183: if ($cached) {
11184: %old_name_to_ip = %{$ip_info->[1]};
11185: }
11186:
1.888 albertel 11187: my %name_to_host = &all_names();
11188: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11189: my $ip;
11190: if (!exists($name_to_ip{$name})) {
11191: $ip = gethostbyname($name);
11192: if (!$ip || length($ip) ne 4) {
1.894 albertel 11193: if (defined($old_name_to_ip{$name})) {
11194: $ip = $old_name_to_ip{$name};
11195: &logthis("Can't find $name defaulting to old $ip");
11196: } else {
11197: &logthis("Name $name no IP found");
11198: next;
11199: }
11200: } else {
11201: $ip=inet_ntoa($ip);
1.847 albertel 11202: }
11203: $name_to_ip{$name} = $ip;
11204: } else {
11205: $ip = $name_to_ip{$name};
1.653 albertel 11206: }
1.888 albertel 11207: foreach my $id (@{ $name_to_host{$name} }) {
11208: $lonid_to_ip{$id} = $ip;
11209: }
11210: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11211: }
1.869 albertel 11212: &Apache::lonnet::do_cache_new('iphost','iphost',
11213: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11214: 48*60*60);
1.869 albertel 11215:
1.847 albertel 11216: return %iphost;
1.598 albertel 11217: }
11218:
1.992 raeburn 11219: #
11220: # Given a DNS returns the loncapa host name for that DNS
11221: #
11222: sub host_from_dns {
11223: my ($dns) = @_;
11224: my @hosts;
11225: my $ip;
11226:
1.993 raeburn 11227: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11228: $ip = $name_to_ip{$dns};
11229: }
11230: if (!$ip) {
11231: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11232: if (length($ip) == 4) {
11233: $ip = &IO::Socket::inet_ntoa($ip);
11234: }
11235: }
11236: if ($ip) {
11237: @hosts = get_hosts_from_ip($ip);
11238: return $hosts[0];
11239: }
11240: return undef;
1.986 foxr 11241: }
1.992 raeburn 11242:
1.1074 raeburn 11243: sub get_internet_names {
11244: my ($lonid) = @_;
11245: return if ($lonid eq '');
11246: my ($idnref,$cached)=
11247: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11248: if ($cached) {
11249: return $idnref;
11250: }
11251: my $ip = &get_host_ip($lonid);
11252: my @hosts = &get_hosts_from_ip($ip);
11253: my %iphost = &get_iphost();
11254: my (@idns,%seen);
11255: foreach my $id (@hosts) {
11256: my $dom = &host_domain($id);
11257: my $prim_id = &domain($dom,'primary');
11258: my $prim_ip = &get_host_ip($prim_id);
11259: next if ($seen{$prim_ip});
11260: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11261: foreach my $id (@{$iphost{$prim_ip}}) {
11262: my $intdom = &internet_dom($id);
11263: unless (grep(/^\Q$intdom\E$/,@idns)) {
11264: push(@idns,$intdom);
11265: }
11266: }
11267: }
11268: $seen{$prim_ip} = 1;
11269: }
11270: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11271: }
11272:
1.986 foxr 11273: }
11274:
1.1079 raeburn 11275: sub all_loncaparevs {
11276: 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);
11277: }
11278:
1.862 albertel 11279: BEGIN {
11280:
11281: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11282: unless ($readit) {
11283: {
11284: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11285: %perlvar = (%perlvar,%{$configvars});
11286: }
11287:
11288:
1.1 albertel 11289: # ------------------------------------------------------ Read spare server file
11290: {
1.448 albertel 11291: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11292:
11293: while (my $configline=<$config>) {
11294: chomp($configline);
1.284 matthew 11295: if ($configline) {
1.784 albertel 11296: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11297: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11298: push(@{ $spareid{$type} }, $host);
1.1 albertel 11299: }
11300: }
1.448 albertel 11301: close($config);
1.1 albertel 11302: }
1.11 www 11303: # ------------------------------------------------------------ Read permissions
11304: {
1.448 albertel 11305: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11306:
11307: while (my $configline=<$config>) {
1.448 albertel 11308: chomp($configline);
11309: if ($configline) {
11310: my ($role,$perm)=split(/ /,$configline);
11311: if ($perm ne '') { $pr{$role}=$perm; }
11312: }
1.11 www 11313: }
1.448 albertel 11314: close($config);
1.11 www 11315: }
11316:
11317: # -------------------------------------------- Read plain texts for permissions
11318: {
1.448 albertel 11319: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11320:
11321: while (my $configline=<$config>) {
1.448 albertel 11322: chomp($configline);
11323: if ($configline) {
1.742 raeburn 11324: my ($short,@plain)=split(/:/,$configline);
11325: %{$prp{$short}} = ();
11326: if (@plain > 0) {
11327: $prp{$short}{'std'} = $plain[0];
11328: for (my $i=1; $i<@plain; $i++) {
11329: $prp{$short}{'alt'.$i} = $plain[$i];
11330: }
11331: }
1.448 albertel 11332: }
1.135 www 11333: }
1.448 albertel 11334: close($config);
1.135 www 11335: }
11336:
11337: # ---------------------------------------------------------- Read package table
11338: {
1.448 albertel 11339: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11340:
11341: while (my $configline=<$config>) {
1.483 albertel 11342: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11343: chomp($configline);
11344: my ($short,$plain)=split(/:/,$configline);
11345: my ($pack,$name)=split(/\&/,$short);
11346: if ($plain ne '') {
11347: $packagetab{$pack.'&'.$name.'&name'}=$name;
11348: $packagetab{$short}=$plain;
11349: }
1.11 www 11350: }
1.448 albertel 11351: close($config);
1.329 matthew 11352: }
11353:
1.1073 raeburn 11354: # ---------------------------------------------------------- Read loncaparev table
11355: {
11356: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11357: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11358: while (my $configline=<$config>) {
11359: chomp($configline);
11360: my ($hostid,$loncaparev)=split(/:/,$configline);
11361: $loncaparevs{$hostid}=$loncaparev;
11362: }
11363: close($config);
11364: }
11365: }
11366: }
11367:
1.1074 raeburn 11368: # ---------------------------------------------------------- Read serverhostID table
11369: {
11370: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11371: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11372: while (my $configline=<$config>) {
11373: chomp($configline);
11374: my ($name,$id)=split(/:/,$configline);
11375: $serverhomeIDs{$name}=$id;
11376: }
11377: close($config);
11378: }
11379: }
11380: }
11381:
1.1079 raeburn 11382: {
11383: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11384: if (-e $file) {
11385: my $parser = HTML::LCParser->new($file);
11386: while (my $token = $parser->get_token()) {
11387: if ($token->[0] eq 'S') {
11388: my $item = $token->[1];
11389: my $name = $token->[2]{'name'};
11390: my $value = $token->[2]{'value'};
11391: if ($item ne '' && $name ne '' && $value ne '') {
11392: my $release = $parser->get_text();
11393: $release =~ s/(^\s*|\s*$ )//gx;
11394: $needsrelease{$item.':'.$name.':'.$value} = $release;
11395: }
11396: }
11397: }
11398: }
1.1073 raeburn 11399: }
11400:
1.1138 raeburn 11401: # ---------------------------------------------------------- Read managers table
11402: {
11403: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11404: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11405: while (my $configline=<$config>) {
11406: chomp($configline);
11407: next if ($configline =~ /^\#/);
11408: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11409: $managerstab{$configline} = 1;
11410: }
11411: }
11412: close($config);
11413: }
11414: }
11415: }
11416:
1.329 matthew 11417: # ------------- set up temporary directory
11418: {
1.1117 foxr 11419: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11420:
1.11 www 11421: }
11422:
1.794 albertel 11423: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11424: 'compress_threshold'=> 20_000,
11425: });
1.185 www 11426:
1.281 www 11427: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11428: $dumpcount=0;
1.958 www 11429: $locknum=0;
1.22 www 11430:
1.163 harris41 11431: &logtouch();
1.672 albertel 11432: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11433: $readit=1;
1.564 albertel 11434: {
11435: use integer;
11436: my $test=(2**32)+1;
1.568 albertel 11437: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11438: &logthis(" Detected 64bit platform ($_64bit)");
11439: }
1.195 www 11440: }
1.1 albertel 11441: }
1.179 www 11442:
1.1 albertel 11443: 1;
1.191 harris41 11444: __END__
11445:
1.243 albertel 11446: =pod
11447:
1.191 harris41 11448: =head1 NAME
11449:
1.243 albertel 11450: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11451:
11452: =head1 SYNOPSIS
11453:
1.243 albertel 11454: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11455:
11456: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11457:
1.243 albertel 11458: Common parameters:
11459:
11460: =over 4
11461:
11462: =item *
11463:
11464: $uname : an internal username (if $cname expecting a course Id specifically)
11465:
11466: =item *
11467:
11468: $udom : a domain (if $cdom expecting a course's domain specifically)
11469:
11470: =item *
11471:
11472: $symb : a resource instance identifier
11473:
11474: =item *
11475:
11476: $namespace : the name of a .db file that contains the data needed or
11477: being set.
11478:
11479: =back
11480:
1.394 bowersj2 11481: =head1 OVERVIEW
1.191 harris41 11482:
1.394 bowersj2 11483: lonnet provides subroutines which interact with the
11484: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11485: about classes, users, and resources.
1.243 albertel 11486:
11487: For many of these objects you can also use this to store data about
11488: them or modify them in various ways.
1.191 harris41 11489:
1.394 bowersj2 11490: =head2 Symbs
1.191 harris41 11491:
1.394 bowersj2 11492: To identify a specific instance of a resource, LON-CAPA uses symbols
11493: or "symbs"X<symb>. These identifiers are built from the URL of the
11494: map, the resource number of the resource in the map, and the URL of
11495: the resource itself. The latter is somewhat redundant, but might help
11496: if maps change.
11497:
11498: An example is
11499:
11500: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11501:
11502: The respective map entry is
11503:
11504: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11505: title="Problem 2">
11506: </resource>
11507:
11508: Symbs are used by the random number generator, as well as to store and
11509: restore data specific to a certain instance of for example a problem.
11510:
11511: =head2 Storing And Retrieving Data
11512:
11513: X<store()>X<cstore()>X<restore()>Three of the most important functions
11514: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11515: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11516: is is the non-critical message twin of cstore. These functions are for
11517: handlers to store a perl hash to a user's permanent data space in an
11518: easy manner, and to retrieve it again on another call. It is expected
11519: that a handler would use this once at the beginning to retrieve data,
11520: and then again once at the end to send only the new data back.
11521:
11522: The data is stored in the user's data directory on the user's
11523: homeserver under the ID of the course.
11524:
11525: The hash that is returned by restore will have all of the previous
11526: value for all of the elements of the hash.
11527:
11528: Example:
11529:
11530: #creating a hash
11531: my %hash;
11532: $hash{'foo'}='bar';
11533:
11534: #storing it
11535: &Apache::lonnet::cstore(\%hash);
11536:
11537: #changing a value
11538: $hash{'foo'}='notbar';
11539:
11540: #adding a new value
11541: $hash{'bar'}='foo';
11542: &Apache::lonnet::cstore(\%hash);
11543:
11544: #retrieving the hash
11545: my %history=&Apache::lonnet::restore();
11546:
11547: #print the hash
11548: foreach my $key (sort(keys(%history))) {
11549: print("\%history{$key} = $history{$key}");
11550: }
11551:
11552: Will print out:
1.191 harris41 11553:
1.394 bowersj2 11554: %history{1:foo} = bar
11555: %history{1:keys} = foo:timestamp
11556: %history{1:timestamp} = 990455579
11557: %history{2:bar} = foo
11558: %history{2:foo} = notbar
11559: %history{2:keys} = foo:bar:timestamp
11560: %history{2:timestamp} = 990455580
11561: %history{bar} = foo
11562: %history{foo} = notbar
11563: %history{timestamp} = 990455580
11564: %history{version} = 2
11565:
11566: Note that the special hash entries C<keys>, C<version> and
11567: C<timestamp> were added to the hash. C<version> will be equal to the
11568: total number of versions of the data that have been stored. The
11569: C<timestamp> attribute will be the UNIX time the hash was
11570: stored. C<keys> is available in every historical section to list which
11571: keys were added or changed at a specific historical revision of a
11572: hash.
11573:
11574: B<Warning>: do not store the hash that restore returns directly. This
11575: will cause a mess since it will restore the historical keys as if the
11576: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11577:
1.394 bowersj2 11578: Calling convention:
1.191 harris41 11579:
1.394 bowersj2 11580: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11581: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11582:
1.394 bowersj2 11583: For more detailed information, see lonnet specific documentation.
1.191 harris41 11584:
1.394 bowersj2 11585: =head1 RETURN MESSAGES
1.191 harris41 11586:
1.394 bowersj2 11587: =over 4
1.191 harris41 11588:
1.394 bowersj2 11589: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11590:
1.394 bowersj2 11591: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11592: when the connection is brought back up
1.191 harris41 11593:
1.394 bowersj2 11594: =item * B<con_failed>: unable to contact remote host and unable to save message
11595: for later delivery
1.191 harris41 11596:
1.967 bisitz 11597: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11598:
1.394 bowersj2 11599: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11600: that was requested
1.191 harris41 11601:
1.243 albertel 11602: =back
1.191 harris41 11603:
1.243 albertel 11604: =head1 PUBLIC SUBROUTINES
1.191 harris41 11605:
1.243 albertel 11606: =head2 Session Environment Functions
1.191 harris41 11607:
1.243 albertel 11608: =over 4
1.191 harris41 11609:
1.394 bowersj2 11610: =item *
11611: X<appenv()>
1.949 raeburn 11612: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11613: the user envirnoment file, and will be restored for each access this
1.620 albertel 11614: user makes during this session, also modifies the %env for the current
1.949 raeburn 11615: process. Optional rolesarrayref - if defined contains a reference to an array
11616: of roles which are exempt from the restriction on modifying user.role entries
11617: in the user's environment.db and in %env.
1.191 harris41 11618:
11619: =item *
1.394 bowersj2 11620: X<delenv()>
1.987 raeburn 11621: B<delenv($delthis,$regexp)>: removes all items from the session
11622: environment file that begin with $delthis. If the
11623: optional second arg - $regexp - is true, $delthis is treated as a
11624: regular expression, otherwise \Q$delthis\E is used.
11625: The values are also deleted from the current processes %env.
1.191 harris41 11626:
1.795 albertel 11627: =item * get_env_multiple($name)
11628:
11629: gets $name from the %env hash, it seemlessly handles the cases where multiple
11630: values may be defined and end up as an array ref.
11631:
11632: returns an array of values
11633:
1.243 albertel 11634: =back
11635:
11636: =head2 User Information
1.191 harris41 11637:
1.243 albertel 11638: =over 4
1.191 harris41 11639:
11640: =item *
1.394 bowersj2 11641: X<queryauthenticate()>
11642: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11643: authentication scheme
11644:
11645: =item *
1.394 bowersj2 11646: X<authenticate()>
1.1073 raeburn 11647: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11648: authenticate user from domain's lib servers (first use the current
11649: one). C<$upass> should be the users password.
1.1073 raeburn 11650: $checkdefauth is optional (value is 1 if a check should be made to
11651: authenticate user using default authentication method, and allow
11652: account creation if username does not have account in the domain).
11653: $clientcancheckhost is optional (value is 1 if checking whether the
11654: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11655:
11656: =item *
1.394 bowersj2 11657: X<homeserver()>
11658: B<homeserver($uname,$udom)>: find the server which has
11659: the user's directory and files (there must be only one), this caches
11660: the answer, and also caches if there is a borken connection.
1.191 harris41 11661:
11662: =item *
1.394 bowersj2 11663: X<idget()>
11664: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11665: (IDs are a unique resource in a domain, there must be only 1 ID per
11666: username, and only 1 username per ID in a specific domain) (returns
11667: hash: id=>name,id=>name)
1.191 harris41 11668:
11669: =item *
1.394 bowersj2 11670: X<idrget()>
11671: B<idrget($udom,@unames)>: find the IDs behind a list of
11672: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11673:
11674: =item *
1.394 bowersj2 11675: X<idput()>
11676: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11677:
11678: =item *
1.394 bowersj2 11679: X<rolesinit()>
1.1169 droeschl 11680: B<rolesinit($udom,$username)>: get user privileges.
11681: returns user role, first access and timer interval hashes
1.243 albertel 11682:
11683: =item *
1.1171 droeschl 11684: X<privileged()>
11685: B<privileged($username,$domain)>: returns a true if user has a
11686: privileged and active role (i.e. su or dc), false otherwise.
11687:
11688: =item *
1.551 albertel 11689: X<getsection()>
11690: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11691: course $cname, return section name/number or '' for "not in course"
11692: and '-1' for "no section"
11693:
11694: =item *
1.394 bowersj2 11695: X<userenvironment()>
11696: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11697: passed in @what from the requested user's environment, returns a hash
11698:
1.858 raeburn 11699: =item *
11700: X<userlog_query()>
1.859 albertel 11701: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11702: activity.log file. %filters defines filters applied when parsing the
11703: log file. These can be start or end timestamps, or the type of action
11704: - log to look for Login or Logout events, check for Checkin or
11705: Checkout, role for role selection. The response is in the form
11706: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11707: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11708:
1.243 albertel 11709: =back
11710:
11711: =head2 User Roles
11712:
11713: =over 4
11714:
11715: =item *
11716:
1.810 raeburn 11717: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11718: F: full access
11719: U,I,K: authentication modes (cxx only)
11720: '': forbidden
11721: 1: user needs to choose course
11722: 2: browse allowed
1.766 albertel 11723: A: passphrase authentication needed
1.243 albertel 11724:
11725: =item *
11726:
11727: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11728: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11729: and course level
11730:
11731: =item *
11732:
1.988 raeburn 11733: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11734: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11735: $type is Course (default) or Community.
1.988 raeburn 11736: If $forcedefault evaluates to true, text returned will be default
11737: text for $type. Otherwise, if this is a course, the text returned
11738: will be a custom name for the role (if defined in the course's
11739: environment). If no custom name is defined the default is returned.
11740:
1.832 raeburn 11741: =item *
11742:
1.935 raeburn 11743: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11744: All arguments are optional. Returns a hash of a roles, either for
11745: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11746: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11747: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11748: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11749: For each key, value is set to colon-separated start and end times for
11750: the role. If no username and domain are specified, will default to
1.934 raeburn 11751: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11752: of role statuses (active, future or previous), roles
11753: (e.g., cc,in, st etc.) and domains of the roles which can be used
11754: to restrict the list of roles reported. If no array ref is
11755: provided for types, will default to return only active roles.
1.834 albertel 11756:
1.243 albertel 11757: =back
11758:
11759: =head2 User Modification
11760:
11761: =over 4
11762:
11763: =item *
11764:
1.957 raeburn 11765: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11766: user for the level given by URL. Optional start and end dates (leave empty
11767: string or zero for "no date")
1.191 harris41 11768:
11769: =item *
11770:
1.243 albertel 11771: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11772: change a users, password, possible return values are: ok,
11773: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11774: refused
1.191 harris41 11775:
11776: =item *
11777:
1.243 albertel 11778: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11779:
11780: =item *
11781:
1.1058 raeburn 11782: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11783: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11784:
11785: will update user information (firstname,middlename,lastname,generation,
11786: permanentemail), and if forceid is true, student/employee ID also.
11787: A user's institutional affiliation(s) can also be updated.
11788: User information fields will not be overwritten with empty entries
11789: unless the field is included in the $candelete array reference.
11790: This array is included when a single user is modified via "Manage Users",
11791: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11792:
11793: =item *
11794:
1.286 matthew 11795: modifystudent
11796:
1.957 raeburn 11797: modify a student's enrollment and identification information.
1.286 matthew 11798: The course id is resolved based on the current users environment.
11799: This means the envoking user must be a course coordinator or otherwise
11800: associated with a course.
11801:
1.297 matthew 11802: This call is essentially a wrapper for lonnet::modifyuser and
11803: lonnet::modify_student_enrollment
1.286 matthew 11804:
11805: Inputs:
11806:
11807: =over 4
11808:
1.957 raeburn 11809: =item B<$udom> Student's loncapa domain
1.286 matthew 11810:
1.957 raeburn 11811: =item B<$uname> Student's loncapa login name
1.286 matthew 11812:
1.964 bisitz 11813: =item B<$uid> Student/Employee ID
1.286 matthew 11814:
1.957 raeburn 11815: =item B<$umode> Student's authentication mode
1.286 matthew 11816:
1.957 raeburn 11817: =item B<$upass> Student's password
1.286 matthew 11818:
1.957 raeburn 11819: =item B<$first> Student's first name
1.286 matthew 11820:
1.957 raeburn 11821: =item B<$middle> Student's middle name
1.286 matthew 11822:
1.957 raeburn 11823: =item B<$last> Student's last name
1.286 matthew 11824:
1.957 raeburn 11825: =item B<$gene> Student's generation
1.286 matthew 11826:
1.957 raeburn 11827: =item B<$usec> Student's section in course
1.286 matthew 11828:
11829: =item B<$end> Unix time of the roles expiration
11830:
11831: =item B<$start> Unix time of the roles start date
11832:
11833: =item B<$forceid> If defined, allow $uid to be changed
11834:
11835: =item B<$desiredhome> server to use as home server for student
11836:
1.957 raeburn 11837: =item B<$email> Student's permanent e-mail address
11838:
11839: =item B<$type> Type of enrollment (auto or manual)
11840:
1.963 raeburn 11841: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11842:
11843: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11844:
1.963 raeburn 11845: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11846:
1.963 raeburn 11847: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11848:
1.963 raeburn 11849: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11850:
1.286 matthew 11851: =back
1.297 matthew 11852:
11853: =item *
11854:
11855: modify_student_enrollment
11856:
11857: Change a students enrollment status in a class. The environment variable
11858: 'role.request.course' must be defined for this function to proceed.
11859:
11860: Inputs:
11861:
11862: =over 4
11863:
11864: =item $udom, students domain
11865:
11866: =item $uname, students name
11867:
11868: =item $uid, students user id
11869:
11870: =item $first, students first name
11871:
11872: =item $middle
11873:
11874: =item $last
11875:
11876: =item $gene
11877:
11878: =item $usec
11879:
11880: =item $end
11881:
11882: =item $start
11883:
1.957 raeburn 11884: =item $type
11885:
11886: =item $locktype
11887:
11888: =item $cid
11889:
11890: =item $selfenroll
11891:
11892: =item $context
11893:
1.297 matthew 11894: =back
11895:
1.191 harris41 11896:
11897: =item *
11898:
1.243 albertel 11899: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11900: custom role; give a custom role to a user for the level given by URL. Specify
11901: name and domain of role author, and role name
1.191 harris41 11902:
11903: =item *
11904:
1.243 albertel 11905: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11906:
11907: =item *
11908:
1.243 albertel 11909: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11910:
11911: =back
11912:
11913: =head2 Course Infomation
11914:
11915: =over 4
1.191 harris41 11916:
11917: =item *
11918:
1.1118 foxr 11919: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11920: specified course id, including all environment settings for the
11921: course, the description of the course will be in the hash under the
11922: key 'description'
1.191 harris41 11923:
1.1118 foxr 11924: $options is an optional parameter that if supplied is a hash reference that controls
11925: what how this function works. It has the following key/values:
11926:
11927: =over 4
11928:
11929: =item freshen_cache
11930:
11931: If defined, and the environment cache for the course is valid, it is
11932: returned in the returned hash.
11933:
11934: =item one_time
11935:
11936: If defined, the last cache time is set to _now_
11937:
11938: =item user
11939:
11940: If defined, the supplied username is used instead of the current user.
11941:
11942:
11943: =back
11944:
1.191 harris41 11945: =item *
11946:
1.624 albertel 11947: resdata($name,$domain,$type,@which) : request for current parameter
11948: setting for a specific $type, where $type is either 'course' or 'user',
11949: @what should be a list of parameters to ask about. This routine caches
11950: answers for 5 minutes.
1.243 albertel 11951:
1.877 foxr 11952: =item *
11953:
11954: get_courseresdata($courseid, $domain) : dump the entire course resource
11955: data base, returning a hash that is keyed by the resource name and has
11956: values that are the resource value. I believe that the timestamps and
11957: versions are also returned.
11958:
11959:
1.243 albertel 11960: =back
11961:
11962: =head2 Course Modification
11963:
11964: =over 4
1.191 harris41 11965:
11966: =item *
11967:
1.243 albertel 11968: writecoursepref($courseid,%prefs) : write preferences (environment
11969: database) for a course
1.191 harris41 11970:
11971: =item *
11972:
1.1011 raeburn 11973: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11974:
11975: =item *
11976:
1.1038 raeburn 11977: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11978:
1.1167 droeschl 11979: =item *
11980:
11981: is_course($courseid), is_course($cdom, $cnum)
11982:
11983: Accepts either a combined $courseid (in the form of domain_courseid) or the
11984: two component version $cdom, $cnum. It checks if the specified course exists.
11985:
11986: Returns:
11987: undef if the course doesn't exist, otherwise
11988: in scalar context the combined courseid.
11989: in list context the two components of the course identifier, domain and
11990: courseid.
11991:
1.243 albertel 11992: =back
11993:
11994: =head2 Resource Subroutines
11995:
11996: =over 4
1.191 harris41 11997:
11998: =item *
11999:
1.243 albertel 12000: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12001:
12002: =item *
12003:
1.243 albertel 12004: repcopy($filename) : subscribes to the requested file, and attempts to
12005: replicate from the owning library server, Might return
1.607 raeburn 12006: 'unavailable', 'not_found', 'forbidden', 'ok', or
12007: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12008: resource. Expects the local filesystem pathname
12009: (/home/httpd/html/res/....)
12010:
12011: =back
12012:
12013: =head2 Resource Information
12014:
12015: =over 4
1.191 harris41 12016:
12017: =item *
12018:
1.243 albertel 12019: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12020: a vairety of different possible values, $varname should be a request
12021: string, and the other parameters can be used to specify who and what
12022: one is asking about.
12023:
12024: Possible values for $varname are environment.lastname (or other item
12025: from the envirnment hash), user.name (or someother aspect about the
12026: user), resource.0.maxtries (or some other part and parameter of a
12027: resource)
1.204 albertel 12028:
12029: =item *
12030:
1.243 albertel 12031: directcondval($number) : get current value of a condition; reads from a state
12032: string
1.204 albertel 12033:
12034: =item *
12035:
1.243 albertel 12036: condval($condidx) : value of condition index based on state
1.204 albertel 12037:
12038: =item *
12039:
1.243 albertel 12040: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12041: resource's metadata, $what should be either a specific key, or either
12042: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12043: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12044:
12045: this function automatically caches all requests
1.191 harris41 12046:
12047: =item *
12048:
1.243 albertel 12049: metadata_query($query,$custom,$customshow) : make a metadata query against the
12050: network of library servers; returns file handle of where SQL and regex results
12051: will be stored for query
1.191 harris41 12052:
12053: =item *
12054:
1.243 albertel 12055: symbread($filename) : return symbolic list entry (filename argument optional);
12056: returns the data handle
1.191 harris41 12057:
12058: =item *
12059:
1.243 albertel 12060: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12061: a possible symb for the URL in $thisfn, and if is an encryypted
12062: resource that the user accessed using /enc/ returns a 1 on success, 0
12063: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12064: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12065:
1.191 harris41 12066:
12067: =item *
12068:
1.243 albertel 12069: symbclean($symb) : removes versions numbers from a symb, returns the
12070: cleaned symb
1.191 harris41 12071:
12072: =item *
12073:
1.243 albertel 12074: is_on_map($uri) : checks if the $uri is somewhere on the current
12075: course map, user must be in a course for it to work.
1.191 harris41 12076:
12077: =item *
12078:
1.243 albertel 12079: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12080:
12081: =item *
12082:
1.243 albertel 12083: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12084: a random seed, all arguments are optional, if they aren't sent it uses the
12085: environment to derive them. Note: if symb isn't sent and it can't get one
12086: from &symbread it will use the current time as its return value
1.191 harris41 12087:
12088: =item *
12089:
1.243 albertel 12090: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12091: unfakeable, receipt
1.191 harris41 12092:
12093: =item *
12094:
1.620 albertel 12095: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12096:
12097: =item *
12098:
1.243 albertel 12099: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12100:
12101: =item *
12102:
1.243 albertel 12103: 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 12104:
12105: =item *
12106:
1.243 albertel 12107: 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 12108:
12109: =item *
12110:
1.243 albertel 12111: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12112:
12113: =item *
12114:
1.243 albertel 12115: devalidate($symb) : devalidate temporary spreadsheet calculations,
12116: forcing spreadsheet to reevaluate the resource scores next time.
12117:
12118: =back
12119:
12120: =head2 Storing/Retreiving Data
12121:
12122: =over 4
1.191 harris41 12123:
12124: =item *
12125:
1.243 albertel 12126: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12127: for this url; hashref needs to be given and should be a \%hashname; the
12128: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12129: be derived from the env
1.191 harris41 12130:
12131: =item *
12132:
1.243 albertel 12133: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12134: uses critical subroutine
1.191 harris41 12135:
12136: =item *
12137:
1.243 albertel 12138: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12139: all args are optional
1.191 harris41 12140:
12141: =item *
12142:
1.717 albertel 12143: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12144: dumps the complete (or key matching regexp) namespace into a hash
12145: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12146: normally &store()ed into
12147:
12148: $range should be either an integer '100' (give me the first 100
12149: matching records)
12150: or be two integers sperated by a - with no spaces
12151: '30-50' (give me the 30th through the 50th matching
12152: records)
12153:
12154:
12155: =item *
12156:
12157: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12158: replaces a &store() version of data with a replacement set of data
12159: for a particular resource in a namespace passed in the $storehash hash
12160: reference
12161:
12162: =item *
12163:
1.243 albertel 12164: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12165: works very similar to store/cstore, but all data is stored in a
12166: temporary location and can be reset using tmpreset, $storehash should
12167: be a hash reference, returns nothing on success
1.191 harris41 12168:
12169: =item *
12170:
1.243 albertel 12171: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12172: similar to restore, but all data is stored in a temporary location and
12173: can be reset using tmpreset. Returns a hash of values on success,
12174: error string otherwise.
1.191 harris41 12175:
12176: =item *
12177:
1.243 albertel 12178: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12179: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12180:
12181: =item *
12182:
1.243 albertel 12183: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12184: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12185:
12186: =item *
12187:
1.243 albertel 12188: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12189: namesp ($udom and $uname are optional)
1.191 harris41 12190:
12191: =item *
12192:
1.702 albertel 12193: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12194: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12195: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12196:
1.702 albertel 12197: $range should be either an integer '100' (give me the first 100
12198: matching records)
12199: or be two integers sperated by a - with no spaces
12200: '30-50' (give me the 30th through the 50th matching
12201: records)
1.449 matthew 12202: =item *
12203:
12204: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12205: $store can be a scalar, an array reference, or if the amount to be
12206: incremented is > 1, a hash reference.
12207:
12208: ($udom and $uname are optional)
1.191 harris41 12209:
12210: =item *
12211:
1.243 albertel 12212: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12213: ($udom and $uname are optional)
1.191 harris41 12214:
12215: =item *
12216:
1.243 albertel 12217: cput($namespace,$storehash,$udom,$uname) : critical put
12218: ($udom and $uname are optional)
1.191 harris41 12219:
12220: =item *
12221:
1.748 albertel 12222: newput($namespace,$storehash,$udom,$uname) :
12223:
12224: Attempts to store the items in the $storehash, but only if they don't
12225: currently exist, if this succeeds you can be certain that you have
12226: successfully created a new key value pair in the $namespace db.
12227:
12228:
12229: Args:
12230: $namespace: name of database to store values to
12231: $storehash: hashref to store to the db
12232: $udom: (optional) domain of user containing the db
12233: $uname: (optional) name of user caontaining the db
12234:
12235: Returns:
12236: 'ok' -> succeeded in storing all keys of $storehash
12237: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12238: least <key> already existed in the db (other
12239: requested keys may also already exist)
1.967 bisitz 12240: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12241: 'con_lost' -> unable to contact request server
12242: 'refused' -> action was not allowed by remote machine
12243:
12244:
12245: =item *
12246:
1.243 albertel 12247: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12248: reference filled in from namesp (encrypts the return communication)
12249: ($udom and $uname are optional)
1.191 harris41 12250:
12251: =item *
12252:
1.243 albertel 12253: log($udom,$name,$home,$message) : write to permanent log for user; use
12254: critical subroutine
12255:
1.806 raeburn 12256: =item *
12257:
1.860 raeburn 12258: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12259: array reference filled in from namespace found in domain level on either
12260: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12261:
12262: =item *
12263:
1.860 raeburn 12264: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12265: domain level either on specified domain server ($uhome) or primary domain
12266: server ($udom and $uhome are optional)
1.806 raeburn 12267:
1.943 raeburn 12268: =item *
12269:
12270: get_domain_defaults($target_domain) : returns hash with defaults for
12271: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12272: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12273: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12274: Values are retrieved from cache (if current), or from domain's configuration.db
12275: (if available), or lastly from values in lonTabs/dns_domain,tab,
12276: or lonTabs/domain.tab.
12277:
12278: %domdefaults = &get_auth_defaults($target_domain);
12279:
1.243 albertel 12280: =back
12281:
12282: =head2 Network Status Functions
12283:
12284: =over 4
1.191 harris41 12285:
12286: =item *
12287:
1.1137 raeburn 12288: dirlist() : return directory list based on URI (first arg).
12289:
12290: Inputs: 1 required, 5 optional.
12291:
12292: =over
12293:
12294: =item
12295: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12296:
12297: =item
12298: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12299:
12300: =item
12301: $username - username of user/course to be listed. Extracted from $uri if absent.
12302:
12303: =item
12304: $getpropath - boolean: 1 if prepend path using &propath().
12305:
12306: =item
12307: $getuserdir - boolean: 1 if prepend path for "userfiles".
12308:
12309: =item
12310: $alternateRoot - path to prepend in place of path from $uri.
12311:
12312: =back
12313:
12314: Returns: Array of up to two items.
12315:
12316: =over
12317:
12318: a reference to an array of files/subdirectories
12319:
12320: =over
12321:
12322: Each element in the array of files/subdirectories is a & separated list of
12323: item name and the result of running stat on the item. If dirlist was requested
12324: for a file instead of a directory, the item name will be ''. For a directory
12325: listing, if the item is a metadata file, the element will end &N&M
12326: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12327: default copyright set (1).
12328:
12329: =back
12330:
12331: a scalar containing error condition (if encountered).
12332:
12333: =over
12334:
12335: =item
12336: no_host (no homeserver identified for $username:$domain).
12337:
12338: =item
12339: no_such_host (server contacted for listing not identified as valid host).
12340:
12341: =item
12342: con_lost (connection to remote server failed).
12343:
12344: =item
12345: refused (invalid $username:$domain received on lond side).
12346:
12347: =item
12348: no_such_dir (directory at specified path on lond side does not exist).
12349:
12350: =item
12351: empty (directory at specified path on lond side is empty).
12352:
12353: =over
12354:
12355: This is currently not encountered because the &ls3, &ls2,
12356: &ls (_handler) routines on the lond side do not filter out
12357: . and .. from a directory listing.
12358:
12359: =back
12360:
12361: =back
12362:
12363: =back
1.191 harris41 12364:
12365: =item *
12366:
1.243 albertel 12367: spareserver() : find server with least workload from spare.tab
12368:
1.986 foxr 12369:
12370: =item *
12371:
12372: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12373: if there is no corresponding loncapa host.
12374:
1.243 albertel 12375: =back
12376:
1.986 foxr 12377:
1.243 albertel 12378: =head2 Apache Request
12379:
12380: =over 4
1.191 harris41 12381:
12382: =item *
12383:
1.243 albertel 12384: ssi($url,%hash) : server side include, does a complete request cycle on url to
12385: localhost, posts hash
12386:
12387: =back
12388:
12389: =head2 Data to String to Data
12390:
12391: =over 4
1.191 harris41 12392:
12393: =item *
12394:
1.243 albertel 12395: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12396: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12397:
12398: =item *
12399:
1.243 albertel 12400: hashref2str($hashref) : convert a hashref into a string complete with
12401: escaping and '=' and '&' separators, supports elements that are
12402: arrayrefs and hashrefs
1.191 harris41 12403:
12404: =item *
12405:
1.243 albertel 12406: arrayref2str($arrayref) : convert an arrayref into a string complete
12407: with escaping and '&' separators, supports elements that are arrayrefs
12408: and hashrefs
1.191 harris41 12409:
12410: =item *
12411:
1.243 albertel 12412: str2hash($string) : convert string to hash using unescaping and
12413: splitting on '=' and '&', supports elements that are arrayrefs and
12414: hashrefs
1.191 harris41 12415:
12416: =item *
12417:
1.243 albertel 12418: str2array($string) : convert string to hash using unescaping and
12419: splitting on '&', supports elements that are arrayrefs and hashrefs
12420:
12421: =back
12422:
12423: =head2 Logging Routines
12424:
12425:
12426: These routines allow one to make log messages in the lonnet.log and
12427: lonnet.perm logfiles.
1.191 harris41 12428:
1.1119 foxr 12429: =over 4
12430:
1.191 harris41 12431: =item *
12432:
1.243 albertel 12433: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12434:
12435: =item *
12436:
1.243 albertel 12437: logthis() : append message to the normal lonnet.log file, it gets
12438: preiodically rolled over and deleted.
1.191 harris41 12439:
12440: =item *
12441:
1.243 albertel 12442: logperm() : append a permanent message to lonnet.perm.log, this log
12443: file never gets deleted by any automated portion of the system, only
12444: messages of critical importance should go in here.
12445:
1.1119 foxr 12446:
1.243 albertel 12447: =back
12448:
12449: =head2 General File Helper Routines
12450:
12451: =over 4
1.191 harris41 12452:
12453: =item *
12454:
1.481 raeburn 12455: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12456: (a) files in /uploaded
12457: (i) If a local copy of the file exists -
12458: compares modification date of local copy with last-modified date for
12459: definitive version stored on home server for course. If local copy is
12460: stale, requests a new version from the home server and stores it.
12461: If the original has been removed from the home server, then local copy
12462: is unlinked.
12463: (ii) If local copy does not exist -
12464: requests the file from the home server and stores it.
12465:
12466: If $caller is 'uploadrep':
12467: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12468: for request for files originally uploaded via DOCS.
12469: - returns 'ok' if fresh local copy now available, -1 otherwise.
12470:
12471: Otherwise:
12472: This indicates a call from the content generation phase of the request.
12473: - returns the entire contents of the file or -1.
12474:
12475: (b) files in /res
12476: - returns the entire contents of a file or -1;
12477: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12478:
1.712 albertel 12479:
12480: =item *
12481:
12482: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12483: reference
12484:
12485: returns either a stat() list of data about the file or an empty list
12486: if the file doesn't exist or couldn't find out about it (connection
12487: problems or user unknown)
12488:
1.191 harris41 12489: =item *
12490:
1.243 albertel 12491: filelocation($dir,$file) : returns file system location of a file
12492: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12493: directory that relative $file lookups are to looked in ($dir of /a/dir
12494: and a file of ../bob will become /a/bob)
1.191 harris41 12495:
12496: =item *
12497:
12498: hreflocation($dir,$file) : returns file system location or a URL; same as
12499: filelocation except for hrefs
12500:
12501: =item *
12502:
12503: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12504:
1.243 albertel 12505: =back
12506:
1.608 albertel 12507: =head2 Usererfile file routines (/uploaded*)
12508:
12509: =over 4
12510:
12511: =item *
12512:
12513: userfileupload(): main rotine for putting a file in a user or course's
12514: filespace, arguments are,
12515:
1.620 albertel 12516: formname - required - this is the name of the element in $env where the
1.608 albertel 12517: filename, and the contents of the file to create/modifed exist
1.620 albertel 12518: the filename is in $env{'form.'.$formname.'.filename'} and the
12519: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12520: context - if coursedoc, store the file in the course of the active role
12521: of the current user;
12522: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12523: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12524: subdir - required - subdirectory to put the file in under ../userfiles/
12525: if undefined, it will be placed in "unknown"
12526:
12527: (This routine calls clean_filename() to remove any dangerous
12528: characters from the filename, and then calls finuserfileupload() to
12529: complete the transaction)
12530:
12531: returns either the url of the uploaded file (/uploaded/....) if successful
12532: and /adm/notfound.html if unsuccessful
12533:
12534: =item *
12535:
12536: clean_filename(): routine for cleaing a filename up for storage in
12537: userfile space, argument is:
12538:
12539: filename - proposed filename
12540:
12541: returns: the new clean filename
12542:
12543: =item *
12544:
1.1090 raeburn 12545: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12546: userspace, probably shouldn't be called directly
12547:
12548: docuname: username or courseid of destination for the file
12549: docudom: domain of user/course of destination for the file
12550: formname: same as for userfileupload()
1.1090 raeburn 12551: fname: filename (including subdirectories) for the file
12552: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12553: allfiles: reference to hash used to store objects found by parser
12554: codebase: reference to hash used for codebases of java objects found by parser
12555: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12556: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12557: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12558: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12559: context: if 'overwrite', will move the uploaded file from its temporary location to
12560: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12561: mimetype: reference to scalar to accommodate mime type determined
12562: from File::MMagic if $parser = parse.
1.608 albertel 12563:
12564: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12565: and /adm/notfound.html if unsuccessful (or an error message if context
12566: was 'overwrite').
12567:
1.608 albertel 12568:
12569: =item *
12570:
12571: renameuserfile(): renames an existing userfile to a new name
12572:
12573: Args:
12574: docuname: username or courseid of destination for the file
12575: docudom: domain of user/course of destination for the file
12576: old: current file name (including any subdirs under userfiles)
12577: new: desired file name (including any subdirs under userfiles)
12578:
12579: =item *
12580:
12581: mkdiruserfile(): creates a directory is a userfiles dir
12582:
12583: Args:
12584: docuname: username or courseid of destination for the file
12585: docudom: domain of user/course of destination for the file
12586: dir: dir to create (including any subdirs under userfiles)
12587:
12588: =item *
12589:
12590: removeuserfile(): removes a file that exists in userfiles
12591:
12592: Args:
12593: docuname: username or courseid of destination for the file
12594: docudom: domain of user/course of destination for the file
12595: fname: filname to delete (including any subdirs under userfiles)
12596:
12597: =item *
12598:
12599: removeuploadedurl(): convience function for removeuserfile()
12600:
12601: Args:
12602: url: a full /uploaded/... url to delete
12603:
1.747 albertel 12604: =item *
12605:
12606: get_portfile_permissions():
12607: Args:
12608: domain: domain of user or course contain the portfolio files
12609: user: name of user or num of course contain the portfolio files
12610: Returns:
12611: hashref of a dump of the proper file_permissions.db
12612:
12613:
12614: =item *
12615:
12616: get_access_controls():
12617:
12618: Args:
12619: current_permissions: the hash ref returned from get_portfile_permissions()
12620: group: (optional) the group you want the files associated with
12621: file: (optional) the file you want access info on
12622:
12623: Returns:
1.749 raeburn 12624: a hash (keys are file names) of hashes containing
12625: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12626: values are XML containing access control settings (see below)
1.747 albertel 12627:
12628: Internal notes:
12629:
1.749 raeburn 12630: access controls are stored in file_permissions.db as key=value pairs.
12631: key -> path to file/file_name\0uniqueID:scope_end_start
12632: where scope -> public,guest,course,group,domains or users.
12633: end -> UNIX time for end of access (0 -> no end date)
12634: start -> UNIX time for start of access
12635:
12636: value -> XML description of access control
12637: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12638: <start></start>
12639: <end></end>
12640:
12641: <password></password> for scope type = guest
12642:
12643: <domain></domain> for scope type = course or group
12644: <number></number>
12645: <roles id="">
12646: <role></role>
12647: <access></access>
12648: <section></section>
12649: <group></group>
12650: </roles>
12651:
12652: <dom></dom> for scope type = domains
12653:
12654: <users> for scope type = users
12655: <user>
12656: <uname></uname>
12657: <udom></udom>
12658: </user>
12659: </users>
12660: </scope>
12661:
12662: Access data is also aggregated for each file in an additional key=value pair:
12663: key -> path to file/file_name\0accesscontrol
12664: value -> reference to hash
12665: hash contains key = value pairs
12666: where key = uniqueID:scope_end_start
12667: value = UNIX time record was last updated
12668:
12669: Used to improve speed of look-ups of access controls for each file.
12670:
12671: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12672:
12673: modify_access_controls():
12674:
12675: Modifies access controls for a portfolio file
12676: Args
12677: 1. file name
12678: 2. reference to hash of required changes,
12679: 3. domain
12680: 4. username
12681: where domain,username are the domain of the portfolio owner
12682: (either a user or a course)
12683:
12684: Returns:
12685: 1. result of additions or updates ('ok' or 'error', with error message).
12686: 2. result of deletions ('ok' or 'error', with error message).
12687: 3. reference to hash of any new or updated access controls.
12688: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12689: key = integer (inbound ID)
12690: value = uniqueID
1.747 albertel 12691:
1.608 albertel 12692: =back
12693:
1.243 albertel 12694: =head2 HTTP Helper Routines
12695:
12696: =over 4
12697:
1.191 harris41 12698: =item *
12699:
12700: escape() : unpack non-word characters into CGI-compatible hex codes
12701:
12702: =item *
12703:
12704: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12705:
1.243 albertel 12706: =back
12707:
12708: =head1 PRIVATE SUBROUTINES
12709:
12710: =head2 Underlying communication routines (Shouldn't call)
12711:
12712: =over 4
12713:
12714: =item *
12715:
12716: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12717:
12718: =item *
12719:
12720: reply() : uses subreply to send a message to remote machine, logs all failures
12721:
12722: =item *
12723:
12724: critical() : passes a critical message to another server; if cannot
12725: get through then place message in connection buffer directory and
12726: returns con_delayed, if incapable of saving message, returns
12727: con_failed
12728:
12729: =item *
12730:
12731: reconlonc() : tries to reconnect lonc client processes.
12732:
12733: =back
12734:
12735: =head2 Resource Access Logging
12736:
12737: =over 4
12738:
12739: =item *
12740:
12741: flushcourselogs() : flush (save) buffer logs and access logs
12742:
12743: =item *
12744:
12745: courselog($what) : save message for course in hash
12746:
12747: =item *
12748:
12749: courseacclog($what) : save message for course using &courselog(). Perform
12750: special processing for specific resource types (problems, exams, quizzes, etc).
12751:
1.191 harris41 12752: =item *
12753:
12754: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12755: as a PerlChildExitHandler
1.243 albertel 12756:
12757: =back
12758:
12759: =head2 Other
12760:
12761: =over 4
12762:
12763: =item *
12764:
12765: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12766:
12767: =back
12768:
12769: =cut
1.877 foxr 12770:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>