Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1076
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1076 ! raeburn 4: # $Id: lonnet.pm,v 1.1075 2010/07/23 14:59:24 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1074 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
1.1073 raeburn 199: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
1.1073 raeburn 214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: }
220: }
221: my ($answer,$loncaparev);
222: my @ids=¤t_machine_ids();
223: if (grep(/^\Q$lonhost\E$/,@ids)) {
224: $answer = $perlvar{'lonVersion'};
225: if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
226: $loncaparev = $1;
227: }
228: } else {
229: $answer = &reply('serverloncaparev',$lonhost);
230: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
231: if ($caller eq 'loncron') {
232: my $ua=new LWP::UserAgent;
233: $ua->timeout(20);
234: my $protocol = $protocol{$lonhost};
235: $protocol = 'http' if ($protocol ne 'https');
236: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
237: my $request=new HTTP::Request('GET',$url);
238: my $response=$ua->request($request);
239: unless ($response->is_error()) {
240: my $content = $response->content;
241: if ($content =~ /<p>VERSION\:\s*([\d.\-]+)<\/p>/) {
242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
248: } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
249: $loncaparev = $1;
250: }
1.993 raeburn 251: }
1.1073 raeburn 252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 253: }
254: }
255:
1.1074 raeburn 256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
260: if (defined($cached)) {
261: return $serverhomeID;
262: }
263: }
264: my $cachetime = 12*3600;
265: my $serverhomeID;
266: if ($caller eq 'loncron') {
267: my @machine_ids = &machine_ids($hostname);
268: foreach my $id (@machine_ids) {
269: my $response = &reply('serverhomeID',$id);
270: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
271: $serverhomeID = $response;
272: last;
273: }
274: }
275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
280: }
281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
282: }
283:
1.1 albertel 284: # -------------------------------------------------- Non-critical communication
285: sub subreply {
286: my ($cmd,$server)=@_;
1.838 albertel 287: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 288: #
289: # With loncnew process trimming, there's a timing hole between lonc server
290: # process exit and the master server picking up the listen on the AF_UNIX
291: # socket. In that time interval, a lock file will exist:
292:
293: my $lockfile=$peerfile.".lock";
294: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
295: sleep(1);
296: }
297: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 298: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 299: #
1.550 foxr 300: # We'll give the connection a few tries before abandoning it. If
301: # connection is not possible, we'll con_lost back to the client.
302: #
303: my $client;
304: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
305: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
306: Type => SOCK_STREAM,
307: Timeout => 10);
1.869 albertel 308: if ($client) {
1.550 foxr 309: last; # Connected!
1.850 albertel 310: } else {
1.853 albertel 311: &create_connection(&hostname($server),$server);
1.550 foxr 312: }
1.850 albertel 313: sleep(1); # Try again later if failed connection.
1.550 foxr 314: }
315: my $answer;
316: if ($client) {
1.704 albertel 317: print $client "sethost:$server:$cmd\n";
1.550 foxr 318: $answer=<$client>;
319: if (!$answer) { $answer="con_lost"; }
320: chomp($answer);
321: } else {
322: $answer = 'con_lost'; # Failed connection.
323: }
1.1 albertel 324: return $answer;
325: }
326:
327: sub reply {
328: my ($cmd,$server)=@_;
1.838 albertel 329: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 330: my $answer=subreply($cmd,$server);
1.65 www 331: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 332: &logthis("<font color=\"blue\">WARNING:".
1.12 www 333: " $cmd to $server returned $answer</font>");
334: }
1.1 albertel 335: return $answer;
336: }
337:
338: # ----------------------------------------------------------- Send USR1 to lonc
339:
340: sub reconlonc {
1.891 albertel 341: my ($lonid) = @_;
342: my $hostname = &hostname($lonid);
343: if ($lonid) {
344: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
345: if ($hostname && -e $peerfile) {
346: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
347: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
348: Type => SOCK_STREAM,
349: Timeout => 10);
350: if ($client) {
351: print $client ("reset_retries\n");
352: my $answer=<$client>;
353: #reset just this one.
354: }
355: }
356: return;
357: }
358:
1.836 www 359: &logthis("Trying to reconnect lonc");
1.1 albertel 360: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 361: if (open(my $fh,"<$loncfile")) {
1.1 albertel 362: my $loncpid=<$fh>;
363: chomp($loncpid);
364: if (kill 0 => $loncpid) {
365: &logthis("lonc at pid $loncpid responding, sending USR1");
366: kill USR1 => $loncpid;
367: sleep 1;
1.836 www 368: } else {
1.12 www 369: &logthis(
1.672 albertel 370: "<font color=\"blue\">WARNING:".
1.12 www 371: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 372: }
373: } else {
1.836 www 374: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 375: }
376: }
377:
378: # ------------------------------------------------------ Critical communication
1.12 www 379:
1.1 albertel 380: sub critical {
381: my ($cmd,$server)=@_;
1.838 albertel 382: unless (&hostname($server)) {
1.672 albertel 383: &logthis("<font color=\"blue\">WARNING:".
1.89 www 384: " Critical message to unknown server ($server)</font>");
385: return 'no_such_host';
386: }
1.1 albertel 387: my $answer=reply($cmd,$server);
388: if ($answer eq 'con_lost') {
389: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 390: my $answer=reply($cmd,$server);
1.1 albertel 391: if ($answer eq 'con_lost') {
392: my $now=time;
393: my $middlename=$cmd;
1.5 www 394: $middlename=substr($middlename,0,16);
1.1 albertel 395: $middlename=~s/\W//g;
396: my $dfilename=
1.305 www 397: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
398: $dumpcount++;
1.1 albertel 399: {
1.448 albertel 400: my $dfh;
401: if (open($dfh,">$dfilename")) {
402: print $dfh "$cmd\n";
403: close($dfh);
404: }
1.1 albertel 405: }
406: sleep 2;
407: my $wcmd='';
408: {
1.448 albertel 409: my $dfh;
410: if (open($dfh,"<$dfilename")) {
411: $wcmd=<$dfh>;
412: close($dfh);
413: }
1.1 albertel 414: }
415: chomp($wcmd);
1.7 www 416: if ($wcmd eq $cmd) {
1.672 albertel 417: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 418: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 419: &logperm("D:$server:$cmd");
420: return 'con_delayed';
421: } else {
1.672 albertel 422: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 423: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 424: &logperm("F:$server:$cmd");
425: return 'con_failed';
426: }
427: }
428: }
429: return $answer;
1.405 albertel 430: }
431:
1.755 albertel 432: # ------------------------------------------- check if return value is an error
433:
434: sub error {
435: my ($result) = @_;
1.756 albertel 436: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 437: if ($2 == 2) { return undef; }
438: return $1;
439: }
440: return undef;
441: }
442:
1.783 albertel 443: sub convert_and_load_session_env {
444: my ($lonidsdir,$handle)=@_;
445: my @profile;
446: {
1.917 albertel 447: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
448: if (!$opened) {
1.915 albertel 449: return 0;
450: }
1.783 albertel 451: flock($idf,LOCK_SH);
452: @profile=<$idf>;
453: close($idf);
454: }
455: my %temp_env;
456: foreach my $line (@profile) {
1.786 albertel 457: if ($line !~ m/=/) {
458: return 0;
459: }
1.783 albertel 460: chomp($line);
461: my ($envname,$envvalue)=split(/=/,$line,2);
462: $temp_env{&unescape($envname)} = &unescape($envvalue);
463: }
464: unlink("$lonidsdir/$handle.id");
465: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
466: 0640)) {
467: %disk_env = %temp_env;
468: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
469: untie(%disk_env);
470: }
1.786 albertel 471: return 1;
1.783 albertel 472: }
473:
1.374 www 474: # ------------------------------------------- Transfer profile into environment
1.780 albertel 475: my $env_loaded;
476: sub transfer_profile_to_env {
1.788 albertel 477: my ($lonidsdir,$handle,$force_transfer) = @_;
478: if (!$force_transfer && $env_loaded) { return; }
1.374 www 479:
1.720 albertel 480: if (!defined($lonidsdir)) {
481: $lonidsdir = $perlvar{'lonIDsDir'};
482: }
483: if (!defined($handle)) {
484: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
485: }
486:
1.786 albertel 487: my $convert;
488: {
1.917 albertel 489: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
490: if (!$opened) {
1.915 albertel 491: return;
492: }
1.786 albertel 493: flock($idf,LOCK_SH);
494: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
495: &GDBM_READER(),0640)) {
496: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
497: untie(%disk_env);
498: } else {
499: $convert = 1;
500: }
501: }
502: if ($convert) {
503: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
504: &logthis("Failed to load session, or convert session.");
505: }
1.374 www 506: }
1.783 albertel 507:
1.786 albertel 508: my %remove;
1.783 albertel 509: while ( my $envname = each(%env) ) {
1.433 matthew 510: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
511: if ($time < time-300) {
1.783 albertel 512: $remove{$key}++;
1.433 matthew 513: }
514: }
515: }
1.783 albertel 516:
1.619 albertel 517: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 518: $env_loaded=1;
1.783 albertel 519: foreach my $expired_key (keys(%remove)) {
1.433 matthew 520: &delenv($expired_key);
1.374 www 521: }
1.1 albertel 522: }
523:
1.916 albertel 524: # ---------------------------------------------------- Check for valid session
525: sub check_for_valid_session {
526: my ($r) = @_;
527: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
528: my $lonid=$cookies{'lonID'};
529: return undef if (!$lonid);
530:
531: my $handle=&LONCAPA::clean_handle($lonid->value);
532: my $lonidsdir=$r->dir_config('lonIDsDir');
533: return undef if (!-e "$lonidsdir/$handle.id");
534:
1.917 albertel 535: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
536: return undef if (!$opened);
1.916 albertel 537:
538: flock($idf,LOCK_SH);
539: my %disk_env;
540: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
541: &GDBM_READER(),0640)) {
542: return undef;
543: }
544:
545: if (!defined($disk_env{'user.name'})
546: || !defined($disk_env{'user.domain'})) {
547: return undef;
548: }
549: return $handle;
550: }
551:
1.830 albertel 552: sub timed_flock {
553: my ($file,$lock_type) = @_;
554: my $failed=0;
555: eval {
556: local $SIG{__DIE__}='DEFAULT';
557: local $SIG{ALRM}=sub {
558: $failed=1;
559: die("failed lock");
560: };
561: alarm(13);
562: flock($file,$lock_type);
563: alarm(0);
564: };
565: if ($failed) {
566: return undef;
567: } else {
568: return 1;
569: }
570: }
571:
1.5 www 572: # ---------------------------------------------------------- Append Environment
573:
574: sub appenv {
1.949 raeburn 575: my ($newenv,$roles) = @_;
576: if (ref($newenv) eq 'HASH') {
577: foreach my $key (keys(%{$newenv})) {
578: my $refused = 0;
579: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
580: $refused = 1;
581: if (ref($roles) eq 'ARRAY') {
582: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
583: if (grep(/^\Q$role\E$/,@{$roles})) {
584: $refused = 0;
585: }
586: }
587: }
588: if ($refused) {
589: &logthis("<font color=\"blue\">WARNING: ".
590: "Attempt to modify environment ".$key." to ".$newenv->{$key}
591: .'</font>');
592: delete($newenv->{$key});
593: } else {
594: $env{$key}=$newenv->{$key};
595: }
596: }
597: my $opened = open(my $env_file,'+<',$env{'user.environment'});
598: if ($opened
599: && &timed_flock($env_file,LOCK_EX)
600: &&
601: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
602: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
603: while (my ($key,$value) = each(%{$newenv})) {
604: $disk_env{$key} = $value;
605: }
606: untie(%disk_env);
1.35 www 607: }
1.191 harris41 608: }
1.56 www 609: return 'ok';
610: }
611: # ----------------------------------------------------- Delete from Environment
612:
613: sub delenv {
1.987 raeburn 614: my ($delthis,$regexp) = @_;
1.56 www 615: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 616: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 617: "Attempt to delete from environment ".$delthis);
618: return 'error';
619: }
1.917 albertel 620: my $opened = open(my $env_file,'+<',$env{'user.environment'});
621: if ($opened
1.915 albertel 622: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 623: &&
624: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
625: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 626: foreach my $key (keys(%disk_env)) {
1.987 raeburn 627: if ($regexp) {
628: if ($key=~/^$delthis/) {
629: delete($env{$key});
630: delete($disk_env{$key});
631: }
632: } else {
633: if ($key=~/^\Q$delthis\E/) {
634: delete($env{$key});
635: delete($disk_env{$key});
636: }
637: }
1.448 albertel 638: }
1.783 albertel 639: untie(%disk_env);
1.5 www 640: }
641: return 'ok';
1.369 albertel 642: }
643:
1.790 albertel 644: sub get_env_multiple {
645: my ($name) = @_;
646: my @values;
647: if (defined($env{$name})) {
648: # exists is it an array
649: if (ref($env{$name})) {
650: @values=@{ $env{$name} };
651: } else {
652: $values[0]=$env{$name};
653: }
654: }
655: return(@values);
656: }
657:
1.958 www 658: # ------------------------------------------------------------------- Locking
659:
660: sub set_lock {
661: my ($text)=@_;
662: $locknum++;
663: my $id=$$.'-'.$locknum;
664: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
665: 'session.lock.'.$id => $text});
666: return $id;
667: }
668:
669: sub get_locks {
670: my $num=0;
671: my %texts=();
672: foreach my $lock (split(/\,/,$env{'session.locks'})) {
673: if ($lock=~/\w/) {
674: $num++;
675: $texts{$lock}=$env{'session.lock.'.$lock};
676: }
677: }
678: return ($num,%texts);
679: }
680:
681: sub remove_lock {
682: my ($id)=@_;
683: my $newlocks='';
684: foreach my $lock (split(/\,/,$env{'session.locks'})) {
685: if (($lock=~/\w/) && ($lock ne $id)) {
686: $newlocks.=','.$lock;
687: }
688: }
689: &appenv({'session.locks' => $newlocks});
690: &delenv('session.lock.'.$id);
691: }
692:
693: sub remove_all_locks {
694: my $activelocks=$env{'session.locks'};
695: foreach my $lock (split(/\,/,$env{'session.locks'})) {
696: if ($lock=~/\w/) {
697: &remove_lock($lock);
698: }
699: }
700: }
701:
702:
1.369 albertel 703: # ------------------------------------------ Find out current server userload
704: sub userload {
705: my $numusers=0;
706: {
707: opendir(LONIDS,$perlvar{'lonIDsDir'});
708: my $filename;
709: my $curtime=time;
710: while ($filename=readdir(LONIDS)) {
1.925 albertel 711: next if ($filename eq '.' || $filename eq '..');
712: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 713: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 714: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 715: }
716: closedir(LONIDS);
717: }
718: my $userloadpercent=0;
719: my $maxuserload=$perlvar{'lonUserLoadLim'};
720: if ($maxuserload) {
1.371 albertel 721: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 722: }
1.372 albertel 723: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 724: return $userloadpercent;
1.283 www 725: }
726:
1.1 albertel 727: # ------------------------------ Find server with least workload from spare.tab
1.11 www 728:
1.1 albertel 729: sub spareserver {
1.670 albertel 730: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 731: my $spare_server;
1.370 albertel 732: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 733: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
734: : $userloadpercent;
735:
736: foreach my $try_server (@{ $spareid{'primary'} }) {
737: ($spare_server, $lowest_load) =
738: &compare_server_load($try_server, $spare_server, $lowest_load);
739: }
740:
741: my $found_server = ($spare_server ne '' && $lowest_load < 100);
742:
743: if (!$found_server) {
744: foreach my $try_server (@{ $spareid{'default'} }) {
745: ($spare_server, $lowest_load) =
746: &compare_server_load($try_server, $spare_server, $lowest_load);
747: }
748: }
749:
750: if (!$want_server_name) {
1.968 raeburn 751: my $protocol = 'http';
752: if ($protocol{$spare_server} eq 'https') {
753: $protocol = $protocol{$spare_server};
754: }
1.1001 raeburn 755: if (defined($spare_server)) {
756: my $hostname = &hostname($spare_server);
757: if (defined($hostname)) {
758: $spare_server = $protocol.'://'.$hostname;
759: }
760: }
1.784 albertel 761: }
762: return $spare_server;
763: }
764:
765: sub compare_server_load {
766: my ($try_server, $spare_server, $lowest_load) = @_;
767:
768: my $loadans = &reply('load', $try_server);
769: my $userloadans = &reply('userload',$try_server);
770:
771: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 772: return; #didn't get a number from the server
1.784 albertel 773: }
774:
775: my $load;
776: if ($loadans =~ /\d/) {
777: if ($userloadans =~ /\d/) {
778: #both are numbers, pick the bigger one
779: $load = ($loadans > $userloadans) ? $loadans
780: : $userloadans;
1.411 albertel 781: } else {
1.784 albertel 782: $load = $loadans;
1.411 albertel 783: }
1.784 albertel 784: } else {
785: $load = $userloadans;
786: }
787:
788: if (($load =~ /\d/) && ($load < $lowest_load)) {
789: $spare_server = $try_server;
790: $lowest_load = $load;
1.370 albertel 791: }
1.784 albertel 792: return ($spare_server,$lowest_load);
1.202 matthew 793: }
1.914 albertel 794:
795: # --------------------------- ask offload servers if user already has a session
796: sub find_existing_session {
797: my ($udom,$uname) = @_;
798: foreach my $try_server (@{ $spareid{'primary'} },
799: @{ $spareid{'default'} }) {
800: return $try_server if (&has_user_session($try_server, $udom, $uname));
801: }
802: return;
803: }
804:
805: # -------------------------------- ask if server already has a session for user
806: sub has_user_session {
807: my ($lonid,$udom,$uname) = @_;
808: my $result = &reply(join(':','userhassession',
809: map {&escape($_)} ($udom,$uname)),$lonid);
810: return 1 if ($result eq 'ok');
811:
812: return 0;
813: }
814:
1.1076 ! raeburn 815: # --------- determine least loaded server in a user's domain which allows login
! 816:
! 817: sub choose_server {
! 818: my ($udom) = @_;
! 819: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
! 820: my %servers = &servers($udom);
! 821: my $lowest_load = 30000;
! 822: my ($login_host,$hostname);
! 823: foreach my $lonhost (keys(%servers)) {
! 824: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
! 825: if ($loginvia eq '') {
! 826: ($login_host, $lowest_load) =
! 827: &compare_server_load($lonhost, $login_host, $lowest_load);
! 828: }
! 829: }
! 830: if ($login_host ne '') {
! 831: $hostname = $servers{$login_host};
! 832: }
! 833: return ($login_host,$hostname);
! 834: }
! 835:
1.202 matthew 836: # --------------------------------------------- Try to change a user's password
837:
838: sub changepass {
1.799 raeburn 839: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 840: $currentpass = &escape($currentpass);
841: $newpass = &escape($newpass);
1.1030 raeburn 842: my $lonhost = $perlvar{'lonHostID'};
843: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 844: $server);
845: if (! $answer) {
846: &logthis("No reply on password change request to $server ".
847: "by $uname in domain $udom.");
848: } elsif ($answer =~ "^ok") {
849: &logthis("$uname in $udom successfully changed their password ".
850: "on $server.");
851: } elsif ($answer =~ "^pwchange_failure") {
852: &logthis("$uname in $udom was unable to change their password ".
853: "on $server. The action was blocked by either lcpasswd ".
854: "or pwchange");
855: } elsif ($answer =~ "^non_authorized") {
856: &logthis("$uname in $udom did not get their password correct when ".
857: "attempting to change it on $server.");
858: } elsif ($answer =~ "^auth_mode_error") {
859: &logthis("$uname in $udom attempted to change their password despite ".
860: "not being locally or internally authenticated on $server.");
861: } elsif ($answer =~ "^unknown_user") {
862: &logthis("$uname in $udom attempted to change their password ".
863: "on $server but were unable to because $server is not ".
864: "their home server.");
865: } elsif ($answer =~ "^refused") {
866: &logthis("$server refused to change $uname in $udom password because ".
867: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 868: } elsif ($answer =~ "invalid_client") {
869: &logthis("$server refused to change $uname in $udom password because ".
870: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 871: }
872: return $answer;
1.1 albertel 873: }
874:
1.169 harris41 875: # ----------------------- Try to determine user's current authentication scheme
876:
877: sub queryauthenticate {
878: my ($uname,$udom)=@_;
1.456 albertel 879: my $uhome=&homeserver($uname,$udom);
880: if (!$uhome) {
881: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
882: return 'no_host';
883: }
884: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
885: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
886: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 887: }
1.456 albertel 888: return $answer;
1.169 harris41 889: }
890:
1.1 albertel 891: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 892:
1.1 albertel 893: sub authenticate {
1.1073 raeburn 894: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 895: $upass=&escape($upass);
896: $uname= &LONCAPA::clean_username($uname);
1.836 www 897: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 898: my $newhome;
1.836 www 899: if ((!$uhome) || ($uhome eq 'no_host')) {
900: # Maybe the machine was offline and only re-appeared again recently?
901: &reconlonc();
902: # One more
1.952 raeburn 903: $uhome=&homeserver($uname,$udom,1);
904: if (($uhome eq 'no_host') && $checkdefauth) {
905: if (defined(&domain($udom,'primary'))) {
906: $newhome=&domain($udom,'primary');
907: }
908: if ($newhome ne '') {
909: $uhome = $newhome;
910: }
911: }
1.836 www 912: if ((!$uhome) || ($uhome eq 'no_host')) {
913: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 914: return 'no_host';
915: }
1.1 albertel 916: }
1.1073 raeburn 917: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 918: if ($answer eq 'authorized') {
1.952 raeburn 919: if ($newhome) {
920: &logthis("User $uname at $udom authorized by $uhome, but needs account");
921: return 'no_account_on_host';
922: } else {
923: &logthis("User $uname at $udom authorized by $uhome");
924: return $uhome;
925: }
1.471 albertel 926: }
927: if ($answer eq 'non_authorized') {
928: &logthis("User $uname at $udom rejected by $uhome");
929: return 'no_host';
1.9 www 930: }
1.471 albertel 931: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 932: return 'no_host';
933: }
934:
1.1073 raeburn 935: sub can_host_session {
1.1074 raeburn 936: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 937: my $canhost = 1;
1.1074 raeburn 938: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 939: if (ref($remotesessions) eq 'HASH') {
940: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 941: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 942: $canhost = 0;
943: } else {
944: $canhost = 1;
945: }
946: }
947: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 948: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 949: $canhost = 1;
950: } else {
951: $canhost = 0;
952: }
953: }
954: if ($canhost) {
955: if ($remotesessions->{'version'} ne '') {
956: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
957: if ($reqmajor ne '' && $reqminor ne '') {
958: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
959: my $major = $1;
960: my $minor = $2;
961: if (($major < $reqmajor ) ||
962: (($major == $reqmajor) && ($minor < $reqminor))) {
963: $canhost = 0;
964: }
965: } else {
966: $canhost = 0;
967: }
968: }
969: }
970: }
971: }
972: if ($canhost) {
973: if (ref($hostedsessions) eq 'HASH') {
974: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
975: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
976: $canhost = 0;
977: } else {
978: $canhost = 1;
979: }
980: }
981: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
982: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
983: $canhost = 1;
984: } else {
985: $canhost = 0;
986: }
987: }
988: }
989: }
990: return $canhost;
991: }
992:
1.1 albertel 993: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 994:
1.599 albertel 995: my %homecache;
1.1 albertel 996: sub homeserver {
1.230 stredwic 997: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 998: my $index="$uname:$udom";
1.426 albertel 999:
1.599 albertel 1000: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1001:
1002: my %servers = &get_servers($udom,'library');
1003: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1004: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1005: exists($badServerCache{$tryserver}));
1.841 albertel 1006:
1007: my $answer=reply("home:$udom:$uname",$tryserver);
1008: if ($answer eq 'found') {
1009: delete($badServerCache{$tryserver});
1010: return $homecache{$index}=$tryserver;
1011: } elsif ($answer eq 'no_host') {
1012: $badServerCache{$tryserver}=1;
1013: }
1.1 albertel 1014: }
1015: return 'no_host';
1.70 www 1016: }
1017:
1018: # ------------------------------------- Find the usernames behind a list of IDs
1019:
1020: sub idget {
1021: my ($udom,@ids)=@_;
1022: my %returnhash=();
1023:
1.841 albertel 1024: my %servers = &get_servers($udom,'library');
1025: foreach my $tryserver (keys(%servers)) {
1026: my $idlist=join('&',@ids);
1027: $idlist=~tr/A-Z/a-z/;
1028: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1029: my @answer=();
1030: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1031: @answer=split(/\&/,$reply);
1032: } ;
1033: my $i;
1034: for ($i=0;$i<=$#ids;$i++) {
1035: if ($answer[$i]) {
1036: $returnhash{$ids[$i]}=$answer[$i];
1037: }
1038: }
1039: }
1.70 www 1040: return %returnhash;
1041: }
1042:
1043: # ------------------------------------- Find the IDs behind a list of usernames
1044:
1045: sub idrget {
1046: my ($udom,@unames)=@_;
1047: my %returnhash=();
1.800 albertel 1048: foreach my $uname (@unames) {
1049: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1050: }
1.70 www 1051: return %returnhash;
1052: }
1053:
1054: # ------------------------------- Store away a list of names and associated IDs
1055:
1056: sub idput {
1057: my ($udom,%ids)=@_;
1058: my %servers=();
1.800 albertel 1059: foreach my $uname (keys(%ids)) {
1060: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1061: my $uhom=&homeserver($uname,$udom);
1.70 www 1062: if ($uhom ne 'no_host') {
1.800 albertel 1063: my $id=&escape($ids{$uname});
1.70 www 1064: $id=~tr/A-Z/a-z/;
1.800 albertel 1065: my $esc_unam=&escape($uname);
1.70 www 1066: if ($servers{$uhom}) {
1.800 albertel 1067: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1068: } else {
1.800 albertel 1069: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1070: }
1071: }
1.191 harris41 1072: }
1.800 albertel 1073: foreach my $server (keys(%servers)) {
1074: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1075: }
1.344 www 1076: }
1077:
1.1023 raeburn 1078: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1079: sub dump_dom {
1.1023 raeburn 1080: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1081: if (!$udom) {
1082: $udom=$env{'user.domain'};
1083: }
1084: my %returnhash;
1.1023 raeburn 1085: if ($udom) {
1086: my $uname = &get_domainconfiguser($udom);
1087: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1088: }
1089: return %returnhash;
1090: }
1091:
1.1023 raeburn 1092: # ------------------------------------------ get items from domain db files
1.806 raeburn 1093:
1094: sub get_dom {
1.860 raeburn 1095: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1096: my $items='';
1097: foreach my $item (@$storearr) {
1098: $items.=&escape($item).'&';
1099: }
1100: $items=~s/\&$//;
1.860 raeburn 1101: if (!$udom) {
1102: $udom=$env{'user.domain'};
1103: if (defined(&domain($udom,'primary'))) {
1104: $uhome=&domain($udom,'primary');
1105: } else {
1.874 albertel 1106: undef($uhome);
1.860 raeburn 1107: }
1108: } else {
1109: if (!$uhome) {
1110: if (defined(&domain($udom,'primary'))) {
1111: $uhome=&domain($udom,'primary');
1112: }
1113: }
1114: }
1115: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1116: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1117: my %returnhash;
1.875 albertel 1118: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1119: return %returnhash;
1120: }
1.806 raeburn 1121: my @pairs=split(/\&/,$rep);
1122: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1123: return @pairs;
1124: }
1125: my $i=0;
1126: foreach my $item (@$storearr) {
1127: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1128: $i++;
1129: }
1130: return %returnhash;
1131: } else {
1.880 banghart 1132: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1133: }
1134: }
1135:
1136: # -------------------------------------------- put items in domain db files
1137:
1138: sub put_dom {
1.860 raeburn 1139: my ($namespace,$storehash,$udom,$uhome)=@_;
1140: if (!$udom) {
1141: $udom=$env{'user.domain'};
1142: if (defined(&domain($udom,'primary'))) {
1143: $uhome=&domain($udom,'primary');
1144: } else {
1.874 albertel 1145: undef($uhome);
1.860 raeburn 1146: }
1147: } else {
1148: if (!$uhome) {
1149: if (defined(&domain($udom,'primary'))) {
1150: $uhome=&domain($udom,'primary');
1151: }
1152: }
1153: }
1154: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1155: my $items='';
1156: foreach my $item (keys(%$storehash)) {
1157: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1158: }
1159: $items=~s/\&$//;
1160: return &reply("putdom:$udom:$namespace:$items",$uhome);
1161: } else {
1.860 raeburn 1162: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1163: }
1164: }
1165:
1.1023 raeburn 1166: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1167: sub newput_dom {
1.1023 raeburn 1168: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1169: my $result;
1170: if (!$udom) {
1171: $udom=$env{'user.domain'};
1172: }
1.1023 raeburn 1173: if ($udom) {
1174: my $uname = &get_domainconfiguser($udom);
1175: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1176: }
1177: return $result;
1178: }
1179:
1.1023 raeburn 1180: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1181: sub del_dom {
1.1023 raeburn 1182: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1183: if (ref($storearr) eq 'ARRAY') {
1184: if (!$udom) {
1185: $udom=$env{'user.domain'};
1186: }
1.1023 raeburn 1187: if ($udom) {
1188: my $uname = &get_domainconfiguser($udom);
1189: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1190: }
1191: }
1192: }
1193:
1.1023 raeburn 1194: # ----------------------------------construct domainconfig user for a domain
1195: sub get_domainconfiguser {
1196: my ($udom) = @_;
1197: return $udom.'-domainconfig';
1198: }
1199:
1.837 raeburn 1200: sub retrieve_inst_usertypes {
1201: my ($udom) = @_;
1202: my (%returnhash,@order);
1.989 raeburn 1203: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1204: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1205: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1206: %returnhash = %{$domdefs{'inststatustypes'}};
1207: @order = @{$domdefs{'inststatusorder'}};
1208: } else {
1209: if (defined(&domain($udom,'primary'))) {
1210: my $uhome=&domain($udom,'primary');
1211: my $rep=&reply("inst_usertypes:$udom",$uhome);
1212: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1213: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1214: return (\%returnhash,\@order);
1215: }
1216: my ($hashitems,$orderitems) = split(/:/,$rep);
1217: my @pairs=split(/\&/,$hashitems);
1218: foreach my $item (@pairs) {
1219: my ($key,$value)=split(/=/,$item,2);
1220: $key = &unescape($key);
1221: next if ($key =~ /^error: 2 /);
1222: $returnhash{$key}=&thaw_unescape($value);
1223: }
1224: my @esc_order = split(/\&/,$orderitems);
1225: foreach my $item (@esc_order) {
1226: push(@order,&unescape($item));
1227: }
1228: } else {
1229: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1230: }
1231: }
1232: return (\%returnhash,\@order);
1233: }
1234:
1.868 raeburn 1235: sub is_domainimage {
1236: my ($url) = @_;
1237: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1238: if (&domain($1) ne '') {
1239: return '1';
1240: }
1241: }
1242: return;
1243: }
1244:
1.899 raeburn 1245: sub inst_directory_query {
1246: my ($srch) = @_;
1247: my $udom = $srch->{'srchdomain'};
1248: my %results;
1249: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1250: my $outcome;
1.899 raeburn 1251: if ($homeserver ne '') {
1.904 albertel 1252: my $queryid=&reply("querysend:instdirsearch:".
1253: &escape($srch->{'srchby'}).':'.
1254: &escape($srch->{'srchterm'}).':'.
1255: &escape($srch->{'srchtype'}),$homeserver);
1256: my $host=&hostname($homeserver);
1257: if ($queryid !~/^\Q$host\E\_/) {
1258: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1259: return;
1260: }
1261: my $response = &get_query_reply($queryid);
1262: my $maxtries = 5;
1263: my $tries = 1;
1264: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1265: $response = &get_query_reply($queryid);
1266: $tries ++;
1267: }
1268:
1269: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1270: if ($response eq 'unavailable') {
1271: $outcome = $response;
1272: } else {
1273: $outcome = 'ok';
1274: my @matches = split(/\n/,$response);
1275: foreach my $match (@matches) {
1276: my ($key,$value) = split(/=/,$match);
1277: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1278: }
1.899 raeburn 1279: }
1280: }
1281: }
1.909 raeburn 1282: return ($outcome,%results);
1.899 raeburn 1283: }
1284:
1285: sub usersearch {
1286: my ($srch) = @_;
1287: my $dom = $srch->{'srchdomain'};
1288: my %results;
1289: my %libserv = &all_library();
1290: my $query = 'usersearch';
1291: foreach my $tryserver (keys(%libserv)) {
1292: if (&host_domain($tryserver) eq $dom) {
1293: my $host=&hostname($tryserver);
1294: my $queryid=
1.911 raeburn 1295: &reply("querysend:".&escape($query).':'.
1296: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1297: &escape($srch->{'srchtype'}).':'.
1298: &escape($srch->{'srchterm'}),$tryserver);
1299: if ($queryid !~/^\Q$host\E\_/) {
1300: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1301: next;
1.899 raeburn 1302: }
1303: my $reply = &get_query_reply($queryid);
1304: my $maxtries = 1;
1305: my $tries = 1;
1306: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1307: $reply = &get_query_reply($queryid);
1308: $tries ++;
1309: }
1310: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1311: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1312: } else {
1.911 raeburn 1313: my @matches;
1314: if ($reply =~ /\n/) {
1315: @matches = split(/\n/,$reply);
1316: } else {
1317: @matches = split(/\&/,$reply);
1318: }
1.899 raeburn 1319: foreach my $match (@matches) {
1320: my ($uname,$udom,%userhash);
1.911 raeburn 1321: foreach my $entry (split(/:/,$match)) {
1322: my ($key,$value) =
1323: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1324: $userhash{$key} = $value;
1325: if ($key eq 'username') {
1326: $uname = $value;
1327: } elsif ($key eq 'domain') {
1328: $udom = $value;
1.911 raeburn 1329: }
1.899 raeburn 1330: }
1331: $results{$uname.':'.$udom} = \%userhash;
1332: }
1333: }
1334: }
1335: }
1336: return %results;
1337: }
1338:
1.912 raeburn 1339: sub get_instuser {
1340: my ($udom,$uname,$id) = @_;
1341: my $homeserver = &domain($udom,'primary');
1342: my ($outcome,%results);
1343: if ($homeserver ne '') {
1344: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1345: &escape($id).':'.&escape($udom),$homeserver);
1346: my $host=&hostname($homeserver);
1347: if ($queryid !~/^\Q$host\E\_/) {
1348: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1349: return;
1350: }
1351: my $response = &get_query_reply($queryid);
1352: my $maxtries = 5;
1353: my $tries = 1;
1354: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1355: $response = &get_query_reply($queryid);
1356: $tries ++;
1357: }
1358: if (!&error($response) && $response ne 'refused') {
1359: if ($response eq 'unavailable') {
1360: $outcome = $response;
1361: } else {
1362: $outcome = 'ok';
1363: my @matches = split(/\n/,$response);
1364: foreach my $match (@matches) {
1365: my ($key,$value) = split(/=/,$match);
1366: $results{&unescape($key)} = &thaw_unescape($value);
1367: }
1368: }
1369: }
1370: }
1371: my %userinfo;
1372: if (ref($results{$uname}) eq 'HASH') {
1373: %userinfo = %{$results{$uname}};
1374: }
1375: return ($outcome,%userinfo);
1376: }
1377:
1378: sub inst_rulecheck {
1.923 raeburn 1379: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1380: my %returnhash;
1381: if ($udom ne '') {
1382: if (ref($rules) eq 'ARRAY') {
1383: @{$rules} = map {&escape($_);} (@{$rules});
1384: my $rulestr = join(':',@{$rules});
1385: my $homeserver=&domain($udom,'primary');
1386: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1387: my $response;
1388: if ($item eq 'username') {
1389: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1390: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1391: $homeserver));
1.923 raeburn 1392: } elsif ($item eq 'id') {
1393: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1394: ':'.&escape($id).':'.$rulestr,
1395: $homeserver));
1.945 raeburn 1396: } elsif ($item eq 'selfcreate') {
1397: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1398: &escape($udom).':'.&escape($uname).
1399: ':'.$rulestr,$homeserver));
1.923 raeburn 1400: }
1.912 raeburn 1401: if ($response ne 'refused') {
1402: my @pairs=split(/\&/,$response);
1403: foreach my $item (@pairs) {
1404: my ($key,$value)=split(/=/,$item,2);
1405: $key = &unescape($key);
1406: next if ($key =~ /^error: 2 /);
1407: $returnhash{$key}=&thaw_unescape($value);
1408: }
1409: }
1410: }
1411: }
1412: }
1413: return %returnhash;
1414: }
1415:
1416: sub inst_userrules {
1.923 raeburn 1417: my ($udom,$check) = @_;
1.912 raeburn 1418: my (%ruleshash,@ruleorder);
1419: if ($udom ne '') {
1420: my $homeserver=&domain($udom,'primary');
1421: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1422: my $response;
1423: if ($check eq 'id') {
1424: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1425: $homeserver);
1.943 raeburn 1426: } elsif ($check eq 'email') {
1427: $response=&reply('instemailrules:'.&escape($udom),
1428: $homeserver);
1.923 raeburn 1429: } else {
1430: $response=&reply('instuserrules:'.&escape($udom),
1431: $homeserver);
1432: }
1.912 raeburn 1433: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1434: ($response ne 'unknown_cmd') &&
1.912 raeburn 1435: ($response ne 'no_such_host')) {
1436: my ($hashitems,$orderitems) = split(/:/,$response);
1437: my @pairs=split(/\&/,$hashitems);
1438: foreach my $item (@pairs) {
1439: my ($key,$value)=split(/=/,$item,2);
1440: $key = &unescape($key);
1441: next if ($key =~ /^error: 2 /);
1442: $ruleshash{$key}=&thaw_unescape($value);
1443: }
1444: my @esc_order = split(/\&/,$orderitems);
1445: foreach my $item (@esc_order) {
1446: push(@ruleorder,&unescape($item));
1447: }
1448: }
1449: }
1450: }
1451: return (\%ruleshash,\@ruleorder);
1452: }
1453:
1.976 raeburn 1454: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1455:
1456: sub get_domain_defaults {
1457: my ($domain) = @_;
1458: my $cachetime = 60*60*24;
1459: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1460: if (defined($cached)) {
1461: if (ref($result) eq 'HASH') {
1462: return %{$result};
1463: }
1464: }
1465: my %domdefaults;
1466: my %domconfig =
1.989 raeburn 1467: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1468: 'requestcourses','inststatus',
1.1073 raeburn 1469: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1470: if (ref($domconfig{'defaults'}) eq 'HASH') {
1471: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1472: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1473: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1474: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1475: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1476: } else {
1477: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1478: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1479: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1480: }
1.976 raeburn 1481: if (ref($domconfig{'quotas'}) eq 'HASH') {
1482: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1483: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1484: } else {
1485: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1486: }
1487: my @usertools = ('aboutme','blog','portfolio');
1488: foreach my $item (@usertools) {
1489: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1490: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1491: }
1492: }
1493: }
1.985 raeburn 1494: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1495: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1496: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1497: }
1498: }
1.989 raeburn 1499: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1500: foreach my $item ('inststatustypes','inststatusorder') {
1501: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1502: }
1503: }
1.1047 raeburn 1504: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1505: foreach my $item ('canuse_pdfforms') {
1506: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1507: }
1508: }
1.1073 raeburn 1509: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1510: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1511: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1512: }
1513: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1514: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1515: }
1516: }
1.943 raeburn 1517: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1518: $cachetime);
1519: return %domdefaults;
1520: }
1521:
1.344 www 1522: # --------------------------------------------------- Assign a key to a student
1523:
1524: sub assign_access_key {
1.364 www 1525: #
1526: # a valid key looks like uname:udom#comments
1527: # comments are being appended
1528: #
1.498 www 1529: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1530: $kdom=
1.620 albertel 1531: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1532: $knum=
1.620 albertel 1533: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1534: $cdom=
1.620 albertel 1535: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1536: $cnum=
1.620 albertel 1537: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1538: $udom=$env{'user.name'} unless (defined($udom));
1539: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1540: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1541: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1542: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1543: # assigned to this person
1544: # - this should not happen,
1.345 www 1545: # unless something went wrong
1546: # the first time around
1547: # ready to assign
1.364 www 1548: $logentry=$1.'; '.$logentry;
1.496 www 1549: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1550: $kdom,$knum) eq 'ok') {
1.345 www 1551: # key now belongs to user
1.346 www 1552: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1553: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1554: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1555: return 'ok';
1556: } else {
1557: return
1558: 'error: Count not permanently assign key, will need to be re-entered later.';
1559: }
1560: } else {
1561: return 'error: Could not assign key, try again later.';
1562: }
1.364 www 1563: } elsif (!$existing{$ckey}) {
1.345 www 1564: # the key does not exist
1565: return 'error: The key does not exist';
1566: } else {
1567: # the key is somebody else's
1568: return 'error: The key is already in use';
1569: }
1.344 www 1570: }
1571:
1.364 www 1572: # ------------------------------------------ put an additional comment on a key
1573:
1574: sub comment_access_key {
1575: #
1576: # a valid key looks like uname:udom#comments
1577: # comments are being appended
1578: #
1579: my ($ckey,$cdom,$cnum,$logentry)=@_;
1580: $cdom=
1.620 albertel 1581: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1582: $cnum=
1.620 albertel 1583: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1584: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1585: if ($existing{$ckey}) {
1586: $existing{$ckey}.='; '.$logentry;
1587: # ready to assign
1.367 www 1588: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1589: $cdom,$cnum) eq 'ok') {
1590: return 'ok';
1591: } else {
1592: return 'error: Count not store comment.';
1593: }
1594: } else {
1595: # the key does not exist
1596: return 'error: The key does not exist';
1597: }
1598: }
1599:
1.344 www 1600: # ------------------------------------------------------ Generate a set of keys
1601:
1602: sub generate_access_keys {
1.364 www 1603: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1604: $cdom=
1.620 albertel 1605: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1606: $cnum=
1.620 albertel 1607: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1608: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1609: unless (($cdom) && ($cnum)) { return 0; }
1610: if ($number>10000) { return 0; }
1611: sleep(2); # make sure don't get same seed twice
1612: srand(time()^($$+($$<<15))); # from "Programming Perl"
1613: my $total=0;
1614: for (my $i=1;$i<=$number;$i++) {
1615: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1616: sprintf("%lx",int(100000*rand)).'-'.
1617: sprintf("%lx",int(100000*rand));
1618: $newkey=~s/1/g/g; # folks mix up 1 and l
1619: $newkey=~s/0/h/g; # and also 0 and O
1620: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1621: if ($existing{$newkey}) {
1622: $i--;
1623: } else {
1.364 www 1624: if (&put('accesskeys',
1625: { $newkey => '# generated '.localtime().
1.620 albertel 1626: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1627: '; '.$logentry },
1628: $cdom,$cnum) eq 'ok') {
1.344 www 1629: $total++;
1630: }
1631: }
1632: }
1.620 albertel 1633: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1634: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1635: return $total;
1636: }
1637:
1638: # ------------------------------------------------------- Validate an accesskey
1639:
1640: sub validate_access_key {
1641: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1642: $cdom=
1.620 albertel 1643: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1644: $cnum=
1.620 albertel 1645: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1646: $udom=$env{'user.domain'} unless (defined($udom));
1647: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1648: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1649: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1650: }
1651:
1652: # ------------------------------------- Find the section of student in a course
1.652 albertel 1653: sub devalidate_getsection_cache {
1654: my ($udom,$unam,$courseid)=@_;
1655: my $hashid="$udom:$unam:$courseid";
1656: &devalidate_cache_new('getsection',$hashid);
1657: }
1.298 matthew 1658:
1.815 albertel 1659: sub courseid_to_courseurl {
1660: my ($courseid) = @_;
1661: #already url style courseid
1662: return $courseid if ($courseid =~ m{^/});
1663:
1664: if (exists($env{'course.'.$courseid.'.num'})) {
1665: my $cnum = $env{'course.'.$courseid.'.num'};
1666: my $cdom = $env{'course.'.$courseid.'.domain'};
1667: return "/$cdom/$cnum";
1668: }
1669:
1670: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1671: if (exists($courseinfo{'num'})) {
1672: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1673: }
1674:
1675: return undef;
1676: }
1677:
1.298 matthew 1678: sub getsection {
1679: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1680: my $cachetime=1800;
1.551 albertel 1681:
1682: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1683: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1684: if (defined($cached)) { return $result; }
1685:
1.298 matthew 1686: my %Pending;
1687: my %Expired;
1688: #
1689: # Each role can either have not started yet (pending), be active,
1690: # or have expired.
1691: #
1692: # If there is an active role, we are done.
1693: #
1694: # If there is more than one role which has not started yet,
1695: # choose the one which will start sooner
1696: # If there is one role which has not started yet, return it.
1697: #
1698: # If there is more than one expired role, choose the one which ended last.
1699: # If there is a role which has expired, return it.
1700: #
1.815 albertel 1701: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1702: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1703: foreach my $key (keys(%roleshash)) {
1.479 albertel 1704: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1705: my $section=$1;
1706: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1707: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1708: my $now=time;
1.548 albertel 1709: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1710: $Expired{$end}=$section;
1711: next;
1712: }
1.548 albertel 1713: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1714: $Pending{$start}=$section;
1715: next;
1716: }
1.599 albertel 1717: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1718: }
1719: #
1720: # Presumedly there will be few matching roles from the above
1721: # loop and the sorting time will be negligible.
1722: if (scalar(keys(%Pending))) {
1723: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1724: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1725: }
1726: if (scalar(keys(%Expired))) {
1727: my @sorted = sort {$a <=> $b} keys(%Expired);
1728: my $time = pop(@sorted);
1.599 albertel 1729: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1730: }
1.599 albertel 1731: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1732: }
1.70 www 1733:
1.599 albertel 1734: sub save_cache {
1735: &purge_remembered();
1.722 albertel 1736: #&Apache::loncommon::validate_page();
1.620 albertel 1737: undef(%env);
1.780 albertel 1738: undef($env_loaded);
1.599 albertel 1739: }
1.452 albertel 1740:
1.599 albertel 1741: my $to_remember=-1;
1742: my %remembered;
1743: my %accessed;
1744: my $kicks=0;
1745: my $hits=0;
1.849 albertel 1746: sub make_key {
1747: my ($name,$id) = @_;
1.872 albertel 1748: if (length($id) > 65
1749: && length(&escape($id)) > 200) {
1750: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1751: }
1.849 albertel 1752: return &escape($name.':'.$id);
1753: }
1754:
1.599 albertel 1755: sub devalidate_cache_new {
1756: my ($name,$id,$debug) = @_;
1757: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1758: $id=&make_key($name,$id);
1.599 albertel 1759: $memcache->delete($id);
1760: delete($remembered{$id});
1761: delete($accessed{$id});
1762: }
1763:
1764: sub is_cached_new {
1765: my ($name,$id,$debug) = @_;
1.849 albertel 1766: $id=&make_key($name,$id);
1.599 albertel 1767: if (exists($remembered{$id})) {
1768: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1769: $accessed{$id}=[&gettimeofday()];
1770: $hits++;
1771: return ($remembered{$id},1);
1772: }
1773: my $value = $memcache->get($id);
1774: if (!(defined($value))) {
1775: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1776: return (undef,undef);
1.416 albertel 1777: }
1.599 albertel 1778: if ($value eq '__undef__') {
1779: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1780: $value=undef;
1781: }
1782: &make_room($id,$value,$debug);
1783: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1784: return ($value,1);
1785: }
1786:
1787: sub do_cache_new {
1788: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1789: $id=&make_key($name,$id);
1.599 albertel 1790: my $setvalue=$value;
1791: if (!defined($setvalue)) {
1792: $setvalue='__undef__';
1793: }
1.623 albertel 1794: if (!defined($time) ) {
1795: $time=600;
1796: }
1.599 albertel 1797: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1798: my $result = $memcache->set($id,$setvalue,$time);
1799: if (! $result) {
1.872 albertel 1800: &logthis("caching of id -> $id failed");
1.910 albertel 1801: $memcache->disconnect_all();
1.872 albertel 1802: }
1.600 albertel 1803: # need to make a copy of $value
1.919 albertel 1804: &make_room($id,$value,$debug);
1.599 albertel 1805: return $value;
1806: }
1807:
1808: sub make_room {
1809: my ($id,$value,$debug)=@_;
1.919 albertel 1810:
1811: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1812: : $value;
1.599 albertel 1813: if ($to_remember<0) { return; }
1814: $accessed{$id}=[&gettimeofday()];
1815: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1816: my $to_kick;
1817: my $max_time=0;
1818: foreach my $other (keys(%accessed)) {
1819: if (&tv_interval($accessed{$other}) > $max_time) {
1820: $to_kick=$other;
1821: $max_time=&tv_interval($accessed{$other});
1822: }
1823: }
1824: delete($remembered{$to_kick});
1825: delete($accessed{$to_kick});
1826: $kicks++;
1827: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1828: return;
1829: }
1830:
1.599 albertel 1831: sub purge_remembered {
1.604 albertel 1832: #&logthis("Tossing ".scalar(keys(%remembered)));
1833: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1834: undef(%remembered);
1835: undef(%accessed);
1.428 albertel 1836: }
1.70 www 1837: # ------------------------------------- Read an entry from a user's environment
1838:
1839: sub userenvironment {
1840: my ($udom,$unam,@what)=@_;
1.976 raeburn 1841: my $items;
1842: foreach my $item (@what) {
1843: $items.=&escape($item).'&';
1844: }
1845: $items=~s/\&$//;
1.70 www 1846: my %returnhash=();
1.1009 raeburn 1847: my $uhome = &homeserver($unam,$udom);
1848: unless ($uhome eq 'no_host') {
1849: my @answer=split(/\&/,
1850: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1851: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1852: return %returnhash;
1853: }
1.1009 raeburn 1854: my $i;
1855: for ($i=0;$i<=$#what;$i++) {
1856: $returnhash{$what[$i]}=&unescape($answer[$i]);
1857: }
1.70 www 1858: }
1859: return %returnhash;
1.1 albertel 1860: }
1861:
1.617 albertel 1862: # ---------------------------------------------------------- Get a studentphoto
1863: sub studentphoto {
1864: my ($udom,$unam,$ext) = @_;
1865: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1866: if (defined($env{'request.course.id'})) {
1.708 raeburn 1867: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1868: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1869: return(&retrievestudentphoto($udom,$unam,$ext));
1870: } else {
1871: my ($result,$perm_reqd)=
1.707 albertel 1872: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1873: if ($result eq 'ok') {
1874: if (!($perm_reqd eq 'yes')) {
1875: return(&retrievestudentphoto($udom,$unam,$ext));
1876: }
1877: }
1878: }
1879: }
1880: } else {
1881: my ($result,$perm_reqd) =
1.707 albertel 1882: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1883: if ($result eq 'ok') {
1884: if (!($perm_reqd eq 'yes')) {
1885: return(&retrievestudentphoto($udom,$unam,$ext));
1886: }
1887: }
1888: }
1889: return '/adm/lonKaputt/lonlogo_broken.gif';
1890: }
1891:
1892: sub retrievestudentphoto {
1893: my ($udom,$unam,$ext,$type) = @_;
1894: my $home=&Apache::lonnet::homeserver($unam,$udom);
1895: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1896: if ($ret eq 'ok') {
1897: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1898: if ($type eq 'thumbnail') {
1899: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1900: }
1901: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1902: return $tokenurl;
1903: } else {
1904: if ($type eq 'thumbnail') {
1905: return '/adm/lonKaputt/genericstudent_tn.gif';
1906: } else {
1907: return '/adm/lonKaputt/lonlogo_broken.gif';
1908: }
1.617 albertel 1909: }
1910: }
1911:
1.263 www 1912: # -------------------------------------------------------------------- New chat
1913:
1914: sub chatsend {
1.724 raeburn 1915: my ($newentry,$anon,$group)=@_;
1.620 albertel 1916: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1917: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1918: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1919: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1920: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1921: &escape($newentry)).':'.$group,$chome);
1.292 www 1922: }
1923:
1924: # ------------------------------------------ Find current version of a resource
1925:
1926: sub getversion {
1927: my $fname=&clutter(shift);
1928: unless ($fname=~/^\/res\//) { return -1; }
1929: return ¤tversion(&filelocation('',$fname));
1930: }
1931:
1932: sub currentversion {
1933: my $fname=shift;
1.599 albertel 1934: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1935: if (defined($cached)) { return $result; }
1.292 www 1936: my $author=$fname;
1937: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1938: my ($udom,$uname)=split(/\//,$author);
1939: my $home=homeserver($uname,$udom);
1940: if ($home eq 'no_host') {
1941: return -1;
1942: }
1943: my $answer=reply("currentversion:$fname",$home);
1944: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1945: return -1;
1946: }
1.599 albertel 1947: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1948: }
1949:
1.1 albertel 1950: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1951:
1.1 albertel 1952: sub subscribe {
1953: my $fname=shift;
1.761 raeburn 1954: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1955: $fname=~s/[\n\r]//g;
1.1 albertel 1956: my $author=$fname;
1957: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1958: my ($udom,$uname)=split(/\//,$author);
1959: my $home=homeserver($uname,$udom);
1.335 albertel 1960: if ($home eq 'no_host') {
1961: return 'not_found';
1.1 albertel 1962: }
1963: my $answer=reply("sub:$fname",$home);
1.64 www 1964: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1965: $answer.=' by '.$home;
1966: }
1.1 albertel 1967: return $answer;
1968: }
1969:
1.8 www 1970: # -------------------------------------------------------------- Replicate file
1971:
1972: sub repcopy {
1973: my $filename=shift;
1.23 www 1974: $filename=~s/\/+/\//g;
1.607 raeburn 1975: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1976: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1977: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1978: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1979: return &repcopy_userfile($filename);
1980: }
1.532 albertel 1981: $filename=~s/[\n\r]//g;
1.8 www 1982: my $transname="$filename.in.transfer";
1.828 www 1983: # FIXME: this should flock
1.607 raeburn 1984: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1985: my $remoteurl=subscribe($filename);
1.64 www 1986: if ($remoteurl =~ /^con_lost by/) {
1987: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1988: return 'unavailable';
1.8 www 1989: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1990: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1991: return 'not_found';
1.64 www 1992: } elsif ($remoteurl =~ /^rejected by/) {
1993: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1994: return 'forbidden';
1.20 www 1995: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1996: return 'ok';
1.8 www 1997: } else {
1.290 www 1998: my $author=$filename;
1999: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2000: my ($udom,$uname)=split(/\//,$author);
2001: my $home=homeserver($uname,$udom);
2002: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2003: my @parts=split(/\//,$filename);
2004: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2005: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2006: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2007: return 'bad_request';
1.8 www 2008: }
2009: my $count;
2010: for ($count=5;$count<$#parts;$count++) {
2011: $path.="/$parts[$count]";
2012: if ((-e $path)!=1) {
2013: mkdir($path,0777);
2014: }
2015: }
2016: my $ua=new LWP::UserAgent;
2017: my $request=new HTTP::Request('GET',"$remoteurl");
2018: my $response=$ua->request($request,$transname);
2019: if ($response->is_error()) {
2020: unlink($transname);
2021: my $message=$response->status_line;
1.672 albertel 2022: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2023: ." LWP get: $message: $filename</font>");
1.607 raeburn 2024: return 'unavailable';
1.8 www 2025: } else {
1.16 www 2026: if ($remoteurl!~/\.meta$/) {
2027: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2028: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2029: if ($mresponse->is_error()) {
2030: unlink($filename.'.meta');
2031: &logthis(
1.672 albertel 2032: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2033: }
2034: }
1.8 www 2035: rename($transname,$filename);
1.607 raeburn 2036: return 'ok';
1.8 www 2037: }
1.290 www 2038: }
1.8 www 2039: }
1.330 www 2040: }
2041:
2042: # ------------------------------------------------ Get server side include body
2043: sub ssi_body {
1.381 albertel 2044: my ($filelink,%form)=@_;
1.606 matthew 2045: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2046: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2047: }
1.953 www 2048: my $output='';
2049: my $response;
1.980 raeburn 2050: if ($filelink=~/^https?\:/) {
1.954 raeburn 2051: ($output,$response)=&externalssi($filelink);
1.953 www 2052: } else {
1.1004 droeschl 2053: $filelink .= $filelink=~/\?/ ? '&' : '?';
2054: $filelink .= 'inhibitmenu=yes';
1.953 www 2055: ($output,$response)=&ssi($filelink,%form);
2056: }
1.778 albertel 2057: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2058: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2059: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2060: if (wantarray) {
2061: return ($output, $response);
2062: } else {
2063: return $output;
2064: }
1.8 www 2065: }
2066:
1.15 www 2067: # --------------------------------------------------------- Server Side Include
2068:
1.782 albertel 2069: sub absolute_url {
2070: my ($host_name) = @_;
2071: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2072: if ($host_name eq '') {
2073: $host_name = $ENV{'SERVER_NAME'};
2074: }
2075: return $protocol.$host_name;
2076: }
2077:
1.942 foxr 2078: #
2079: # Server side include.
2080: # Parameters:
2081: # fn Possibly encrypted resource name/id.
2082: # form Hash that describes how the rendering should be done
2083: # and other things.
1.944 foxr 2084: # Returns:
1.950 raeburn 2085: # Scalar context: The content of the response.
2086: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2087: #
1.15 www 2088: sub ssi {
2089:
1.944 foxr 2090: my ($fn,%form)=@_;
1.15 www 2091: my $ua=new LWP::UserAgent;
1.23 www 2092: my $request;
1.711 albertel 2093:
2094: $form{'no_update_last_known'}=1;
1.895 albertel 2095: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2096: if (%form) {
1.782 albertel 2097: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2098: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2099: } else {
1.782 albertel 2100: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2101: }
2102:
1.15 www 2103: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2104: my $response=$ua->request($request);
2105:
1.944 foxr 2106: if (wantarray) {
2107: return ($response->content, $response);
2108: } else {
2109: return $response->content;
1.942 foxr 2110: }
1.324 www 2111: }
2112:
2113: sub externalssi {
2114: my ($url)=@_;
2115: my $ua=new LWP::UserAgent;
2116: my $request=new HTTP::Request('GET',$url);
2117: my $response=$ua->request($request);
1.954 raeburn 2118: if (wantarray) {
2119: return ($response->content, $response);
2120: } else {
2121: return $response->content;
2122: }
1.15 www 2123: }
1.254 www 2124:
1.492 albertel 2125: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2126:
2127: sub allowuploaded {
2128: my ($srcurl,$url)=@_;
2129: $url=&clutter(&declutter($url));
2130: my $dir=$url;
2131: $dir=~s/\/[^\/]+$//;
2132: my %httpref=();
2133: my $httpurl=&hreflocation('',$url);
2134: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2135: &Apache::lonnet::appenv(\%httpref);
1.254 www 2136: }
1.477 raeburn 2137:
1.478 albertel 2138: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2139: # input: action, courseID, current domain, intended
1.637 raeburn 2140: # path to file, source of file, instruction to parse file for objects,
2141: # ref to hash for embedded objects,
2142: # ref to hash for codebase of java objects.
2143: #
1.485 raeburn 2144: # output: url to file (if action was uploaddoc),
2145: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2146: #
1.478 albertel 2147: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2148: # course.
1.477 raeburn 2149: #
1.478 albertel 2150: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2151: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2152: # course's home server.
1.477 raeburn 2153: #
1.478 albertel 2154: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2155: # be copied from $source (current location) to
2156: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2157: # and will then be copied to
2158: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2159: # course's home server.
1.485 raeburn 2160: #
1.481 raeburn 2161: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2162: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2163: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2164: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2165: # in course's home server.
1.637 raeburn 2166: #
1.477 raeburn 2167:
2168: sub process_coursefile {
1.638 albertel 2169: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2170: my $fetchresult;
1.638 albertel 2171: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2172: if ($action eq 'propagate') {
1.638 albertel 2173: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2174: $home);
1.481 raeburn 2175: } else {
1.477 raeburn 2176: my $fpath = '';
2177: my $fname = $file;
1.478 albertel 2178: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2179: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2180: my $filepath = &build_filepath($fpath);
1.481 raeburn 2181: if ($action eq 'copy') {
2182: if ($source eq '') {
2183: $fetchresult = 'no source file';
2184: return $fetchresult;
2185: } else {
2186: my $destination = $filepath.'/'.$fname;
2187: rename($source,$destination);
2188: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2189: $home);
1.481 raeburn 2190: }
2191: } elsif ($action eq 'uploaddoc') {
2192: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2193: print $fh $env{'form.'.$source};
1.481 raeburn 2194: close($fh);
1.637 raeburn 2195: if ($parser eq 'parse') {
1.1024 raeburn 2196: my $mm = new File::MMagic;
2197: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2198: if ($mime_type eq 'text/html') {
2199: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2200: unless ($parse_result eq 'ok') {
2201: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2202: }
1.637 raeburn 2203: }
2204: }
1.477 raeburn 2205: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2206: $home);
1.481 raeburn 2207: if ($fetchresult eq 'ok') {
2208: return '/uploaded/'.$fpath.'/'.$fname;
2209: } else {
2210: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2211: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2212: return '/adm/notfound.html';
2213: }
1.477 raeburn 2214: }
2215: }
1.485 raeburn 2216: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2217: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2218: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2219: }
2220: return $fetchresult;
2221: }
2222:
1.637 raeburn 2223: sub build_filepath {
2224: my ($fpath) = @_;
2225: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2226: unless ($fpath eq '') {
2227: my @parts=split('/',$fpath);
2228: foreach my $part (@parts) {
2229: $filepath.= '/'.$part;
2230: if ((-e $filepath)!=1) {
2231: mkdir($filepath,0777);
2232: }
2233: }
2234: }
2235: return $filepath;
2236: }
2237:
2238: sub store_edited_file {
1.638 albertel 2239: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2240: my $file = $primary_url;
2241: $file =~ s#^/uploaded/$docudom/$docuname/##;
2242: my $fpath = '';
2243: my $fname = $file;
2244: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2245: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2246: my $filepath = &build_filepath($fpath);
2247: open(my $fh,'>'.$filepath.'/'.$fname);
2248: print $fh $content;
2249: close($fh);
1.638 albertel 2250: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2251: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2252: $home);
1.637 raeburn 2253: if ($$fetchresult eq 'ok') {
2254: return '/uploaded/'.$fpath.'/'.$fname;
2255: } else {
1.638 albertel 2256: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2257: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2258: return '/adm/notfound.html';
2259: }
2260: }
2261:
1.531 albertel 2262: sub clean_filename {
1.831 albertel 2263: my ($fname,$args)=@_;
1.315 www 2264: # Replace Windows backslashes by forward slashes
1.257 www 2265: $fname=~s/\\/\//g;
1.831 albertel 2266: if (!$args->{'keep_path'}) {
2267: # Get rid of everything but the actual filename
2268: $fname=~s/^.*\/([^\/]+)$/$1/;
2269: }
1.315 www 2270: # Replace spaces by underscores
2271: $fname=~s/\s+/\_/g;
2272: # Replace all other weird characters by nothing
1.831 albertel 2273: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2274: # Replace all .\d. sequences with _\d. so they no longer look like version
2275: # numbers
2276: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2277: return $fname;
2278: }
1.1051 raeburn 2279: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2280: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2281: # image with the same aspect ratio as the original, but with dimensions which do
2282: # not exceed $resizewidth and $resizeheight.
2283:
1.984 neumanie 2284: sub resizeImage {
1.1051 raeburn 2285: my ($img_path,$resizewidth,$resizeheight) = @_;
2286: my $ima = Image::Magick->new;
2287: my $resized;
2288: if (-e $img_path) {
2289: $ima->Read($img_path);
2290: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2291: my $width = $ima->Get('width');
2292: my $height = $ima->Get('height');
2293: if ($width > $resizewidth) {
2294: my $factor = $width/$resizewidth;
2295: my $newheight = $height/$factor;
2296: $ima->Scale(width=>$resizewidth,height=>$newheight);
2297: $resized = 1;
2298: }
2299: }
2300: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2301: my $width = $ima->Get('width');
2302: my $height = $ima->Get('height');
2303: if ($height > $resizeheight) {
2304: my $factor = $height/$resizeheight;
2305: my $newwidth = $width/$factor;
2306: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2307: $resized = 1;
2308: }
2309: }
2310: if ($resized) {
2311: $ima->Write($img_path);
2312: }
2313: }
2314: return;
1.977 amueller 2315: }
2316:
1.608 albertel 2317: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2318: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2319: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2320: # $coursedoc - if true up to the current course
2321: # if false
2322: # $subdir - directory in userfile to store the file into
1.858 raeburn 2323: # $parser - instruction to parse file for objects ($parser = parse)
2324: # $allfiles - reference to hash for embedded objects
2325: # $codebase - reference to hash for codebase of java objects
2326: # $desuname - username for permanent storage of uploaded file
2327: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2328: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2329: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2330: # $resizewidth - width (pixels) to which to resize uploaded image
2331: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2332: #
1.686 albertel 2333: # output: url of file in userspace, or error: <message>
2334: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2335:
1.531 albertel 2336: sub userfileupload {
1.860 raeburn 2337: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2338: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2339: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2340: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2341: $fname=&clean_filename($fname);
1.315 www 2342: # See if there is anything left
1.257 www 2343: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2344: chop($env{'form.'.$formname});
1.523 raeburn 2345: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2346: my $now = time;
2347: my $filepath = 'tmp/helprequests/'.$now;
2348: my @parts=split(/\//,$filepath);
2349: my $fullpath = $perlvar{'lonDaemons'};
2350: for (my $i=0;$i<@parts;$i++) {
2351: $fullpath .= '/'.$parts[$i];
2352: if ((-e $fullpath)!=1) {
2353: mkdir($fullpath,0777);
2354: }
2355: }
2356: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2357: print $fh $env{'form.'.$formname};
1.523 raeburn 2358: close($fh);
1.741 raeburn 2359: return $fullpath.'/'.$fname;
2360: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2361: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2362: '_'.$env{'user.domain'}.'/pending';
2363: my @parts=split(/\//,$filepath);
2364: my $fullpath = $perlvar{'lonDaemons'};
2365: for (my $i=0;$i<@parts;$i++) {
2366: $fullpath .= '/'.$parts[$i];
2367: if ((-e $fullpath)!=1) {
2368: mkdir($fullpath,0777);
2369: }
2370: }
2371: open(my $fh,'>'.$fullpath.'/'.$fname);
2372: print $fh $env{'form.'.$formname};
2373: close($fh);
2374: return $fullpath.'/'.$fname;
1.523 raeburn 2375: }
1.995 raeburn 2376: if ($subdir eq 'scantron') {
2377: $fname = 'scantron_orig_'.$fname;
2378: } else {
1.258 www 2379: # Create the directory if not present
1.995 raeburn 2380: $fname="$subdir/$fname";
2381: }
1.259 www 2382: if ($coursedoc) {
1.638 albertel 2383: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2384: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2385: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2386: return &finishuserfileupload($docuname,$docudom,
2387: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2388: $codebase,$thumbwidth,$thumbheight,
2389: $resizewidth,$resizeheight);
1.481 raeburn 2390: } else {
1.620 albertel 2391: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2392: return &process_coursefile('uploaddoc',$docuname,$docudom,
2393: $fname,$formname,$parser,
2394: $allfiles,$codebase);
1.481 raeburn 2395: }
1.719 banghart 2396: } elsif (defined($destuname)) {
2397: my $docuname=$destuname;
2398: my $docudom=$destudom;
1.860 raeburn 2399: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2400: $parser,$allfiles,$codebase,
1.1051 raeburn 2401: $thumbwidth,$thumbheight,
2402: $resizewidth,$resizeheight);
1.719 banghart 2403:
1.259 www 2404: } else {
1.638 albertel 2405: my $docuname=$env{'user.name'};
2406: my $docudom=$env{'user.domain'};
1.714 raeburn 2407: if (exists($env{'form.group'})) {
2408: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2409: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2410: }
1.860 raeburn 2411: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2412: $parser,$allfiles,$codebase,
1.1051 raeburn 2413: $thumbwidth,$thumbheight,
2414: $resizewidth,$resizeheight);
1.259 www 2415: }
1.271 www 2416: }
2417:
2418: sub finishuserfileupload {
1.860 raeburn 2419: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2420: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2421: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2422: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2423:
1.860 raeburn 2424: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2425: $file=$fname;
2426: if ($fname=~m|/|) {
2427: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2428: $path.=$fnamepath.'/';
2429: }
1.259 www 2430: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2431: my $count;
2432: for ($count=4;$count<=$#parts;$count++) {
2433: $filepath.="/$parts[$count]";
2434: if ((-e $filepath)!=1) {
2435: mkdir($filepath,0777);
2436: }
2437: }
1.984 neumanie 2438:
1.258 www 2439: # Save the file
2440: {
1.701 albertel 2441: if (!open(FH,'>'.$filepath.'/'.$file)) {
2442: &logthis('Failed to create '.$filepath.'/'.$file);
2443: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2444: return '/adm/notfound.html';
2445: }
2446: if (!print FH ($env{'form.'.$formname})) {
2447: &logthis('Failed to write to '.$filepath.'/'.$file);
2448: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2449: return '/adm/notfound.html';
2450: }
1.570 albertel 2451: close(FH);
1.1051 raeburn 2452: if ($resizewidth && $resizeheight) {
2453: my $mm = new File::MMagic;
2454: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2455: if ($mime_type =~ m{^image/}) {
2456: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2457: }
1.977 amueller 2458: }
1.258 www 2459: }
1.637 raeburn 2460: if ($parser eq 'parse') {
1.1024 raeburn 2461: my $mm = new File::MMagic;
2462: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2463: if ($mime_type eq 'text/html') {
2464: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2465: $allfiles,$codebase);
2466: unless ($parse_result eq 'ok') {
2467: &logthis('Failed to parse '.$filepath.$file.
2468: ' for embedded media: '.$parse_result);
2469: }
1.637 raeburn 2470: }
2471: }
1.860 raeburn 2472: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2473: my $input = $filepath.'/'.$file;
2474: my $output = $filepath.'/'.'tn-'.$file;
2475: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2476: system("convert -sample $thumbsize $input $output");
2477: if (-e $filepath.'/'.'tn-'.$file) {
2478: $fetchthumb = 1;
2479: }
2480: }
1.858 raeburn 2481:
1.259 www 2482: # Notify homeserver to grep it
2483: #
1.984 neumanie 2484: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2485: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2486: if ($fetchresult eq 'ok') {
1.860 raeburn 2487: if ($fetchthumb) {
2488: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2489: if ($thumbresult ne 'ok') {
2490: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2491: $docuhome.': '.$thumbresult);
2492: }
2493: }
1.259 www 2494: #
1.258 www 2495: # Return the URL to it
1.494 albertel 2496: return '/uploaded/'.$path.$file;
1.263 www 2497: } else {
1.494 albertel 2498: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2499: ': '.$fetchresult);
1.263 www 2500: return '/adm/notfound.html';
1.858 raeburn 2501: }
1.493 albertel 2502: }
2503:
1.637 raeburn 2504: sub extract_embedded_items {
1.961 raeburn 2505: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2506: my @state = ();
2507: my %javafiles = (
2508: codebase => '',
2509: code => '',
2510: archive => ''
2511: );
2512: my %mediafiles = (
2513: src => '',
2514: movie => '',
2515: );
1.648 raeburn 2516: my $p;
2517: if ($content) {
2518: $p = HTML::LCParser->new($content);
2519: } else {
1.961 raeburn 2520: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2521: }
1.641 albertel 2522: while (my $t=$p->get_token()) {
1.640 albertel 2523: if ($t->[0] eq 'S') {
2524: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2525: push(@state, $tagname);
1.648 raeburn 2526: if (lc($tagname) eq 'allow') {
2527: &add_filetype($allfiles,$attr->{'src'},'src');
2528: }
1.640 albertel 2529: if (lc($tagname) eq 'img') {
2530: &add_filetype($allfiles,$attr->{'src'},'src');
2531: }
1.886 albertel 2532: if (lc($tagname) eq 'a') {
2533: &add_filetype($allfiles,$attr->{'href'},'href');
2534: }
1.645 raeburn 2535: if (lc($tagname) eq 'script') {
2536: if ($attr->{'archive'} =~ /\.jar$/i) {
2537: &add_filetype($allfiles,$attr->{'archive'},'archive');
2538: } else {
2539: &add_filetype($allfiles,$attr->{'src'},'src');
2540: }
2541: }
2542: if (lc($tagname) eq 'link') {
2543: if (lc($attr->{'rel'}) eq 'stylesheet') {
2544: &add_filetype($allfiles,$attr->{'href'},'href');
2545: }
2546: }
1.640 albertel 2547: if (lc($tagname) eq 'object' ||
2548: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2549: foreach my $item (keys(%javafiles)) {
2550: $javafiles{$item} = '';
2551: }
2552: }
2553: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2554: my $name = lc($attr->{'name'});
2555: foreach my $item (keys(%javafiles)) {
2556: if ($name eq $item) {
2557: $javafiles{$item} = $attr->{'value'};
2558: last;
2559: }
2560: }
2561: foreach my $item (keys(%mediafiles)) {
2562: if ($name eq $item) {
2563: &add_filetype($allfiles, $attr->{'value'}, 'value');
2564: last;
2565: }
2566: }
2567: }
2568: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2569: foreach my $item (keys(%javafiles)) {
2570: if ($attr->{$item}) {
2571: $javafiles{$item} = $attr->{$item};
2572: last;
2573: }
2574: }
2575: foreach my $item (keys(%mediafiles)) {
2576: if ($attr->{$item}) {
2577: &add_filetype($allfiles,$attr->{$item},$item);
2578: last;
2579: }
2580: }
2581: }
2582: } elsif ($t->[0] eq 'E') {
2583: my ($tagname) = ($t->[1]);
2584: if ($javafiles{'codebase'} ne '') {
2585: $javafiles{'codebase'} .= '/';
2586: }
2587: if (lc($tagname) eq 'applet' ||
2588: lc($tagname) eq 'object' ||
2589: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2590: ) {
2591: foreach my $item (keys(%javafiles)) {
2592: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2593: my $file=$javafiles{'codebase'}.$javafiles{$item};
2594: &add_filetype($allfiles,$file,$item);
2595: }
2596: }
2597: }
2598: pop @state;
2599: }
2600: }
1.637 raeburn 2601: return 'ok';
2602: }
2603:
1.639 albertel 2604: sub add_filetype {
2605: my ($allfiles,$file,$type)=@_;
2606: if (exists($allfiles->{$file})) {
2607: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2608: push(@{$allfiles->{$file}}, &escape($type));
2609: }
2610: } else {
2611: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2612: }
2613: }
2614:
1.493 albertel 2615: sub removeuploadedurl {
1.984 neumanie 2616: my ($url)=@_;
2617: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2618: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2619: }
2620:
2621: sub removeuserfile {
2622: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2623: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2624: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2625: if ($result eq 'ok') {
1.798 raeburn 2626: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2627: my $metafile = $fname.'.meta';
2628: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2629: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2630: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2631: my $sqlresult =
1.823 albertel 2632: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2633: 'portfolio_metadata',$group,
2634: 'delete');
1.798 raeburn 2635: }
2636: }
2637: return $result;
1.257 www 2638: }
1.15 www 2639:
1.530 albertel 2640: sub mkdiruserfile {
2641: my ($docuname,$docudom,$dir)=@_;
2642: my $home=&homeserver($docuname,$docudom);
2643: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2644: }
2645:
1.531 albertel 2646: sub renameuserfile {
2647: my ($docuname,$docudom,$old,$new)=@_;
2648: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2649: my $result = &reply("renameuserfile:$docudom:$docuname:".
2650: &escape("$old").':'.&escape("$new"),$home);
2651: if ($result eq 'ok') {
2652: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2653: my $oldmeta = $old.'.meta';
2654: my $newmeta = $new.'.meta';
2655: my $metaresult =
2656: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2657: my $url = "/uploaded/$docudom/$docuname/$old";
2658: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2659: my $sqlresult =
1.823 albertel 2660: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2661: 'portfolio_metadata',$group,
2662: 'delete');
1.798 raeburn 2663: }
2664: }
2665: return $result;
1.531 albertel 2666: }
2667:
1.14 www 2668: # ------------------------------------------------------------------------- Log
2669:
2670: sub log {
2671: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2672: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2673: }
2674:
2675: # ------------------------------------------------------------------ Course Log
1.352 www 2676: #
2677: # This routine flushes several buffers of non-mission-critical nature
2678: #
1.157 www 2679:
2680: sub flushcourselogs {
1.352 www 2681: &logthis('Flushing log buffers');
2682: #
2683: # course logs
2684: # This is a log of all transactions in a course, which can be used
2685: # for data mining purposes
2686: #
2687: # It also collects the courseid database, which lists last transaction
2688: # times and course titles for all courseids
2689: #
2690: my %courseidbuffer=();
1.921 raeburn 2691: foreach my $crsid (keys(%courselogs)) {
1.352 www 2692: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2693: &escape($courselogs{$crsid}),
2694: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2695: delete $courselogs{$crsid};
2696: } else {
2697: &logthis('Failed to flush log buffer for '.$crsid);
2698: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2699: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2700: " exceeded maximum size, deleting.</font>");
2701: delete $courselogs{$crsid};
2702: }
1.352 www 2703: }
1.920 raeburn 2704: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2705: 'description' => $coursedescrbuf{$crsid},
2706: 'inst_code' => $courseinstcodebuf{$crsid},
2707: 'type' => $coursetypebuf{$crsid},
2708: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2709: };
1.191 harris41 2710: }
1.352 www 2711: #
2712: # Write course id database (reverse lookup) to homeserver of courses
2713: # Is used in pickcourse
2714: #
1.840 albertel 2715: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2716: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2717: $courseidbuffer{$crs_home},
2718: $crs_home,'timeonly');
1.352 www 2719: }
2720: #
2721: # File accesses
2722: # Writes to the dynamic metadata of resources to get hit counts, etc.
2723: #
1.449 matthew 2724: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2725: if ($entry =~ /___count$/) {
2726: my ($dom,$name);
1.807 albertel 2727: ($dom,$name,undef)=
1.811 albertel 2728: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2729: if (! defined($dom) || $dom eq '' ||
2730: ! defined($name) || $name eq '') {
1.620 albertel 2731: my $cid = $env{'request.course.id'};
2732: $dom = $env{'request.'.$cid.'.domain'};
2733: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2734: }
1.450 matthew 2735: my $value = $accesshash{$entry};
2736: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2737: my %temphash=($url => $value);
1.449 matthew 2738: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2739: if ($result eq 'ok') {
2740: delete $accesshash{$entry};
2741: } elsif ($result eq 'unknown_cmd') {
2742: # Target server has old code running on it.
1.450 matthew 2743: my %temphash=($entry => $value);
1.449 matthew 2744: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2745: delete $accesshash{$entry};
2746: }
2747: }
2748: } else {
1.811 albertel 2749: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2750: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2751: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2752: delete $accesshash{$entry};
2753: }
1.185 www 2754: }
1.191 harris41 2755: }
1.352 www 2756: #
2757: # Roles
2758: # Reverse lookup of user roles for course faculty/staff and co-authorship
2759: #
1.800 albertel 2760: foreach my $entry (keys(%userrolehash)) {
1.351 www 2761: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2762: split(/\:/,$entry);
2763: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2764: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2765: $rudom,$runame) eq 'ok') {
2766: delete $userrolehash{$entry};
2767: }
2768: }
1.662 raeburn 2769: #
2770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2771: #
2772: my %domrolebuffer = ();
1.1000 raeburn 2773: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2774: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2775: if ($domrolebuffer{$rudom}) {
2776: $domrolebuffer{$rudom}.='&'.&escape($entry).
2777: '='.&escape($domainrolehash{$entry});
2778: } else {
2779: $domrolebuffer{$rudom}.=&escape($entry).
2780: '='.&escape($domainrolehash{$entry});
2781: }
2782: delete $domainrolehash{$entry};
2783: }
2784: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2785: my %servers = &get_servers($dom,'library');
2786: foreach my $tryserver (keys(%servers)) {
2787: unless (&reply('domroleput:'.$dom.':'.
2788: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2789: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2790: }
1.662 raeburn 2791: }
2792: }
1.186 www 2793: $dumpcount++;
1.157 www 2794: }
2795:
2796: sub courselog {
2797: my $what=shift;
1.158 www 2798: $what=time.':'.$what;
1.620 albertel 2799: unless ($env{'request.course.id'}) { return ''; }
2800: $coursedombuf{$env{'request.course.id'}}=
2801: $env{'course.'.$env{'request.course.id'}.'.domain'};
2802: $coursenumbuf{$env{'request.course.id'}}=
2803: $env{'course.'.$env{'request.course.id'}.'.num'};
2804: $coursehombuf{$env{'request.course.id'}}=
2805: $env{'course.'.$env{'request.course.id'}.'.home'};
2806: $coursedescrbuf{$env{'request.course.id'}}=
2807: $env{'course.'.$env{'request.course.id'}.'.description'};
2808: $courseinstcodebuf{$env{'request.course.id'}}=
2809: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2810: $courseownerbuf{$env{'request.course.id'}}=
2811: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2812: $coursetypebuf{$env{'request.course.id'}}=
2813: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2814: if (defined $courselogs{$env{'request.course.id'}}) {
2815: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2816: } else {
1.620 albertel 2817: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2818: }
1.620 albertel 2819: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2820: &flushcourselogs();
2821: }
1.158 www 2822: }
2823:
2824: sub courseacclog {
2825: my $fnsymb=shift;
1.620 albertel 2826: unless ($env{'request.course.id'}) { return ''; }
2827: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2828: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2829: $what.=':POST';
1.583 matthew 2830: # FIXME: Probably ought to escape things....
1.800 albertel 2831: foreach my $key (keys(%env)) {
2832: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2833: my $formitem = $1;
2834: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2835: $what.=':'.$formitem.'='.$env{$key};
2836: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2837: $what.=':'.$formitem.'='.$env{$key};
2838: }
1.158 www 2839: }
1.191 harris41 2840: }
1.583 matthew 2841: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2842: # FIXME: We should not be depending on a form parameter that someone
2843: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2844: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2845: $what.= ':POST';
2846: # FIXME: Probably ought to escape things....
2847: foreach my $element ('courseexp','crsfulltext','crsrelated',
2848: 'crsdiscuss') {
1.620 albertel 2849: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2850: }
2851: }
1.158 www 2852: }
2853: &courselog($what);
1.149 www 2854: }
2855:
1.185 www 2856: sub countacc {
2857: my $url=&declutter(shift);
1.458 matthew 2858: return if (! defined($url) || $url eq '');
1.620 albertel 2859: unless ($env{'request.course.id'}) { return ''; }
2860: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2861: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2862: $accesshash{$key}++;
1.185 www 2863: }
1.349 www 2864:
1.361 www 2865: sub linklog {
2866: my ($from,$to)=@_;
2867: $from=&declutter($from);
2868: $to=&declutter($to);
2869: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2870: $accesshash{$to.'___'.$from.'___goto'}=1;
2871: }
2872:
1.349 www 2873: sub userrolelog {
2874: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2875: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2876: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2877: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2878: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2879: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2880: $userrolehash
2881: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2882: =$tend.':'.$tstart;
1.662 raeburn 2883: }
1.898 albertel 2884: if (($env{'request.role'} =~ /dc\./) &&
2885: (($trole=~/^au/) || ($trole=~/^in/) ||
2886: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2887: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2888: ($trole=~/^co/))) {
1.898 albertel 2889: $userrolehash
2890: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2891: =$tend.':'.$tstart;
2892: }
1.662 raeburn 2893: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2894: ($trole=~/^li/) || ($trole=~/^li/) ||
2895: ($trole=~/^au/) || ($trole=~/^dg/) ||
2896: ($trole=~/^sc/)) {
2897: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2898: $domainrolehash
2899: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2900: = $tend.':'.$tstart;
2901: }
1.351 www 2902: }
2903:
1.957 raeburn 2904: sub courserolelog {
2905: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2906: if (($trole eq 'cc') || ($trole eq 'in') ||
2907: ($trole eq 'ep') || ($trole eq 'ad') ||
2908: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2909: ($trole=~/^cr/) || ($trole eq 'gr') ||
2910: ($trole eq 'co')) {
1.957 raeburn 2911: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2912: my $cdom = $1;
2913: my $cnum = $2;
2914: my $sec = $3;
2915: my $namespace = 'rolelog';
2916: my %storehash = (
2917: role => $trole,
2918: start => $tstart,
2919: end => $tend,
2920: selfenroll => $selfenroll,
2921: context => $context,
2922: );
2923: if ($trole eq 'gr') {
2924: $namespace = 'groupslog';
2925: $storehash{'group'} = $sec;
2926: } else {
2927: $storehash{'section'} = $sec;
2928: }
2929: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2930: if (($trole ne 'st') || ($sec ne '')) {
2931: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2932: }
1.957 raeburn 2933: }
2934: }
2935: return;
2936: }
2937:
1.351 www 2938: sub get_course_adv_roles {
1.948 raeburn 2939: my ($cid,$codes) = @_;
1.620 albertel 2940: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2941: my %coursehash=&coursedescription($cid);
1.988 raeburn 2942: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2943: my %nothide=();
1.800 albertel 2944: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2945: if ($user !~ /:/) {
2946: $nothide{join(':',split(/[\@]/,$user))}=1;
2947: } else {
2948: $nothide{$user}=1;
2949: }
1.470 www 2950: }
1.351 www 2951: my %returnhash=();
2952: my %dumphash=
2953: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2954: my $now=time;
1.997 raeburn 2955: my %privileged;
1.1000 raeburn 2956: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2957: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2958: if (($tstart) && ($tstart<0)) { next; }
2959: if (($tend) && ($tend<$now)) { next; }
2960: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2961: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2962: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2963: unless (ref($privileged{$domain}) eq 'HASH') {
2964: my %dompersonnel =
1.998 raeburn 2965: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2966: $privileged{$domain} = {};
2967: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2968: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2969: foreach my $user (keys(%{$dompersonnel{$server}})) {
2970: my ($trole,$uname,$udom) = split(/:/,$user);
2971: $privileged{$udom}{$uname} = 1;
2972: }
2973: }
2974: }
2975: }
2976: if ((exists($privileged{$domain}{$username})) &&
2977: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2978: if ($role eq 'cr') { next; }
1.948 raeburn 2979: if ($codes) {
2980: if ($section) { $role .= ':'.$section; }
2981: if ($returnhash{$role}) {
2982: $returnhash{$role}.=','.$username.':'.$domain;
2983: } else {
2984: $returnhash{$role}=$username.':'.$domain;
2985: }
1.351 www 2986: } else {
1.988 raeburn 2987: my $key=&plaintext($role,$crstype);
1.973 bisitz 2988: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2989: if ($returnhash{$key}) {
2990: $returnhash{$key}.=','.$username.':'.$domain;
2991: } else {
2992: $returnhash{$key}=$username.':'.$domain;
2993: }
1.351 www 2994: }
1.948 raeburn 2995: }
1.400 www 2996: return %returnhash;
2997: }
2998:
2999: sub get_my_roles {
1.937 raeburn 3000: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3001: unless (defined($uname)) { $uname=$env{'user.name'}; }
3002: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3003: my (%dumphash,%nothide);
1.858 raeburn 3004: if ($context eq 'userroles') {
3005: %dumphash = &dump('roles',$udom,$uname);
3006: } else {
3007: %dumphash=
1.400 www 3008: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3009: if ($hidepriv) {
3010: my %coursehash=&coursedescription($udom.'_'.$uname);
3011: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3012: if ($user !~ /:/) {
3013: $nothide{join(':',split(/[\@]/,$user))} = 1;
3014: } else {
3015: $nothide{$user} = 1;
3016: }
3017: }
3018: }
1.858 raeburn 3019: }
1.400 www 3020: my %returnhash=();
3021: my $now=time;
1.999 raeburn 3022: my %privileged;
1.800 albertel 3023: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3024: my ($role,$tend,$tstart);
3025: if ($context eq 'userroles') {
3026: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3027: } else {
3028: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3029: }
1.400 www 3030: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3031: my $status = 'active';
1.939 raeburn 3032: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3033: $status = 'previous';
3034: }
3035: if (($tstart) && ($now<$tstart)) {
3036: $status = 'future';
3037: }
3038: if (ref($types) eq 'ARRAY') {
3039: if (!grep(/^\Q$status\E$/,@{$types})) {
3040: next;
3041: }
3042: } else {
3043: if ($status ne 'active') {
3044: next;
3045: }
3046: }
1.867 raeburn 3047: my ($rolecode,$username,$domain,$section,$area);
3048: if ($context eq 'userroles') {
3049: ($area,$rolecode) = split(/_/,$entry);
3050: (undef,$domain,$username,$section) = split(/\//,$area);
3051: } else {
3052: ($role,$username,$domain,$section) = split(/\:/,$entry);
3053: }
1.832 raeburn 3054: if (ref($roledoms) eq 'ARRAY') {
3055: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3056: next;
3057: }
3058: }
3059: if (ref($roles) eq 'ARRAY') {
3060: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3061: if ($role =~ /^cr\//) {
3062: if (!grep(/^cr$/,@{$roles})) {
3063: next;
3064: }
3065: } else {
3066: next;
3067: }
1.832 raeburn 3068: }
1.867 raeburn 3069: }
1.937 raeburn 3070: if ($hidepriv) {
1.999 raeburn 3071: if ($context eq 'userroles') {
3072: if ((&privileged($username,$domain)) &&
3073: (!$nothide{$username.':'.$domain})) {
3074: next;
3075: }
3076: } else {
3077: unless (ref($privileged{$domain}) eq 'HASH') {
3078: my %dompersonnel =
3079: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3080: $privileged{$domain} = {};
3081: if (keys(%dompersonnel)) {
3082: foreach my $server (keys(%dompersonnel)) {
3083: if (ref($dompersonnel{$server}) eq 'HASH') {
3084: foreach my $user (keys(%{$dompersonnel{$server}})) {
3085: my ($trole,$uname,$udom) = split(/:/,$user);
3086: $privileged{$udom}{$uname} = $trole;
3087: }
3088: }
3089: }
3090: }
3091: }
3092: if (exists($privileged{$domain}{$username})) {
3093: if (!$nothide{$username.':'.$domain}) {
3094: next;
3095: }
3096: }
1.937 raeburn 3097: }
3098: }
1.933 raeburn 3099: if ($withsec) {
3100: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3101: $tstart.':'.$tend;
3102: } else {
3103: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3104: }
1.832 raeburn 3105: }
1.373 www 3106: return %returnhash;
1.399 www 3107: }
3108:
3109: # ----------------------------------------------------- Frontpage Announcements
3110: #
3111: #
3112:
3113: sub postannounce {
3114: my ($server,$text)=@_;
1.844 albertel 3115: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3116: unless ($text=~/\w/) { $text=''; }
3117: return &reply('setannounce:'.&escape($text),$server);
3118: }
3119:
3120: sub getannounce {
1.448 albertel 3121:
3122: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3123: my $announcement='';
1.800 albertel 3124: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3125: close($fh);
1.399 www 3126: if ($announcement=~/\w/) {
3127: return
3128: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3129: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3130: } else {
3131: return '';
3132: }
3133: } else {
3134: return '';
3135: }
1.351 www 3136: }
1.353 www 3137:
3138: # ---------------------------------------------------------- Course ID routines
3139: # Deal with domain's nohist_courseid.db files
3140: #
3141:
3142: sub courseidput {
1.921 raeburn 3143: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3144: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3145: my $outcome;
3146: if ($caller eq 'timeonly') {
3147: my $cids = '';
3148: foreach my $item (keys(%$storehash)) {
3149: $cids.=&escape($item).'&';
3150: }
3151: $cids=~s/\&$//;
3152: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3153: $coursehome);
3154: } else {
3155: my $items = '';
3156: foreach my $item (keys(%$storehash)) {
3157: $items.= &escape($item).'='.
3158: &freeze_escape($$storehash{$item}).'&';
3159: }
3160: $items=~s/\&$//;
3161: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3162: $coursehome);
1.918 raeburn 3163: }
3164: if ($outcome eq 'unknown_cmd') {
3165: my $what;
3166: foreach my $cid (keys(%$storehash)) {
3167: $what .= &escape($cid).'=';
1.921 raeburn 3168: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3169: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3170: }
3171: $what =~ s/\:$/&/;
3172: }
3173: $what =~ s/\&$//;
3174: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3175: } else {
3176: return $outcome;
3177: }
1.353 www 3178: }
3179:
3180: sub courseiddump {
1.921 raeburn 3181: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3182: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3183: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3184: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3185: my $as_hash = 1;
3186: my %returnhash;
3187: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3188: my %libserv = &all_library();
3189: foreach my $tryserver (keys(%libserv)) {
3190: if ( ( $hostidflag == 1
3191: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3192: || (!defined($hostidflag)) ) {
3193:
1.918 raeburn 3194: if (($domfilter eq '') ||
3195: (&host_domain($tryserver) eq $domfilter)) {
3196: my $rep =
3197: &reply('courseiddump:'.&host_domain($tryserver).':'.
3198: $sincefilter.':'.&escape($descfilter).':'.
3199: &escape($instcodefilter).':'.&escape($ownerfilter).
3200: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3201: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3202: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3203: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3204: &escape($cc_clone).':'.$cloneonly.':'.
3205: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3206: &escape($creationcontext).':'.$domcloner,
3207: $tryserver);
1.918 raeburn 3208: my @pairs=split(/\&/,$rep);
3209: foreach my $item (@pairs) {
3210: my ($key,$value)=split(/\=/,$item,2);
3211: $key = &unescape($key);
3212: next if ($key =~ /^error: 2 /);
3213: my $result = &thaw_unescape($value);
3214: if (ref($result) eq 'HASH') {
3215: $returnhash{$key}=$result;
3216: } else {
1.921 raeburn 3217: my @responses = split(/:/,$value);
3218: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3219: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3220: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3221: }
1.1008 raeburn 3222: }
1.353 www 3223: }
3224: }
3225: }
3226: }
3227: return %returnhash;
3228: }
3229:
1.1055 raeburn 3230: sub courselastaccess {
3231: my ($cdom,$cnum,$hostidref) = @_;
3232: my %returnhash;
3233: if ($cdom && $cnum) {
3234: my $chome = &homeserver($cnum,$cdom);
3235: if ($chome ne 'no_host') {
3236: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3237: &extract_lastaccess(\%returnhash,$rep);
3238: }
3239: } else {
3240: if (!$cdom) { $cdom=''; }
3241: my %libserv = &all_library();
3242: foreach my $tryserver (keys(%libserv)) {
3243: if (ref($hostidref) eq 'ARRAY') {
3244: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3245: }
3246: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3247: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3248: &extract_lastaccess(\%returnhash,$rep);
3249: }
3250: }
3251: }
3252: return %returnhash;
3253: }
3254:
3255: sub extract_lastaccess {
3256: my ($returnhash,$rep) = @_;
3257: if (ref($returnhash) eq 'HASH') {
3258: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3259: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3260: $rep eq '') {
3261: my @pairs=split(/\&/,$rep);
3262: foreach my $item (@pairs) {
3263: my ($key,$value)=split(/\=/,$item,2);
3264: $key = &unescape($key);
3265: next if ($key =~ /^error: 2 /);
3266: $returnhash->{$key} = &thaw_unescape($value);
3267: }
3268: }
3269: }
3270: return;
3271: }
3272:
1.658 raeburn 3273: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3274:
3275: sub dcmailput {
1.685 raeburn 3276: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3277: my $status = &Apache::lonnet::critical(
1.740 www 3278: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3279: &escape($message),$server);
1.662 raeburn 3280: return $status;
3281: }
3282:
1.658 raeburn 3283: sub dcmaildump {
3284: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3285: my %returnhash=();
1.846 albertel 3286:
3287: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3288: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3289: &escape($enddate).':';
3290: my @esc_senders=map { &escape($_)} @$senders;
3291: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3292: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3293: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3294: if (($key) && ($value)) {
3295: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3296: }
3297: }
3298: }
3299: return %returnhash;
3300: }
1.662 raeburn 3301: # ---------------------------------------------------------- Domain roles
3302:
3303: sub get_domain_roles {
3304: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3305: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3306: $startdate = '.';
3307: }
1.1018 raeburn 3308: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3309: $enddate = '.';
3310: }
1.922 raeburn 3311: my $rolelist;
3312: if (ref($roles) eq 'ARRAY') {
3313: $rolelist = join(':',@{$roles});
3314: }
1.662 raeburn 3315: my %personnel = ();
1.841 albertel 3316:
3317: my %servers = &get_servers($dom,'library');
3318: foreach my $tryserver (keys(%servers)) {
3319: %{$personnel{$tryserver}}=();
3320: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3321: &escape($startdate).':'.
3322: &escape($enddate).':'.
3323: &escape($rolelist), $tryserver))) {
3324: my ($key,$value) = split(/\=/,$line,2);
3325: if (($key) && ($value)) {
3326: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3327: }
3328: }
1.662 raeburn 3329: }
3330: return %personnel;
3331: }
1.658 raeburn 3332:
1.1057 www 3333: # ----------------------------------------------------------- Interval timing
1.149 www 3334:
1.504 albertel 3335: sub get_first_access {
3336: my ($type,$argsymb)=@_;
1.790 albertel 3337: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3338: if ($argsymb) { $symb=$argsymb; }
3339: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3340: if ($type eq 'course') {
3341: $res='course';
3342: } elsif ($type eq 'map') {
1.588 albertel 3343: $res=&symbread($map);
3344: } else {
3345: $res=$symb;
3346: }
3347: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3348: return $times{"$courseid\0$res"};
1.504 albertel 3349: }
3350:
3351: sub set_first_access {
3352: my ($type)=@_;
1.790 albertel 3353: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3354: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3355: if ($type eq 'course') {
3356: $res='course';
3357: } elsif ($type eq 'map') {
1.588 albertel 3358: $res=&symbread($map);
3359: } else {
3360: $res=$symb;
3361: }
3362: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3363: if (!$firstaccess) {
1.588 albertel 3364: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3365: }
3366: return 'already_set';
1.504 albertel 3367: }
3368:
1.110 www 3369: # --------------------------------------------- Set Expire Date for Spreadsheet
3370:
3371: sub expirespread {
3372: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3373: my $cid=$env{'request.course.id'};
1.110 www 3374: if ($cid) {
3375: my $now=time;
3376: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3377: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3378: $env{'course.'.$cid.'.num'}.
1.110 www 3379: ':nohist_expirationdates:'.
3380: &escape($key).'='.$now,
1.620 albertel 3381: $env{'course.'.$cid.'.home'})
1.110 www 3382: }
3383: return 'ok';
1.14 www 3384: }
3385:
1.109 www 3386: # ----------------------------------------------------- Devalidate Spreadsheets
3387:
3388: sub devalidate {
1.325 www 3389: my ($symb,$uname,$udom)=@_;
1.620 albertel 3390: my $cid=$env{'request.course.id'};
1.109 www 3391: if ($cid) {
1.391 matthew 3392: # delete the stored spreadsheets for
3393: # - the student level sheet of this user in course's homespace
3394: # - the assessment level sheet for this resource
3395: # for this user in user's homespace
1.553 albertel 3396: # - current conditional state info
1.325 www 3397: my $key=$uname.':'.$udom.':';
1.109 www 3398: my $status=
1.299 matthew 3399: &del('nohist_calculatedsheets',
1.391 matthew 3400: [$key.'studentcalc:'],
1.620 albertel 3401: $env{'course.'.$cid.'.domain'},
3402: $env{'course.'.$cid.'.num'})
1.133 albertel 3403: .' '.
3404: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3405: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3406: unless ($status eq 'ok ok') {
3407: &logthis('Could not devalidate spreadsheet '.
1.325 www 3408: $uname.' at '.$udom.' for '.
1.109 www 3409: $symb.': '.$status);
1.133 albertel 3410: }
1.553 albertel 3411: &delenv('user.state.'.$cid);
1.109 www 3412: }
3413: }
3414:
1.265 albertel 3415: sub get_scalar {
3416: my ($string,$end) = @_;
3417: my $value;
3418: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3419: $value = $1;
3420: } elsif ($$string =~ s/^([^&]*?)&//) {
3421: $value = $1;
3422: }
3423: return &unescape($value);
3424: }
3425:
3426: sub array2str {
3427: my (@array) = @_;
3428: my $result=&arrayref2str(\@array);
3429: $result=~s/^__ARRAY_REF__//;
3430: $result=~s/__END_ARRAY_REF__$//;
3431: return $result;
3432: }
3433:
1.204 albertel 3434: sub arrayref2str {
3435: my ($arrayref) = @_;
1.265 albertel 3436: my $result='__ARRAY_REF__';
1.204 albertel 3437: foreach my $elem (@$arrayref) {
1.265 albertel 3438: if(ref($elem) eq 'ARRAY') {
3439: $result.=&arrayref2str($elem).'&';
3440: } elsif(ref($elem) eq 'HASH') {
3441: $result.=&hashref2str($elem).'&';
3442: } elsif(ref($elem)) {
3443: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3444: } else {
3445: $result.=&escape($elem).'&';
3446: }
3447: }
3448: $result=~s/\&$//;
1.265 albertel 3449: $result .= '__END_ARRAY_REF__';
1.204 albertel 3450: return $result;
3451: }
3452:
1.168 albertel 3453: sub hash2str {
1.204 albertel 3454: my (%hash) = @_;
3455: my $result=&hashref2str(\%hash);
1.265 albertel 3456: $result=~s/^__HASH_REF__//;
3457: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3458: return $result;
3459: }
3460:
3461: sub hashref2str {
3462: my ($hashref)=@_;
1.265 albertel 3463: my $result='__HASH_REF__';
1.800 albertel 3464: foreach my $key (sort(keys(%$hashref))) {
3465: if (ref($key) eq 'ARRAY') {
3466: $result.=&arrayref2str($key).'=';
3467: } elsif (ref($key) eq 'HASH') {
3468: $result.=&hashref2str($key).'=';
3469: } elsif (ref($key)) {
1.265 albertel 3470: $result.='=';
1.800 albertel 3471: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3472: } else {
1.800 albertel 3473: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3474: }
3475:
1.800 albertel 3476: if(ref($hashref->{$key}) eq 'ARRAY') {
3477: $result.=&arrayref2str($hashref->{$key}).'&';
3478: } elsif(ref($hashref->{$key}) eq 'HASH') {
3479: $result.=&hashref2str($hashref->{$key}).'&';
3480: } elsif(ref($hashref->{$key})) {
1.265 albertel 3481: $result.='&';
1.800 albertel 3482: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3483: } else {
1.800 albertel 3484: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3485: }
3486: }
1.168 albertel 3487: $result=~s/\&$//;
1.265 albertel 3488: $result .= '__END_HASH_REF__';
1.168 albertel 3489: return $result;
3490: }
3491:
3492: sub str2hash {
1.265 albertel 3493: my ($string)=@_;
3494: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3495: return %$hash;
3496: }
3497:
3498: sub str2hashref {
1.168 albertel 3499: my ($string) = @_;
1.265 albertel 3500:
3501: my %hash;
3502:
3503: if($string !~ /^__HASH_REF__/) {
3504: if (! ($string eq '' || !defined($string))) {
3505: $hash{'error'}='Not hash reference';
3506: }
3507: return (\%hash, $string);
3508: }
3509:
3510: $string =~ s/^__HASH_REF__//;
3511:
3512: while($string !~ /^__END_HASH_REF__/) {
3513: #key
3514: my $key='';
3515: if($string =~ /^__HASH_REF__/) {
3516: ($key, $string)=&str2hashref($string);
3517: if(defined($key->{'error'})) {
3518: $hash{'error'}='Bad data';
3519: return (\%hash, $string);
3520: }
3521: } elsif($string =~ /^__ARRAY_REF__/) {
3522: ($key, $string)=&str2arrayref($string);
3523: if($key->[0] eq 'Array reference error') {
3524: $hash{'error'}='Bad data';
3525: return (\%hash, $string);
3526: }
3527: } else {
3528: $string =~ s/^(.*?)=//;
1.267 albertel 3529: $key=&unescape($1);
1.265 albertel 3530: }
3531: $string =~ s/^=//;
3532:
3533: #value
3534: my $value='';
3535: if($string =~ /^__HASH_REF__/) {
3536: ($value, $string)=&str2hashref($string);
3537: if(defined($value->{'error'})) {
3538: $hash{'error'}='Bad data';
3539: return (\%hash, $string);
3540: }
3541: } elsif($string =~ /^__ARRAY_REF__/) {
3542: ($value, $string)=&str2arrayref($string);
3543: if($value->[0] eq 'Array reference error') {
3544: $hash{'error'}='Bad data';
3545: return (\%hash, $string);
3546: }
3547: } else {
3548: $value=&get_scalar(\$string,'__END_HASH_REF__');
3549: }
3550: $string =~ s/^&//;
3551:
3552: $hash{$key}=$value;
1.204 albertel 3553: }
1.265 albertel 3554:
3555: $string =~ s/^__END_HASH_REF__//;
3556:
3557: return (\%hash, $string);
1.204 albertel 3558: }
3559:
3560: sub str2array {
1.265 albertel 3561: my ($string)=@_;
3562: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3563: return @$array;
3564: }
3565:
3566: sub str2arrayref {
1.204 albertel 3567: my ($string) = @_;
1.265 albertel 3568: my @array;
3569:
3570: if($string !~ /^__ARRAY_REF__/) {
3571: if (! ($string eq '' || !defined($string))) {
3572: $array[0]='Array reference error';
3573: }
3574: return (\@array, $string);
3575: }
3576:
3577: $string =~ s/^__ARRAY_REF__//;
3578:
3579: while($string !~ /^__END_ARRAY_REF__/) {
3580: my $value='';
3581: if($string =~ /^__HASH_REF__/) {
3582: ($value, $string)=&str2hashref($string);
3583: if(defined($value->{'error'})) {
3584: $array[0] ='Array reference error';
3585: return (\@array, $string);
3586: }
3587: } elsif($string =~ /^__ARRAY_REF__/) {
3588: ($value, $string)=&str2arrayref($string);
3589: if($value->[0] eq 'Array reference error') {
3590: $array[0] ='Array reference error';
3591: return (\@array, $string);
3592: }
3593: } else {
3594: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3595: }
3596: $string =~ s/^&//;
3597:
3598: push(@array, $value);
1.191 harris41 3599: }
1.265 albertel 3600:
3601: $string =~ s/^__END_ARRAY_REF__//;
3602:
3603: return (\@array, $string);
1.168 albertel 3604: }
3605:
1.167 albertel 3606: # -------------------------------------------------------------------Temp Store
3607:
1.168 albertel 3608: sub tmpreset {
3609: my ($symb,$namespace,$domain,$stuname) = @_;
3610: if (!$symb) {
3611: $symb=&symbread();
1.620 albertel 3612: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3613: }
3614: $symb=escape($symb);
3615:
1.620 albertel 3616: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3617: $namespace=~s/\//\_/g;
3618: $namespace=~s/\W//g;
3619:
1.620 albertel 3620: if (!$domain) { $domain=$env{'user.domain'}; }
3621: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3622: if ($domain eq 'public' && $stuname eq 'public') {
3623: $stuname=$ENV{'REMOTE_ADDR'};
3624: }
1.168 albertel 3625: my $path=$perlvar{'lonDaemons'}.'/tmp';
3626: my %hash;
3627: if (tie(%hash,'GDBM_File',
3628: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3629: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3630: foreach my $key (keys(%hash)) {
1.180 albertel 3631: if ($key=~ /:$symb/) {
1.168 albertel 3632: delete($hash{$key});
3633: }
3634: }
3635: }
3636: }
3637:
1.167 albertel 3638: sub tmpstore {
1.168 albertel 3639: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3640:
3641: if (!$symb) {
3642: $symb=&symbread();
1.620 albertel 3643: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3644: }
3645: $symb=escape($symb);
3646:
3647: if (!$namespace) {
3648: # I don't think we would ever want to store this for a course.
3649: # it seems this will only be used if we don't have a course.
1.620 albertel 3650: #$namespace=$env{'request.course.id'};
1.168 albertel 3651: #if (!$namespace) {
1.620 albertel 3652: $namespace=$env{'request.state'};
1.168 albertel 3653: #}
3654: }
3655: $namespace=~s/\//\_/g;
3656: $namespace=~s/\W//g;
1.620 albertel 3657: if (!$domain) { $domain=$env{'user.domain'}; }
3658: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3659: if ($domain eq 'public' && $stuname eq 'public') {
3660: $stuname=$ENV{'REMOTE_ADDR'};
3661: }
1.168 albertel 3662: my $now=time;
3663: my %hash;
3664: my $path=$perlvar{'lonDaemons'}.'/tmp';
3665: if (tie(%hash,'GDBM_File',
3666: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3667: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3668: $hash{"version:$symb"}++;
3669: my $version=$hash{"version:$symb"};
3670: my $allkeys='';
3671: foreach my $key (keys(%$storehash)) {
3672: $allkeys.=$key.':';
1.591 albertel 3673: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3674: }
3675: $hash{"$version:$symb:timestamp"}=$now;
3676: $allkeys.='timestamp';
3677: $hash{"$version:keys:$symb"}=$allkeys;
3678: if (untie(%hash)) {
3679: return 'ok';
3680: } else {
3681: return "error:$!";
3682: }
3683: } else {
3684: return "error:$!";
3685: }
3686: }
1.167 albertel 3687:
1.168 albertel 3688: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3689:
1.168 albertel 3690: sub tmprestore {
3691: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3692:
1.168 albertel 3693: if (!$symb) {
3694: $symb=&symbread();
1.620 albertel 3695: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3696: }
3697: $symb=escape($symb);
3698:
1.620 albertel 3699: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3700:
1.620 albertel 3701: if (!$domain) { $domain=$env{'user.domain'}; }
3702: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3703: if ($domain eq 'public' && $stuname eq 'public') {
3704: $stuname=$ENV{'REMOTE_ADDR'};
3705: }
1.168 albertel 3706: my %returnhash;
3707: $namespace=~s/\//\_/g;
3708: $namespace=~s/\W//g;
3709: my %hash;
3710: my $path=$perlvar{'lonDaemons'}.'/tmp';
3711: if (tie(%hash,'GDBM_File',
3712: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3713: &GDBM_READER(),0640)) {
1.168 albertel 3714: my $version=$hash{"version:$symb"};
3715: $returnhash{'version'}=$version;
3716: my $scope;
3717: for ($scope=1;$scope<=$version;$scope++) {
3718: my $vkeys=$hash{"$scope:keys:$symb"};
3719: my @keys=split(/:/,$vkeys);
3720: my $key;
3721: $returnhash{"$scope:keys"}=$vkeys;
3722: foreach $key (@keys) {
1.591 albertel 3723: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3724: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3725: }
3726: }
1.168 albertel 3727: if (!(untie(%hash))) {
3728: return "error:$!";
3729: }
3730: } else {
3731: return "error:$!";
3732: }
3733: return %returnhash;
1.167 albertel 3734: }
3735:
1.9 www 3736: # ----------------------------------------------------------------------- Store
3737:
3738: sub store {
1.124 www 3739: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3740: my $home='';
3741:
1.168 albertel 3742: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3743:
1.213 www 3744: $symb=&symbclean($symb);
1.122 albertel 3745: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3746:
1.620 albertel 3747: if (!$domain) { $domain=$env{'user.domain'}; }
3748: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3749:
3750: &devalidate($symb,$stuname,$domain);
1.109 www 3751:
3752: $symb=escape($symb);
1.187 www 3753: if (!$namespace) {
1.620 albertel 3754: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3755: return '';
3756: }
3757: }
1.620 albertel 3758: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3759:
3760: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3761: $$storehash{'host'}=$perlvar{'lonHostID'};
3762:
1.12 www 3763: my $namevalue='';
1.800 albertel 3764: foreach my $key (keys(%$storehash)) {
3765: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3766: }
1.12 www 3767: $namevalue=~s/\&$//;
1.187 www 3768: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3769: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3770: }
3771:
1.47 www 3772: # -------------------------------------------------------------- Critical Store
3773:
3774: sub cstore {
1.124 www 3775: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3776: my $home='';
3777:
1.168 albertel 3778: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3779:
1.213 www 3780: $symb=&symbclean($symb);
1.122 albertel 3781: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3782:
1.620 albertel 3783: if (!$domain) { $domain=$env{'user.domain'}; }
3784: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3785:
3786: &devalidate($symb,$stuname,$domain);
1.109 www 3787:
3788: $symb=escape($symb);
1.187 www 3789: if (!$namespace) {
1.620 albertel 3790: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3791: return '';
3792: }
3793: }
1.620 albertel 3794: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3795:
3796: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3797: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3798:
1.47 www 3799: my $namevalue='';
1.800 albertel 3800: foreach my $key (keys(%$storehash)) {
3801: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3802: }
1.47 www 3803: $namevalue=~s/\&$//;
1.187 www 3804: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3805: return critical
3806: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3807: }
3808:
1.9 www 3809: # --------------------------------------------------------------------- Restore
3810:
3811: sub restore {
1.124 www 3812: my ($symb,$namespace,$domain,$stuname) = @_;
3813: my $home='';
3814:
1.168 albertel 3815: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3816:
1.122 albertel 3817: if (!$symb) {
3818: unless ($symb=escape(&symbread())) { return ''; }
3819: } else {
1.213 www 3820: $symb=&escape(&symbclean($symb));
1.122 albertel 3821: }
1.188 www 3822: if (!$namespace) {
1.620 albertel 3823: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3824: return '';
3825: }
3826: }
1.620 albertel 3827: if (!$domain) { $domain=$env{'user.domain'}; }
3828: if (!$stuname) { $stuname=$env{'user.name'}; }
3829: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3830: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3831:
1.12 www 3832: my %returnhash=();
1.800 albertel 3833: foreach my $line (split(/\&/,$answer)) {
3834: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3835: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3836: }
1.75 www 3837: my $version;
3838: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3839: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3840: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3841: }
1.75 www 3842: }
1.13 www 3843: return %returnhash;
1.34 www 3844: }
3845:
3846: # ---------------------------------------------------------- Course Description
3847:
3848: sub coursedescription {
1.731 albertel 3849: my ($courseid,$args)=@_;
1.34 www 3850: $courseid=~s/^\///;
1.49 www 3851: $courseid=~s/\_/\//g;
1.34 www 3852: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3853: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3854: my $normalid=$cdomain.'_'.$cnum;
3855: # need to always cache even if we get errors otherwise we keep
3856: # trying and trying and trying to get the course description.
3857: my %envhash=();
3858: my %returnhash=();
1.731 albertel 3859:
3860: my $expiretime=600;
3861: if ($env{'request.course.id'} eq $normalid) {
3862: $expiretime=120;
3863: }
3864:
3865: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3866: if (!$args->{'freshen_cache'}
3867: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3868: foreach my $key (keys(%env)) {
3869: next if ($key !~ /^\Q$prefix\E(.*)/);
3870: my ($setting) = $1;
3871: $returnhash{$setting} = $env{$key};
3872: }
3873: return %returnhash;
3874: }
3875:
3876: # get the data agin
3877: if (!$args->{'one_time'}) {
3878: $envhash{'course.'.$normalid.'.last_cache'}=time;
3879: }
1.811 albertel 3880:
1.34 www 3881: if ($chome ne 'no_host') {
1.302 albertel 3882: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3883: if (!exists($returnhash{'con_lost'})) {
3884: $returnhash{'home'}= $chome;
3885: $returnhash{'domain'} = $cdomain;
3886: $returnhash{'num'} = $cnum;
1.741 raeburn 3887: if (!defined($returnhash{'type'})) {
3888: $returnhash{'type'} = 'Course';
3889: }
1.130 albertel 3890: while (my ($name,$value) = each %returnhash) {
1.53 www 3891: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3892: }
1.270 www 3893: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3894: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3895: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3896: $envhash{'course.'.$normalid.'.home'}=$chome;
3897: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3898: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3899: }
3900: }
1.731 albertel 3901: if (!$args->{'one_time'}) {
1.949 raeburn 3902: &appenv(\%envhash);
1.731 albertel 3903: }
1.302 albertel 3904: return %returnhash;
1.461 www 3905: }
3906:
3907: # -------------------------------------------------See if a user is privileged
3908:
3909: sub privileged {
3910: my ($username,$domain)=@_;
3911: my $rolesdump=&reply("dump:$domain:$username:roles",
3912: &homeserver($username,$domain));
1.1033 raeburn 3913: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3914: ($rolesdump =~ /^error:/)) {
3915: return 0;
3916: }
1.461 www 3917: my $now=time;
3918: if ($rolesdump ne '') {
1.800 albertel 3919: foreach my $entry (split(/&/,$rolesdump)) {
3920: if ($entry!~/^rolesdef_/) {
3921: my ($area,$role)=split(/=/,$entry);
1.461 www 3922: $area=~s/\_\w\w$//;
3923: my ($trole,$tend,$tstart)=split(/_/,$role);
3924: if (($trole eq 'dc') || ($trole eq 'su')) {
3925: my $active=1;
3926: if ($tend) {
3927: if ($tend<$now) { $active=0; }
3928: }
3929: if ($tstart) {
3930: if ($tstart>$now) { $active=0; }
3931: }
3932: if ($active) { return 1; }
3933: }
3934: }
3935: }
3936: }
3937: return 0;
1.9 www 3938: }
1.1 albertel 3939:
1.103 harris41 3940: # -------------------------------------------------------- Get user privileges
1.11 www 3941:
3942: sub rolesinit {
3943: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3944: my $now=time;
3945: my %userroles = ('user.login.time' => $now);
1.11 www 3946: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3947: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3948: ($rolesdump =~ /^error:/)) {
3949: return \%userroles;
3950: }
1.11 www 3951: my %allroles=();
1.678 raeburn 3952: my %allgroups=();
3953: my $group_privs;
1.11 www 3954:
3955: if ($rolesdump ne '') {
1.800 albertel 3956: foreach my $entry (split(/&/,$rolesdump)) {
3957: if ($entry!~/^rolesdef_/) {
3958: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3959: $area=~s/\_\w\w$//;
1.678 raeburn 3960: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3961: if ($role=~/^cr/) {
1.807 albertel 3962: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3963: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3964: ($tend,$tstart)=split('_',$trest);
3965: } else {
3966: $trole=$role;
3967: }
1.678 raeburn 3968: } elsif ($role =~ m|^gr/|) {
3969: ($trole,$tend,$tstart) = split(/_/,$role);
3970: ($trole,$group_privs) = split(/\//,$trole);
3971: $group_privs = &unescape($group_privs);
1.587 albertel 3972: } else {
3973: ($trole,$tend,$tstart)=split(/_/,$role);
3974: }
1.743 albertel 3975: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3976: $username);
3977: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3978: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3979: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3980: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3981: my $spec=$trole.'.'.$area;
3982: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3983: if ($trole =~ /^cr\//) {
1.567 raeburn 3984: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3985: } elsif ($trole eq 'gr') {
3986: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3987: } else {
1.567 raeburn 3988: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3989: }
1.12 www 3990: }
1.662 raeburn 3991: }
1.191 harris41 3992: }
1.743 albertel 3993: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3994: $userroles{'user.adv'} = $adv;
3995: $userroles{'user.author'} = $author;
1.620 albertel 3996: $env{'user.adv'}=$adv;
1.11 www 3997: }
1.743 albertel 3998: return \%userroles;
1.11 www 3999: }
4000:
1.567 raeburn 4001: sub set_arearole {
4002: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4003: # log the associated role with the area
4004: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4005: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4006: }
4007:
4008: sub custom_roleprivs {
4009: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4010: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4011: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4012: if (&hostname($homsvr) ne '') {
1.567 raeburn 4013: my ($rdummy,$roledef)=
4014: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4015: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4016: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4017: if (defined($syspriv)) {
1.1043 raeburn 4018: if ($trest =~ /^$match_community$/) {
4019: $syspriv =~ s/bre\&S//;
4020: }
1.567 raeburn 4021: $$allroles{'cm./'}.=':'.$syspriv;
4022: $$allroles{$spec.'./'}.=':'.$syspriv;
4023: }
4024: if ($tdomain ne '') {
4025: if (defined($dompriv)) {
4026: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4027: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4028: }
4029: if (($trest ne '') && (defined($coursepriv))) {
4030: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4031: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4032: }
4033: }
4034: }
4035: }
4036: }
4037:
1.678 raeburn 4038: sub group_roleprivs {
4039: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4040: my $access = 1;
4041: my $now = time;
4042: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4043: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4044: if ($access) {
1.811 albertel 4045: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4046: $$allgroups{$course}{$group} .=':'.$group_privs;
4047: }
4048: }
1.567 raeburn 4049:
4050: sub standard_roleprivs {
4051: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4052: if (defined($pr{$trole.':s'})) {
4053: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4054: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4055: }
4056: if ($tdomain ne '') {
4057: if (defined($pr{$trole.':d'})) {
4058: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4059: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4060: }
4061: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4062: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4063: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4064: }
4065: }
4066: }
4067:
4068: sub set_userprivs {
1.1064 raeburn 4069: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4070: my $author=0;
4071: my $adv=0;
1.678 raeburn 4072: my %grouproles = ();
4073: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4074: my @groupkeys;
1.1000 raeburn 4075: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4076: push(@groupkeys,$role);
4077: }
4078: if (ref($groups_roles) eq 'HASH') {
4079: foreach my $key (keys(%{$groups_roles})) {
4080: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4081: push(@groupkeys,$key);
4082: }
4083: }
4084: }
4085: if (@groupkeys > 0) {
4086: foreach my $role (@groupkeys) {
4087: my ($trole,$area,$sec,$extendedarea);
4088: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4089: $trole = $1;
4090: $area = $2;
4091: $sec = $3;
4092: $extendedarea = $area.$sec;
4093: if (exists($$allgroups{$area})) {
4094: foreach my $group (keys(%{$$allgroups{$area}})) {
4095: my $spec = $trole.'.'.$extendedarea;
4096: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4097: $$allgroups{$area}{$group};
1.1064 raeburn 4098: }
1.678 raeburn 4099: }
4100: }
4101: }
4102: }
4103: }
1.800 albertel 4104: foreach my $group (keys(%grouproles)) {
4105: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4106: }
1.800 albertel 4107: foreach my $role (keys(%{$allroles})) {
4108: my %thesepriv;
1.941 raeburn 4109: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4110: foreach my $item (split(/:/,$$allroles{$role})) {
4111: if ($item ne '') {
4112: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4113: if ($restrictions eq '') {
4114: $thesepriv{$privilege}='F';
4115: } elsif ($thesepriv{$privilege} ne 'F') {
4116: $thesepriv{$privilege}.=$restrictions;
4117: }
4118: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4119: }
4120: }
4121: my $thesestr='';
1.800 albertel 4122: foreach my $priv (keys(%thesepriv)) {
4123: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4124: }
4125: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4126: }
4127: return ($author,$adv);
4128: }
4129:
1.994 raeburn 4130: sub role_status {
1.1002 raeburn 4131: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4132: my @pwhere = ();
4133: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4134: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4135: unless (!defined($$role) || $$role eq '') {
4136: $$where=join('.',@pwhere);
4137: $$trolecode=$$role.'.'.$$where;
4138: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4139: $$tstatus='is';
4140: if ($$tstart && $$tstart>$then) {
4141: $$tstatus='future';
1.1034 raeburn 4142: if ($$tstart<$now) {
4143: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4144: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4145: my (%allroles,%allgroups,$group_privs,
4146: %groups_roles,@rolecodes);
1.1002 raeburn 4147: my %userroles = (
4148: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4149: );
1.1064 raeburn 4150: @rolecodes = ('cm');
1.1002 raeburn 4151: my $spec=$$role.'.'.$$where;
4152: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4153: if ($$role =~ /^cr\//) {
4154: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4155: push(@rolecodes,'cr');
1.1002 raeburn 4156: } elsif ($$role eq 'gr') {
1.1064 raeburn 4157: push(@rolecodes,$$role);
1.1002 raeburn 4158: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4159: $env{'user.name'});
1.1064 raeburn 4160: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4161: (undef,my $group_privs) = split(/\//,$trole);
4162: $group_privs = &unescape($group_privs);
4163: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4164: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4165: if (keys(%course_roles) > 0) {
4166: my ($tnum) = ($trest =~ /^($match_courseid)/);
4167: if ($tdomain ne '' && $tnum ne '') {
4168: foreach my $key (keys(%course_roles)) {
4169: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4170: my $crsrole = $1;
4171: my $crssec = $2;
4172: if ($crsrole =~ /^cr/) {
4173: unless (grep(/^cr$/,@rolecodes)) {
4174: push(@rolecodes,'cr');
4175: }
4176: } else {
4177: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4178: push(@rolecodes,$crsrole);
4179: }
4180: }
4181: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4182: if ($crssec ne '') {
4183: $rolekey .= '/'.$crssec;
4184: }
4185: $rolekey .= './';
4186: $groups_roles{$rolekey} = \@rolecodes;
4187: }
4188: }
4189: }
4190: }
1.1002 raeburn 4191: } else {
1.1064 raeburn 4192: push(@rolecodes,$$role);
1.1002 raeburn 4193: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4194: }
1.1064 raeburn 4195: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4196: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4197: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4198: }
4199: }
1.1034 raeburn 4200: $$tstatus = 'is';
1.1002 raeburn 4201: }
1.994 raeburn 4202: }
4203: if ($$tend) {
4204: if ($$tend<$then) {
4205: $$tstatus='expired';
4206: } elsif ($$tend<$now) {
4207: $$tstatus='will_not';
4208: }
4209: }
4210: }
4211: }
4212: }
4213:
4214: sub check_adhoc_privs {
1.1002 raeburn 4215: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4216: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4217: if ($env{$cckey}) {
4218: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4219: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4220: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4221: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4222: }
4223: } else {
4224: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4225: }
4226: }
4227:
4228: sub set_adhoc_privileges {
4229: # role can be cc or ca
4230: my ($dcdom,$pickedcourse,$role) = @_;
4231: my $area = '/'.$dcdom.'/'.$pickedcourse;
4232: my $spec = $role.'.'.$area;
4233: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4234: $env{'user.name'});
4235: my %ccrole = ();
4236: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4237: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4238: &appenv(\%userroles,[$role,'cm']);
4239: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4240: &appenv( {'request.role' => $spec,
4241: 'request.role.domain' => $dcdom,
4242: 'request.course.sec' => ''
4243: }
4244: );
4245: my $tadv=0;
4246: if (&allowed('adv') eq 'F') { $tadv=1; }
4247: &appenv({'request.role.adv' => $tadv});
4248: }
4249:
1.12 www 4250: # --------------------------------------------------------------- get interface
4251:
4252: sub get {
1.131 albertel 4253: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4254: my $items='';
1.800 albertel 4255: foreach my $item (@$storearr) {
4256: $items.=&escape($item).'&';
1.191 harris41 4257: }
1.12 www 4258: $items=~s/\&$//;
1.620 albertel 4259: if (!$udomain) { $udomain=$env{'user.domain'}; }
4260: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4261: my $uhome=&homeserver($uname,$udomain);
4262:
1.133 albertel 4263: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4264: my @pairs=split(/\&/,$rep);
1.273 albertel 4265: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4266: return @pairs;
4267: }
1.15 www 4268: my %returnhash=();
1.42 www 4269: my $i=0;
1.800 albertel 4270: foreach my $item (@$storearr) {
4271: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4272: $i++;
1.191 harris41 4273: }
1.15 www 4274: return %returnhash;
1.27 www 4275: }
4276:
4277: # --------------------------------------------------------------- del interface
4278:
4279: sub del {
1.133 albertel 4280: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4281: my $items='';
1.800 albertel 4282: foreach my $item (@$storearr) {
4283: $items.=&escape($item).'&';
1.191 harris41 4284: }
1.984 neumanie 4285:
1.27 www 4286: $items=~s/\&$//;
1.620 albertel 4287: if (!$udomain) { $udomain=$env{'user.domain'}; }
4288: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4289: my $uhome=&homeserver($uname,$udomain);
4290: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4291: }
4292:
4293: # -------------------------------------------------------------- dump interface
4294:
4295: sub dump {
1.755 albertel 4296: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4297: if (!$udomain) { $udomain=$env{'user.domain'}; }
4298: if (!$uname) { $uname=$env{'user.name'}; }
4299: my $uhome=&homeserver($uname,$udomain);
4300: if ($regexp) {
4301: $regexp=&escape($regexp);
4302: } else {
4303: $regexp='.';
4304: }
4305: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4306: my @pairs=split(/\&/,$rep);
4307: my %returnhash=();
4308: foreach my $item (@pairs) {
4309: my ($key,$value)=split(/=/,$item,2);
4310: $key = &unescape($key);
4311: next if ($key =~ /^error: 2 /);
4312: $returnhash{$key}=&thaw_unescape($value);
4313: }
4314: return %returnhash;
1.407 www 4315: }
4316:
1.717 albertel 4317: # --------------------------------------------------------- dumpstore interface
4318:
4319: sub dumpstore {
4320: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4321: if (!$udomain) { $udomain=$env{'user.domain'}; }
4322: if (!$uname) { $uname=$env{'user.name'}; }
4323: my $uhome=&homeserver($uname,$udomain);
4324: if ($regexp) {
4325: $regexp=&escape($regexp);
4326: } else {
4327: $regexp='.';
4328: }
4329: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4330: my @pairs=split(/\&/,$rep);
4331: my %returnhash=();
4332: foreach my $item (@pairs) {
4333: my ($key,$value)=split(/=/,$item,2);
4334: next if ($key =~ /^error: 2 /);
4335: $returnhash{$key}=&thaw_unescape($value);
4336: }
4337: return %returnhash;
1.717 albertel 4338: }
4339:
1.407 www 4340: # -------------------------------------------------------------- keys interface
4341:
4342: sub getkeys {
4343: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4344: if (!$udomain) { $udomain=$env{'user.domain'}; }
4345: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4346: my $uhome=&homeserver($uname,$udomain);
4347: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4348: my @keyarray=();
1.800 albertel 4349: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4350: next if ($key =~ /^error: 2 /);
1.800 albertel 4351: push(@keyarray,&unescape($key));
1.407 www 4352: }
4353: return @keyarray;
1.318 matthew 4354: }
4355:
1.319 matthew 4356: # --------------------------------------------------------------- currentdump
4357: sub currentdump {
1.328 matthew 4358: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4359: $courseid = $env{'request.course.id'} if (! defined($courseid));
4360: $sdom = $env{'user.domain'} if (! defined($sdom));
4361: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4362: my $uhome = &homeserver($sname,$sdom);
4363: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4364: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4365: #
1.318 matthew 4366: my %returnhash=();
1.319 matthew 4367: #
4368: if ($rep eq "unknown_cmd") {
4369: # an old lond will not know currentdump
4370: # Do a dump and make it look like a currentdump
1.822 albertel 4371: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4372: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4373: my %hash = @tmp;
4374: @tmp=();
1.424 matthew 4375: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4376: } else {
4377: my @pairs=split(/\&/,$rep);
1.800 albertel 4378: foreach my $pair (@pairs) {
4379: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4380: my ($symb,$param) = split(/:/,$key);
4381: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4382: &thaw_unescape($value);
1.319 matthew 4383: }
1.191 harris41 4384: }
1.12 www 4385: return %returnhash;
1.424 matthew 4386: }
4387:
4388: sub convert_dump_to_currentdump{
4389: my %hash = %{shift()};
4390: my %returnhash;
4391: # Code ripped from lond, essentially. The only difference
4392: # here is the unescaping done by lonnet::dump(). Conceivably
4393: # we might run in to problems with parameter names =~ /^v\./
4394: while (my ($key,$value) = each(%hash)) {
4395: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4396: $symb = &unescape($symb);
4397: $param = &unescape($param);
1.424 matthew 4398: next if ($v eq 'version' || $symb eq 'keys');
4399: next if (exists($returnhash{$symb}) &&
4400: exists($returnhash{$symb}->{$param}) &&
4401: $returnhash{$symb}->{'v.'.$param} > $v);
4402: $returnhash{$symb}->{$param}=$value;
4403: $returnhash{$symb}->{'v.'.$param}=$v;
4404: }
4405: #
4406: # Remove all of the keys in the hashes which keep track of
4407: # the version of the parameter.
4408: while (my ($symb,$param_hash) = each(%returnhash)) {
4409: # use a foreach because we are going to delete from the hash.
4410: foreach my $key (keys(%$param_hash)) {
4411: delete($param_hash->{$key}) if ($key =~ /^v\./);
4412: }
4413: }
4414: return \%returnhash;
1.12 www 4415: }
4416:
1.627 albertel 4417: # ------------------------------------------------------ critical inc interface
4418:
4419: sub cinc {
4420: return &inc(@_,'critical');
4421: }
4422:
1.449 matthew 4423: # --------------------------------------------------------------- inc interface
4424:
4425: sub inc {
1.627 albertel 4426: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4427: if (!$udomain) { $udomain=$env{'user.domain'}; }
4428: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4429: my $uhome=&homeserver($uname,$udomain);
4430: my $items='';
4431: if (! ref($store)) {
4432: # got a single value, so use that instead
4433: $items = &escape($store).'=&';
4434: } elsif (ref($store) eq 'SCALAR') {
4435: $items = &escape($$store).'=&';
4436: } elsif (ref($store) eq 'ARRAY') {
4437: $items = join('=&',map {&escape($_);} @{$store});
4438: } elsif (ref($store) eq 'HASH') {
4439: while (my($key,$value) = each(%{$store})) {
4440: $items.= &escape($key).'='.&escape($value).'&';
4441: }
4442: }
4443: $items=~s/\&$//;
1.627 albertel 4444: if ($critical) {
4445: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4446: } else {
4447: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4448: }
1.449 matthew 4449: }
4450:
1.12 www 4451: # --------------------------------------------------------------- put interface
4452:
4453: sub put {
1.134 albertel 4454: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4455: if (!$udomain) { $udomain=$env{'user.domain'}; }
4456: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4457: my $uhome=&homeserver($uname,$udomain);
1.12 www 4458: my $items='';
1.800 albertel 4459: foreach my $item (keys(%$storehash)) {
4460: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4461: }
1.12 www 4462: $items=~s/\&$//;
1.134 albertel 4463: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4464: }
4465:
1.631 albertel 4466: # ------------------------------------------------------------ newput interface
4467:
4468: sub newput {
4469: my ($namespace,$storehash,$udomain,$uname)=@_;
4470: if (!$udomain) { $udomain=$env{'user.domain'}; }
4471: if (!$uname) { $uname=$env{'user.name'}; }
4472: my $uhome=&homeserver($uname,$udomain);
4473: my $items='';
4474: foreach my $key (keys(%$storehash)) {
4475: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4476: }
4477: $items=~s/\&$//;
4478: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4479: }
4480:
4481: # --------------------------------------------------------- putstore interface
4482:
1.524 raeburn 4483: sub putstore {
1.715 albertel 4484: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4485: if (!$udomain) { $udomain=$env{'user.domain'}; }
4486: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4487: my $uhome=&homeserver($uname,$udomain);
4488: my $items='';
1.715 albertel 4489: foreach my $key (keys(%$storehash)) {
4490: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4491: }
1.715 albertel 4492: $items=~s/\&$//;
1.716 albertel 4493: my $esc_symb=&escape($symb);
4494: my $esc_v=&escape($version);
1.715 albertel 4495: my $reply =
1.716 albertel 4496: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4497: $uhome);
4498: if ($reply eq 'unknown_cmd') {
1.716 albertel 4499: # gfall back to way things use to be done
1.715 albertel 4500: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4501: $uname);
1.524 raeburn 4502: }
1.715 albertel 4503: return $reply;
4504: }
4505:
4506: sub old_putstore {
1.716 albertel 4507: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4508: if (!$udomain) { $udomain=$env{'user.domain'}; }
4509: if (!$uname) { $uname=$env{'user.name'}; }
4510: my $uhome=&homeserver($uname,$udomain);
4511: my %newstorehash;
1.800 albertel 4512: foreach my $item (keys(%$storehash)) {
4513: my $key = $version.':'.&escape($symb).':'.$item;
4514: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4515: }
4516: my $items='';
4517: my %allitems = ();
1.800 albertel 4518: foreach my $item (keys(%newstorehash)) {
4519: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4520: my $key = $1.':keys:'.$2;
4521: $allitems{$key} .= $3.':';
4522: }
1.800 albertel 4523: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4524: }
1.800 albertel 4525: foreach my $item (keys(%allitems)) {
4526: $allitems{$item} =~ s/\:$//;
4527: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4528: }
4529: $items=~s/\&$//;
4530: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4531: }
4532:
1.47 www 4533: # ------------------------------------------------------ critical put interface
4534:
4535: sub cput {
1.134 albertel 4536: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4537: if (!$udomain) { $udomain=$env{'user.domain'}; }
4538: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4539: my $uhome=&homeserver($uname,$udomain);
1.47 www 4540: my $items='';
1.800 albertel 4541: foreach my $item (keys(%$storehash)) {
4542: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4543: }
1.47 www 4544: $items=~s/\&$//;
1.134 albertel 4545: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4546: }
4547:
4548: # -------------------------------------------------------------- eget interface
4549:
4550: sub eget {
1.133 albertel 4551: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4552: my $items='';
1.800 albertel 4553: foreach my $item (@$storearr) {
4554: $items.=&escape($item).'&';
1.191 harris41 4555: }
1.12 www 4556: $items=~s/\&$//;
1.620 albertel 4557: if (!$udomain) { $udomain=$env{'user.domain'}; }
4558: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4559: my $uhome=&homeserver($uname,$udomain);
4560: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4561: my @pairs=split(/\&/,$rep);
4562: my %returnhash=();
1.42 www 4563: my $i=0;
1.800 albertel 4564: foreach my $item (@$storearr) {
4565: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4566: $i++;
1.191 harris41 4567: }
1.12 www 4568: return %returnhash;
4569: }
4570:
1.667 albertel 4571: # ------------------------------------------------------------ tmpput interface
4572: sub tmpput {
1.802 raeburn 4573: my ($storehash,$server,$context)=@_;
1.667 albertel 4574: my $items='';
1.800 albertel 4575: foreach my $item (keys(%$storehash)) {
4576: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4577: }
4578: $items=~s/\&$//;
1.802 raeburn 4579: if (defined($context)) {
4580: $items .= ':'.&escape($context);
4581: }
1.667 albertel 4582: return &reply("tmpput:$items",$server);
4583: }
4584:
4585: # ------------------------------------------------------------ tmpget interface
4586: sub tmpget {
1.688 albertel 4587: my ($token,$server)=@_;
4588: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4589: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4590: my %returnhash;
4591: foreach my $item (split(/\&/,$rep)) {
4592: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4593: next if ($key =~ /^error: 2 /);
1.667 albertel 4594: $returnhash{&unescape($key)}=&thaw_unescape($value);
4595: }
4596: return %returnhash;
4597: }
4598:
1.688 albertel 4599: # ------------------------------------------------------------ tmpget interface
4600: sub tmpdel {
4601: my ($token,$server)=@_;
4602: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4603: return &reply("tmpdel:$token",$server);
4604: }
4605:
1.765 albertel 4606: # -------------------------------------------------- portfolio access checking
4607:
4608: sub portfolio_access {
1.766 albertel 4609: my ($requrl) = @_;
1.765 albertel 4610: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4611: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4612: if ($result) {
4613: my %setters;
4614: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4615: my ($startblock,$endblock) =
4616: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4617: if ($startblock && $endblock) {
4618: return 'B';
4619: }
4620: } else {
4621: my ($startblock,$endblock) =
4622: &Apache::loncommon::blockcheck(\%setters,'port');
4623: if ($startblock && $endblock) {
4624: return 'B';
4625: }
4626: }
4627: }
1.765 albertel 4628: if ($result eq 'ok') {
1.766 albertel 4629: return 'F';
1.765 albertel 4630: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4631: return 'A';
1.765 albertel 4632: }
1.766 albertel 4633: return '';
1.765 albertel 4634: }
4635:
4636: sub get_portfolio_access {
1.767 albertel 4637: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4638:
4639: if (!ref($access_hash)) {
4640: my $current_perms = &get_portfile_permissions($udom,$unum);
4641: my %access_controls = &get_access_controls($current_perms,$group,
4642: $file_name);
4643: $access_hash = $access_controls{$file_name};
4644: }
4645:
1.765 albertel 4646: my ($public,$guest,@domains,@users,@courses,@groups);
4647: my $now = time;
4648: if (ref($access_hash) eq 'HASH') {
4649: foreach my $key (keys(%{$access_hash})) {
4650: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4651: if ($start > $now) {
4652: next;
4653: }
4654: if ($end && $end<$now) {
4655: next;
4656: }
4657: if ($scope eq 'public') {
4658: $public = $key;
4659: last;
4660: } elsif ($scope eq 'guest') {
4661: $guest = $key;
4662: } elsif ($scope eq 'domains') {
4663: push(@domains,$key);
4664: } elsif ($scope eq 'users') {
4665: push(@users,$key);
4666: } elsif ($scope eq 'course') {
4667: push(@courses,$key);
4668: } elsif ($scope eq 'group') {
4669: push(@groups,$key);
4670: }
4671: }
4672: if ($public) {
4673: return 'ok';
4674: }
4675: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4676: if ($guest) {
4677: return $guest;
4678: }
4679: } else {
4680: if (@domains > 0) {
4681: foreach my $domkey (@domains) {
4682: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4683: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4684: return 'ok';
4685: }
4686: }
4687: }
4688: }
4689: if (@users > 0) {
4690: foreach my $userkey (@users) {
1.865 raeburn 4691: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4692: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4693: if (ref($item) eq 'HASH') {
4694: if (($item->{'uname'} eq $env{'user.name'}) &&
4695: ($item->{'udom'} eq $env{'user.domain'})) {
4696: return 'ok';
4697: }
4698: }
4699: }
4700: }
1.765 albertel 4701: }
4702: }
4703: my %roleshash;
4704: my @courses_and_groups = @courses;
4705: push(@courses_and_groups,@groups);
4706: if (@courses_and_groups > 0) {
4707: my (%allgroups,%allroles);
4708: my ($start,$end,$role,$sec,$group);
4709: foreach my $envkey (%env) {
1.1060 raeburn 4710: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4711: my $cid = $2.'_'.$3;
4712: if ($1 eq 'gr') {
4713: $group = $4;
4714: $allgroups{$cid}{$group} = $env{$envkey};
4715: } else {
4716: if ($4 eq '') {
4717: $sec = 'none';
4718: } else {
4719: $sec = $4;
4720: }
4721: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4722: }
1.811 albertel 4723: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4724: my $cid = $2.'_'.$3;
4725: if ($4 eq '') {
4726: $sec = 'none';
4727: } else {
4728: $sec = $4;
4729: }
4730: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4731: }
4732: }
4733: if (keys(%allroles) == 0) {
4734: return;
4735: }
4736: foreach my $key (@courses_and_groups) {
4737: my %content = %{$$access_hash{$key}};
4738: my $cnum = $content{'number'};
4739: my $cdom = $content{'domain'};
4740: my $cid = $cdom.'_'.$cnum;
4741: if (!exists($allroles{$cid})) {
4742: next;
4743: }
4744: foreach my $role_id (keys(%{$content{'roles'}})) {
4745: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4746: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4747: my @status = @{$content{'roles'}{$role_id}{'access'}};
4748: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4749: foreach my $role (keys(%{$allroles{$cid}})) {
4750: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4751: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4752: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4753: if (grep/^all$/,@sections) {
4754: return 'ok';
4755: } else {
4756: if (grep/^$sec$/,@sections) {
4757: return 'ok';
4758: }
4759: }
4760: }
4761: }
4762: if (keys(%{$allgroups{$cid}}) == 0) {
4763: if (grep/^none$/,@groups) {
4764: return 'ok';
4765: }
4766: } else {
4767: if (grep/^all$/,@groups) {
4768: return 'ok';
4769: }
4770: foreach my $group (keys(%{$allgroups{$cid}})) {
4771: if (grep/^$group$/,@groups) {
4772: return 'ok';
4773: }
4774: }
4775: }
4776: }
4777: }
4778: }
4779: }
4780: }
4781: if ($guest) {
4782: return $guest;
4783: }
4784: }
4785: }
4786: return;
4787: }
4788:
4789: sub course_group_datechecker {
4790: my ($dates,$now,$status) = @_;
4791: my ($start,$end) = split(/\./,$dates);
4792: if (!$start && !$end) {
4793: return 'ok';
4794: }
4795: if (grep/^active$/,@{$status}) {
4796: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4797: return 'ok';
4798: }
4799: }
4800: if (grep/^previous$/,@{$status}) {
4801: if ($end > $now ) {
4802: return 'ok';
4803: }
4804: }
4805: if (grep/^future$/,@{$status}) {
4806: if ($start > $now) {
4807: return 'ok';
4808: }
4809: }
4810: return;
4811: }
4812:
4813: sub parse_portfolio_url {
4814: my ($url) = @_;
4815:
4816: my ($type,$udom,$unum,$group,$file_name);
4817:
1.823 albertel 4818: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4819: $type = 1;
4820: $udom = $1;
4821: $unum = $2;
4822: $file_name = $3;
1.823 albertel 4823: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4824: $type = 2;
4825: $udom = $1;
4826: $unum = $2;
4827: $group = $3;
4828: $file_name = $3.'/'.$4;
4829: }
4830: if (wantarray) {
4831: return ($type,$udom,$unum,$file_name,$group);
4832: }
4833: return $type;
4834: }
4835:
4836: sub is_portfolio_url {
4837: my ($url) = @_;
4838: return scalar(&parse_portfolio_url($url));
4839: }
4840:
1.798 raeburn 4841: sub is_portfolio_file {
4842: my ($file) = @_;
1.820 raeburn 4843: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4844: return 1;
4845: }
4846: return;
4847: }
4848:
1.976 raeburn 4849: sub usertools_access {
1.985 raeburn 4850: my ($uname,$udom,$tool,$action,$context) = @_;
4851: my ($access,%tools);
4852: if ($context eq '') {
4853: $context = 'tools';
4854: }
4855: if ($context eq 'requestcourses') {
4856: %tools = (
4857: official => 1,
4858: unofficial => 1,
1.1006 raeburn 4859: community => 1,
1.985 raeburn 4860: );
4861: } else {
4862: %tools = (
4863: aboutme => 1,
4864: blog => 1,
4865: portfolio => 1,
4866: );
4867: }
1.976 raeburn 4868: return if (!defined($tools{$tool}));
4869:
4870: if ((!defined($udom)) || (!defined($uname))) {
4871: $udom = $env{'user.domain'};
4872: $uname = $env{'user.name'};
4873: }
4874:
1.978 raeburn 4875: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4876: if ($action ne 'reload') {
1.985 raeburn 4877: if ($context eq 'requestcourses') {
4878: return $env{'environment.canrequest.'.$tool};
4879: } else {
4880: return $env{'environment.availabletools.'.$tool};
4881: }
4882: }
1.976 raeburn 4883: }
4884:
4885: my ($toolstatus,$inststatus);
4886:
1.985 raeburn 4887: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4888: ($action ne 'reload')) {
4889: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4890: $inststatus = $env{'environment.inststatus'};
4891: } else {
1.1025 raeburn 4892: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4893: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4894: $inststatus = $userenv{'inststatus'};
4895: }
4896:
4897: if ($toolstatus ne '') {
4898: if ($toolstatus) {
4899: $access = 1;
4900: } else {
4901: $access = 0;
4902: }
4903: return $access;
4904: }
4905:
4906: my $is_adv = &is_advanced_user($udom,$uname);
4907: my %domdef = &get_domain_defaults($udom);
4908: if (ref($domdef{$tool}) eq 'HASH') {
4909: if ($is_adv) {
4910: if ($domdef{$tool}{'_LC_adv'} ne '') {
4911: if ($domdef{$tool}{'_LC_adv'}) {
4912: $access = 1;
4913: } else {
4914: $access = 0;
4915: }
4916: return $access;
4917: }
4918: }
4919: if ($inststatus ne '') {
4920: my ($hasaccess,$hasnoaccess);
4921: foreach my $affiliation (split(/:/,$inststatus)) {
4922: if ($domdef{$tool}{$affiliation} ne '') {
4923: if ($domdef{$tool}{$affiliation}) {
4924: $hasaccess = 1;
4925: } else {
4926: $hasnoaccess = 1;
4927: }
4928: }
4929: }
4930: if ($hasaccess || $hasnoaccess) {
4931: if ($hasaccess) {
4932: $access = 1;
4933: } elsif ($hasnoaccess) {
4934: $access = 0;
4935: }
4936: return $access;
4937: }
4938: } else {
4939: if ($domdef{$tool}{'default'} ne '') {
4940: if ($domdef{$tool}{'default'}) {
4941: $access = 1;
4942: } elsif ($domdef{$tool}{'default'} == 0) {
4943: $access = 0;
4944: }
4945: return $access;
4946: }
4947: }
4948: } else {
1.985 raeburn 4949: if ($context eq 'tools') {
4950: $access = 1;
4951: } else {
4952: $access = 0;
4953: }
1.976 raeburn 4954: return $access;
4955: }
4956: }
4957:
1.1050 raeburn 4958: sub is_course_owner {
4959: my ($cdom,$cnum,$udom,$uname) = @_;
4960: if (($udom eq '') || ($uname eq '')) {
4961: $udom = $env{'user.domain'};
4962: $uname = $env{'user.name'};
4963: }
4964: unless (($udom eq '') || ($uname eq '')) {
4965: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4966: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4967: return 1;
4968: } else {
4969: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4970: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4971: return 1;
4972: }
4973: }
4974: }
4975: }
4976: return;
4977: }
4978:
1.976 raeburn 4979: sub is_advanced_user {
4980: my ($udom,$uname) = @_;
4981: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4982: my %allroles;
4983: my $is_adv;
4984: foreach my $role (keys(%roleshash)) {
4985: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4986: my $area = '/'.$tdomain.'/'.$trest;
4987: if ($sec ne '') {
4988: $area .= '/'.$sec;
4989: }
4990: if (($area ne '') && ($trole ne '')) {
4991: my $spec=$trole.'.'.$area;
4992: if ($trole =~ /^cr\//) {
4993: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4994: } elsif ($trole ne 'gr') {
4995: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4996: }
4997: }
4998: }
4999: foreach my $role (keys(%allroles)) {
5000: last if ($is_adv);
5001: foreach my $item (split(/:/,$allroles{$role})) {
5002: if ($item ne '') {
5003: my ($privilege,$restrictions)=split(/&/,$item);
5004: if ($privilege eq 'adv') {
5005: $is_adv = 1;
5006: last;
5007: }
5008: }
5009: }
5010: }
5011: return $is_adv;
5012: }
1.798 raeburn 5013:
1.1035 raeburn 5014: sub check_can_request {
1.1036 raeburn 5015: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5016: my $canreq = 0;
5017: my ($types,$typename) = &Apache::loncommon::course_types();
5018: my @options = ('approval','validate','autolimit');
5019: my $optregex = join('|',@options);
5020: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5021: foreach my $type (@{$types}) {
5022: if (&usertools_access($env{'user.name'},
5023: $env{'user.domain'},
5024: $type,undef,'requestcourses')) {
5025: $canreq ++;
1.1036 raeburn 5026: if (ref($request_domains) eq 'HASH') {
5027: push(@{$request_domains->{$type}},$env{'user.domain'});
5028: }
1.1035 raeburn 5029: if ($dom eq $env{'user.domain'}) {
5030: $can_request->{$type} = 1;
5031: }
5032: }
5033: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5034: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5035: if (@curr > 0) {
1.1036 raeburn 5036: foreach my $item (@curr) {
5037: if (ref($request_domains) eq 'HASH') {
5038: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5039: if ($otherdom ne '') {
5040: if (ref($request_domains->{$type}) eq 'ARRAY') {
5041: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5042: push(@{$request_domains->{$type}},$otherdom);
5043: }
5044: } else {
5045: push(@{$request_domains->{$type}},$otherdom);
5046: }
5047: }
5048: }
5049: }
5050: unless($dom eq $env{'user.domain'}) {
5051: $canreq ++;
1.1035 raeburn 5052: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5053: $can_request->{$type} = 1;
5054: }
5055: }
5056: }
5057: }
5058: }
5059: }
5060: return $canreq;
5061: }
5062:
1.341 www 5063: # ---------------------------------------------- Custom access rule evaluation
5064:
5065: sub customaccess {
5066: my ($priv,$uri)=@_;
1.807 albertel 5067: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5068: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5069: $udom = &LONCAPA::clean_domain($udom);
5070: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5071: my $access=0;
1.800 albertel 5072: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5073: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5074: if ($type eq 'user') {
5075: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5076: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5077: if ($tdom) {
5078: if ($tdom ne $env{'user.domain'}) { next; }
5079: }
1.896 albertel 5080: if ($tuname) {
5081: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5082: }
5083: $access=($effect eq 'allow');
5084: last;
5085: }
5086: } else {
5087: if ($role) {
5088: if ($role ne $urole) { next; }
5089: }
5090: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5091: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5092: if ($tdom) {
5093: if ($tdom ne $udom) { next; }
5094: }
5095: if ($tcrs) {
5096: if ($tcrs ne $ucrs) { next; }
5097: }
5098: if ($tsec) {
5099: if ($tsec ne $usec) { next; }
5100: }
5101: $access=($effect eq 'allow');
5102: last;
5103: }
5104: if ($realm eq '' && $role eq '') {
5105: $access=($effect eq 'allow');
5106: }
1.402 bowersj2 5107: }
1.341 www 5108: }
5109: return $access;
5110: }
5111:
1.103 harris41 5112: # ------------------------------------------------- Check for a user privilege
1.12 www 5113:
5114: sub allowed {
1.810 raeburn 5115: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5116: my $ver_orguri=$uri;
1.439 www 5117: $uri=&deversion($uri);
1.152 www 5118: my $orguri=$uri;
1.52 www 5119: $uri=&declutter($uri);
1.809 raeburn 5120:
1.810 raeburn 5121: if ($priv eq 'evb') {
5122: # Evade communication block restrictions for specified role in a course
5123: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5124: return $1;
5125: } else {
5126: return;
5127: }
5128: }
5129:
1.620 albertel 5130: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5131: # Free bre access to adm and meta resources
1.775 albertel 5132: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5133: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5134: && ($priv eq 'bre')) {
1.14 www 5135: return 'F';
1.159 www 5136: }
5137:
1.545 banghart 5138: # Free bre access to user's own portfolio contents
1.714 raeburn 5139: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5140: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5141: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5142: my %setters;
5143: my ($startblock,$endblock) =
5144: &Apache::loncommon::blockcheck(\%setters,'port');
5145: if ($startblock && $endblock) {
5146: return 'B';
5147: } else {
5148: return 'F';
5149: }
1.545 banghart 5150: }
5151:
1.762 raeburn 5152: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5153: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5154: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5155: if (exists($env{'request.course.id'})) {
5156: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5157: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5158: if (($domain eq $cdom) && ($name eq $cnum)) {
5159: my $courseprivid=$env{'request.course.id'};
5160: $courseprivid=~s/\_/\//;
5161: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5162: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5163: return $1;
1.762 raeburn 5164: } else {
5165: if ($env{'request.course.sec'}) {
5166: $courseprivid.='/'.$env{'request.course.sec'};
5167: }
5168: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5169: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5170: return $2;
5171: }
1.714 raeburn 5172: }
5173: }
5174: }
5175: }
5176:
1.159 www 5177: # Free bre to public access
5178:
5179: if ($priv eq 'bre') {
1.238 www 5180: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5181: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5182: return 'F';
5183: }
1.238 www 5184: if ($copyright eq 'priv') {
5185: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5186: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5187: return '';
5188: }
5189: }
5190: if ($copyright eq 'domain') {
5191: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5192: unless (($env{'user.domain'} eq $1) ||
5193: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5194: return '';
5195: }
1.262 matthew 5196: }
1.620 albertel 5197: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5198: # Library role, so allow browsing of resources in this domain.
5199: return 'F';
1.238 www 5200: }
1.341 www 5201: if ($copyright eq 'custom') {
5202: unless (&customaccess($priv,$uri)) { return ''; }
5203: }
1.14 www 5204: }
1.264 matthew 5205: # Domain coordinator is trying to create a course
1.620 albertel 5206: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5207: # uri is the requested domain in this case.
5208: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5209: # a role of dc for the domain in question.
1.620 albertel 5210: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5211: }
1.29 www 5212:
1.52 www 5213: my $thisallowed='';
5214: my $statecond=0;
5215: my $courseprivid='';
5216:
1.1039 raeburn 5217: my $ownaccess;
1.1043 raeburn 5218: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5219: if (($priv eq 'bro') && ($env{'user.author'})) {
5220: if ($uri eq '') {
5221: $ownaccess = 1;
5222: } else {
5223: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5224: my $udom = $env{'user.domain'};
5225: my $uname = $env{'user.name'};
5226: if ($uri =~ m{^\Q$udom\E/?$}) {
5227: $ownaccess = 1;
1.1040 raeburn 5228: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5229: unless ($uri =~ m{\.\./}) {
5230: $ownaccess = 1;
5231: }
5232: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5233: my $now = time;
5234: if ($uri =~ m{^([^/]+)/?$}) {
5235: my $adom = $1;
5236: foreach my $key (keys(%env)) {
1.1042 raeburn 5237: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5238: my ($start,$end) = split('.',$env{$key});
5239: if (($now >= $start) && (!$end || $end < $now)) {
5240: $ownaccess = 1;
5241: last;
5242: }
5243: }
5244: }
5245: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5246: my $adom = $1;
5247: my $aname = $2;
1.1042 raeburn 5248: foreach my $role ('ca','aa') {
5249: if ($env{"user.role.$role./$adom/$aname"}) {
5250: my ($start,$end) =
5251: split('.',$env{"user.role.$role./$adom/$aname"});
5252: if (($now >= $start) && (!$end || $end < $now)) {
5253: $ownaccess = 1;
5254: last;
5255: }
1.1039 raeburn 5256: }
5257: }
5258: }
5259: }
5260: }
5261: }
5262: }
5263:
1.52 www 5264: # Course
5265:
1.620 albertel 5266: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5267: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5268: $thisallowed.=$1;
5269: }
1.52 www 5270: }
1.29 www 5271:
1.52 www 5272: # Domain
5273:
1.620 albertel 5274: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5275: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5276: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5277: $thisallowed.=$1;
5278: }
1.12 www 5279: }
1.52 www 5280:
5281: # Course: uri itself is a course
1.66 www 5282: my $courseuri=$uri;
5283: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5284: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5285:
1.620 albertel 5286: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5287: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5288: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5289: $thisallowed.=$1;
5290: }
1.12 www 5291: }
1.29 www 5292:
1.665 albertel 5293: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5294: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5295: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5296: $thisallowed='';
1.671 raeburn 5297: my ($match)=&is_on_map($uri);
5298: if ($match) {
5299: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5300: =~/\Q$priv\E\&([^\:]*)/) {
5301: $thisallowed.=$1;
5302: }
5303: } else {
1.705 albertel 5304: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5305: if ($refuri) {
5306: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5307: $thisallowed='F';
1.671 raeburn 5308: } else {
5309: $refuri=&declutter($refuri);
5310: my ($match) = &is_on_map($refuri);
5311: if ($match) {
5312: $thisallowed='F';
5313: }
1.669 raeburn 5314: }
1.671 raeburn 5315: }
5316: }
1.314 www 5317: }
1.492 albertel 5318:
1.766 albertel 5319: if ($priv eq 'bre'
5320: && $thisallowed ne 'F'
5321: && $thisallowed ne '2'
5322: && &is_portfolio_url($uri)) {
5323: $thisallowed = &portfolio_access($uri);
5324: }
5325:
1.52 www 5326: # Full access at system, domain or course-wide level? Exit.
1.29 www 5327: if ($thisallowed=~/F/) {
5328: return 'F';
5329: }
5330:
1.52 www 5331: # If this is generating or modifying users, exit with special codes
1.29 www 5332:
1.643 www 5333: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5334: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5335: my ($audom,$auname)=split('/',$uri);
1.643 www 5336: # no author name given, so this just checks on the general right to make a co-author in this domain
5337: unless ($auname) { return $thisallowed; }
5338: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5339: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5340: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5341: ($audom ne $env{'request.role.domain'}))) { return ''; }
5342: }
1.52 www 5343: return $thisallowed;
5344: }
5345: #
1.103 harris41 5346: # Gathered so far: system, domain and course wide privileges
1.52 www 5347: #
5348: # Course: See if uri or referer is an individual resource that is part of
5349: # the course
5350:
1.620 albertel 5351: if ($env{'request.course.id'}) {
1.232 www 5352:
1.620 albertel 5353: $courseprivid=$env{'request.course.id'};
5354: if ($env{'request.course.sec'}) {
5355: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5356: }
5357: $courseprivid=~s/\_/\//;
5358: my $checkreferer=1;
1.232 www 5359: my ($match,$cond)=&is_on_map($uri);
5360: if ($match) {
5361: $statecond=$cond;
1.620 albertel 5362: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5363: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5364: $thisallowed.=$1;
5365: $checkreferer=0;
5366: }
1.29 www 5367: }
1.83 www 5368:
1.148 www 5369: if ($checkreferer) {
1.620 albertel 5370: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5371: unless ($refuri) {
1.800 albertel 5372: foreach my $key (keys(%env)) {
5373: if ($key=~/^httpref\..*\*/) {
5374: my $pattern=$key;
1.156 www 5375: $pattern=~s/^httpref\.\/res\///;
1.148 www 5376: $pattern=~s/\*/\[\^\/\]\+/g;
5377: $pattern=~s/\//\\\//g;
1.152 www 5378: if ($orguri=~/$pattern/) {
1.800 albertel 5379: $refuri=$env{$key};
1.148 www 5380: }
5381: }
1.191 harris41 5382: }
1.148 www 5383: }
1.232 www 5384:
1.148 www 5385: if ($refuri) {
1.152 www 5386: $refuri=&declutter($refuri);
1.232 www 5387: my ($match,$cond)=&is_on_map($refuri);
5388: if ($match) {
5389: my $refstatecond=$cond;
1.620 albertel 5390: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5391: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5392: $thisallowed.=$1;
1.53 www 5393: $uri=$refuri;
5394: $statecond=$refstatecond;
1.52 www 5395: }
5396: }
1.148 www 5397: }
1.29 www 5398: }
1.52 www 5399: }
1.29 www 5400:
1.52 www 5401: #
1.103 harris41 5402: # Gathered now: all privileges that could apply, and condition number
1.52 www 5403: #
5404: #
5405: # Full or no access?
5406: #
1.29 www 5407:
1.52 www 5408: if ($thisallowed=~/F/) {
5409: return 'F';
5410: }
1.29 www 5411:
1.52 www 5412: unless ($thisallowed) {
5413: return '';
5414: }
1.29 www 5415:
1.52 www 5416: # Restrictions exist, deal with them
5417: #
5418: # C:according to course preferences
5419: # R:according to resource settings
5420: # L:unless locked
5421: # X:according to user session state
5422: #
5423:
5424: # Possibly locked functionality, check all courses
1.54 www 5425: # Locks might take effect only after 10 minutes cache expiration for other
5426: # courses, and 2 minutes for current course
1.52 www 5427:
5428: my $envkey;
5429: if ($thisallowed=~/L/) {
1.1000 raeburn 5430: foreach $envkey (keys(%env)) {
1.54 www 5431: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5432: my $courseid=$2;
5433: my $roleid=$1.'.'.$2;
1.92 www 5434: $courseid=~s/^\///;
1.54 www 5435: my $expiretime=600;
1.620 albertel 5436: if ($env{'request.role'} eq $roleid) {
1.54 www 5437: $expiretime=120;
5438: }
5439: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5440: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5441: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5442: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5443: }
1.620 albertel 5444: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5445: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5446: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5447: &log($env{'user.domain'},$env{'user.name'},
5448: $env{'user.home'},
1.57 www 5449: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5450: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5451: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5452: return '';
5453: }
5454: }
1.620 albertel 5455: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5456: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5457: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5458: &log($env{'user.domain'},$env{'user.name'},
5459: $env{'user.home'},
1.57 www 5460: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5461: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5462: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5463: return '';
5464: }
5465: }
5466: }
1.29 www 5467: }
1.52 www 5468: }
5469:
5470: #
5471: # Rest of the restrictions depend on selected course
5472: #
5473:
1.620 albertel 5474: unless ($env{'request.course.id'}) {
1.766 albertel 5475: if ($thisallowed eq 'A') {
5476: return 'A';
1.814 raeburn 5477: } elsif ($thisallowed eq 'B') {
5478: return 'B';
1.766 albertel 5479: } else {
5480: return '1';
5481: }
1.52 www 5482: }
1.29 www 5483:
1.52 www 5484: #
5485: # Now user is definitely in a course
5486: #
1.53 www 5487:
5488:
5489: # Course preferences
5490:
5491: if ($thisallowed=~/C/) {
1.620 albertel 5492: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5493: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5494: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5495: =~/\Q$rolecode\E/) {
1.689 albertel 5496: if ($priv ne 'pch') {
5497: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5498: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5499: $env{'request.course.id'});
5500: }
1.237 www 5501: return '';
5502: }
5503:
1.620 albertel 5504: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5505: =~/\Q$unamedom\E/) {
1.689 albertel 5506: if ($priv ne 'pch') {
5507: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5508: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5509: $env{'request.course.id'});
5510: }
1.54 www 5511: return '';
5512: }
1.53 www 5513: }
5514:
5515: # Resource preferences
5516:
5517: if ($thisallowed=~/R/) {
1.620 albertel 5518: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5519: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5520: if ($priv ne 'pch') {
5521: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5522: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5523: }
5524: return '';
1.54 www 5525: }
1.53 www 5526: }
1.30 www 5527:
1.246 www 5528: # Restricted by state or randomout?
1.30 www 5529:
1.52 www 5530: if ($thisallowed=~/X/) {
1.620 albertel 5531: if ($env{'acc.randomout'}) {
1.579 albertel 5532: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5533: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5534: return '';
5535: }
1.247 www 5536: }
5537: if (&condval($statecond)) {
1.52 www 5538: return '2';
5539: } else {
5540: return '';
5541: }
5542: }
1.30 www 5543:
1.766 albertel 5544: if ($thisallowed eq 'A') {
5545: return 'A';
1.814 raeburn 5546: } elsif ($thisallowed eq 'B') {
5547: return 'B';
1.766 albertel 5548: }
1.52 www 5549: return 'F';
1.232 www 5550: }
5551:
1.710 albertel 5552: sub split_uri_for_cond {
5553: my $uri=&deversion(&declutter(shift));
5554: my @uriparts=split(/\//,$uri);
5555: my $filename=pop(@uriparts);
5556: my $pathname=join('/',@uriparts);
5557: return ($pathname,$filename);
5558: }
1.232 www 5559: # --------------------------------------------------- Is a resource on the map?
5560:
5561: sub is_on_map {
1.710 albertel 5562: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5563: #Trying to find the conditional for the file
1.620 albertel 5564: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5565: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5566: if ($match) {
1.289 bowersj2 5567: return (1,$1);
5568: } else {
1.434 www 5569: return (0,0);
1.289 bowersj2 5570: }
1.12 www 5571: }
5572:
1.427 www 5573: # --------------------------------------------------------- Get symb from alias
5574:
5575: sub get_symb_from_alias {
5576: my $symb=shift;
5577: my ($map,$resid,$url)=&decode_symb($symb);
5578: # Already is a symb
5579: if ($url) { return $symb; }
5580: # Must be an alias
5581: my $aliassymb='';
5582: my %bighash;
1.620 albertel 5583: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5584: &GDBM_READER(),0640)) {
5585: my $rid=$bighash{'mapalias_'.$symb};
5586: if ($rid) {
5587: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5588: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5589: $resid,$bighash{'src_'.$rid});
1.427 www 5590: }
5591: untie %bighash;
5592: }
5593: return $aliassymb;
5594: }
5595:
1.12 www 5596: # ----------------------------------------------------------------- Define Role
5597:
5598: sub definerole {
5599: if (allowed('mcr','/')) {
5600: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5601: foreach my $role (split(':',$sysrole)) {
5602: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5603: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5604: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5605: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5606: return "refused:s:$crole&$cqual";
5607: }
5608: }
1.191 harris41 5609: }
1.800 albertel 5610: foreach my $role (split(':',$domrole)) {
5611: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5612: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5613: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5614: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5615: return "refused:d:$crole&$cqual";
5616: }
5617: }
1.191 harris41 5618: }
1.800 albertel 5619: foreach my $role (split(':',$courole)) {
5620: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5621: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5622: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5623: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5624: return "refused:c:$crole&$cqual";
5625: }
5626: }
1.191 harris41 5627: }
1.620 albertel 5628: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5629: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5630: "rolesdef_$rolename=".
5631: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5632: return reply($command,$env{'user.home'});
1.12 www 5633: } else {
5634: return 'refused';
5635: }
1.105 harris41 5636: }
5637:
5638: # ---------------- Make a metadata query against the network of library servers
5639:
5640: sub metadata_query {
1.244 matthew 5641: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5642: my %rhash;
1.845 albertel 5643: my %libserv = &all_library();
1.244 matthew 5644: my @server_list = (defined($server_array) ? @$server_array
5645: : keys(%libserv) );
5646: for my $server (@server_list) {
1.118 harris41 5647: unless ($custom or $customshow) {
5648: my $reply=&reply("querysend:".&escape($query),$server);
5649: $rhash{$server}=$reply;
5650: }
5651: else {
5652: my $reply=&reply("querysend:".&escape($query).':'.
5653: &escape($custom).':'.&escape($customshow),
5654: $server);
5655: $rhash{$server}=$reply;
5656: }
1.112 harris41 5657: }
1.118 harris41 5658: return \%rhash;
1.240 www 5659: }
5660:
5661: # ----------------------------------------- Send log queries and wait for reply
5662:
5663: sub log_query {
5664: my ($uname,$udom,$query,%filters)=@_;
5665: my $uhome=&homeserver($uname,$udom);
5666: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5667: my $uhost=&hostname($uhome);
1.800 albertel 5668: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5669: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5670: $uhome);
1.479 albertel 5671: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5672: return get_query_reply($queryid);
5673: }
5674:
1.818 raeburn 5675: # -------------------------- Update MySQL table for portfolio file
5676:
5677: sub update_portfolio_table {
1.821 raeburn 5678: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5679: if ($group ne '') {
5680: $file_name =~s /^\Q$group\E//;
5681: }
1.818 raeburn 5682: my $homeserver = &homeserver($uname,$udom);
5683: my $queryid=
1.821 raeburn 5684: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5685: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5686: my $reply = &get_query_reply($queryid);
5687: return $reply;
5688: }
5689:
1.899 raeburn 5690: # -------------------------- Update MySQL allusers table
5691:
5692: sub update_allusers_table {
5693: my ($uname,$udom,$names) = @_;
5694: my $homeserver = &homeserver($uname,$udom);
5695: my $queryid=
5696: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5697: 'lastname='.&escape($names->{'lastname'}).'%%'.
5698: 'firstname='.&escape($names->{'firstname'}).'%%'.
5699: 'middlename='.&escape($names->{'middlename'}).'%%'.
5700: 'generation='.&escape($names->{'generation'}).'%%'.
5701: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5702: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5703: return;
1.899 raeburn 5704: }
5705:
1.508 raeburn 5706: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5707:
5708: sub fetch_enrollment_query {
1.511 raeburn 5709: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5710: my $homeserver;
1.547 raeburn 5711: my $maxtries = 1;
1.508 raeburn 5712: if ($context eq 'automated') {
5713: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5714: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5715: } else {
5716: $homeserver = &homeserver($cnum,$dom);
5717: }
1.838 albertel 5718: my $host=&hostname($homeserver);
1.506 raeburn 5719: my $cmd = '';
1.1000 raeburn 5720: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5721: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5722: }
5723: $cmd =~ s/%%$//;
5724: $cmd = &escape($cmd);
5725: my $query = 'fetchenrollment';
1.620 albertel 5726: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5727: unless ($queryid=~/^\Q$host\E\_/) {
5728: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5729: return 'error: '.$queryid;
5730: }
1.506 raeburn 5731: my $reply = &get_query_reply($queryid);
1.547 raeburn 5732: my $tries = 1;
5733: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5734: $reply = &get_query_reply($queryid);
5735: $tries ++;
5736: }
1.526 raeburn 5737: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5738: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5739: } else {
1.901 albertel 5740: my @responses = split(/:/,$reply);
1.515 raeburn 5741: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5742: foreach my $line (@responses) {
5743: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5744: $$replyref{$key} = $value;
5745: }
5746: } else {
1.506 raeburn 5747: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5748: foreach my $line (@responses) {
5749: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5750: $$replyref{$key} = $value;
5751: if ($value > 0) {
1.800 albertel 5752: foreach my $item (@{$$affiliatesref{$key}}) {
5753: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5754: my $destname = $pathname.'/'.$filename;
5755: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5756: if ($xml_classlist =~ /^error/) {
5757: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5758: } else {
1.506 raeburn 5759: if ( open(FILE,">$destname") ) {
5760: print FILE &unescape($xml_classlist);
5761: close(FILE);
1.526 raeburn 5762: } else {
5763: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5764: }
5765: }
5766: }
5767: }
5768: }
5769: }
5770: return 'ok';
5771: }
5772: return 'error';
5773: }
5774:
1.242 www 5775: sub get_query_reply {
5776: my $queryid=shift;
1.240 www 5777: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5778: my $reply='';
5779: for (1..100) {
5780: sleep 2;
5781: if (-e $replyfile.'.end') {
1.448 albertel 5782: if (open(my $fh,$replyfile)) {
1.904 albertel 5783: $reply = join('',<$fh>);
5784: close($fh);
1.240 www 5785: } else { return 'error: reply_file_error'; }
1.242 www 5786: return &unescape($reply);
5787: }
1.240 www 5788: }
1.242 www 5789: return 'timeout:'.$queryid;
1.240 www 5790: }
5791:
5792: sub courselog_query {
1.241 www 5793: #
5794: # possible filters:
5795: # url: url or symb
5796: # username
5797: # domain
5798: # action: view, submit, grade
5799: # start: timestamp
5800: # end: timestamp
5801: #
1.240 www 5802: my (%filters)=@_;
1.620 albertel 5803: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5804: if ($filters{'url'}) {
5805: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5806: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5807: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5808: }
1.620 albertel 5809: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5810: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5811: return &log_query($cname,$cdom,'courselog',%filters);
5812: }
5813:
5814: sub userlog_query {
1.858 raeburn 5815: #
5816: # possible filters:
5817: # action: log check role
5818: # start: timestamp
5819: # end: timestamp
5820: #
1.240 www 5821: my ($uname,$udom,%filters)=@_;
5822: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5823: }
5824:
1.506 raeburn 5825: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5826:
5827: sub auto_run {
1.508 raeburn 5828: my ($cnum,$cdom) = @_;
1.876 raeburn 5829: my $response = 0;
5830: my $settings;
5831: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5832: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5833: $settings = $domconfig{'autoenroll'};
5834: if ($settings->{'run'} eq '1') {
5835: $response = 1;
5836: }
5837: } else {
1.934 raeburn 5838: my $homeserver;
5839: if (&is_course($cdom,$cnum)) {
5840: $homeserver = &homeserver($cnum,$cdom);
5841: } else {
5842: $homeserver = &domain($cdom,'primary');
5843: }
5844: if ($homeserver ne 'no_host') {
5845: $response = &reply('autorun:'.$cdom,$homeserver);
5846: }
1.876 raeburn 5847: }
1.506 raeburn 5848: return $response;
5849: }
1.776 albertel 5850:
1.506 raeburn 5851: sub auto_get_sections {
1.508 raeburn 5852: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5853: my $homeserver;
5854: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5855: $homeserver = &homeserver($cnum,$cdom);
5856: }
5857: if (!defined($homeserver)) {
5858: if ($cdom =~ /^$match_domain$/) {
5859: $homeserver = &domain($cdom,'primary');
5860: }
5861: }
5862: my @secs;
5863: if (defined($homeserver)) {
5864: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5865: unless ($response eq 'refused') {
5866: @secs = split(/:/,$response);
5867: }
1.506 raeburn 5868: }
5869: return @secs;
5870: }
1.776 albertel 5871:
1.506 raeburn 5872: sub auto_new_course {
1.508 raeburn 5873: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5874: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5875: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5876: return $response;
5877: }
1.776 albertel 5878:
1.506 raeburn 5879: sub auto_validate_courseID {
1.508 raeburn 5880: my ($cnum,$cdom,$inst_course_id) = @_;
5881: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5882: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5883: return $response;
5884: }
1.776 albertel 5885:
1.1007 raeburn 5886: sub auto_validate_instcode {
1.1020 raeburn 5887: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5888: my ($homeserver,$response);
5889: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5890: $homeserver = &homeserver($cnum,$cdom);
5891: }
5892: if (!defined($homeserver)) {
5893: if ($cdom =~ /^$match_domain$/) {
5894: $homeserver = &domain($cdom,'primary');
5895: }
5896: }
1.1065 raeburn 5897: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5898: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5899: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5900: return ($outcome,$description);
1.1007 raeburn 5901: }
5902:
1.506 raeburn 5903: sub auto_create_password {
1.873 raeburn 5904: my ($cnum,$cdom,$authparam,$udom) = @_;
5905: my ($homeserver,$response);
1.506 raeburn 5906: my $create_passwd = 0;
5907: my $authchk = '';
1.873 raeburn 5908: if ($udom =~ /^$match_domain$/) {
5909: $homeserver = &domain($udom,'primary');
5910: }
5911: if ($homeserver eq '') {
5912: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5913: $homeserver = &homeserver($cnum,$cdom);
5914: }
5915: }
5916: if ($homeserver eq '') {
5917: $authchk = 'nodomain';
1.506 raeburn 5918: } else {
1.873 raeburn 5919: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5920: if ($response eq 'refused') {
5921: $authchk = 'refused';
5922: } else {
1.901 albertel 5923: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5924: }
1.506 raeburn 5925: }
5926: return ($authparam,$create_passwd,$authchk);
5927: }
5928:
1.706 raeburn 5929: sub auto_photo_permission {
5930: my ($cnum,$cdom,$students) = @_;
5931: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5932: my ($outcome,$perm_reqd,$conditions) =
5933: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5934: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5935: return (undef,undef);
5936: }
1.706 raeburn 5937: return ($outcome,$perm_reqd,$conditions);
5938: }
5939:
5940: sub auto_checkphotos {
5941: my ($uname,$udom,$pid) = @_;
5942: my $homeserver = &homeserver($uname,$udom);
5943: my ($result,$resulttype);
5944: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5945: &escape($uname).':'.&escape($pid),
5946: $homeserver));
1.709 albertel 5947: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5948: return (undef,undef);
5949: }
1.706 raeburn 5950: if ($outcome) {
5951: ($result,$resulttype) = split(/:/,$outcome);
5952: }
5953: return ($result,$resulttype);
5954: }
5955:
5956: sub auto_photochoice {
5957: my ($cnum,$cdom) = @_;
5958: my $homeserver = &homeserver($cnum,$cdom);
5959: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5960: &escape($cdom),
5961: $homeserver)));
1.709 albertel 5962: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5963: return (undef,undef);
5964: }
1.706 raeburn 5965: return ($update,$comment);
5966: }
5967:
5968: sub auto_photoupdate {
5969: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5970: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5971: my $host=&hostname($homeserver);
1.706 raeburn 5972: my $cmd = '';
5973: my $maxtries = 1;
1.800 albertel 5974: foreach my $affiliate (keys(%{$affiliatesref})) {
5975: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5976: }
5977: $cmd =~ s/%%$//;
5978: $cmd = &escape($cmd);
5979: my $query = 'institutionalphotos';
5980: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5981: unless ($queryid=~/^\Q$host\E\_/) {
5982: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5983: return 'error: '.$queryid;
5984: }
5985: my $reply = &get_query_reply($queryid);
5986: my $tries = 1;
5987: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5988: $reply = &get_query_reply($queryid);
5989: $tries ++;
5990: }
5991: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5992: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5993: } else {
5994: my @responses = split(/:/,$reply);
5995: my $outcome = shift(@responses);
5996: foreach my $item (@responses) {
5997: my ($key,$value) = split(/=/,$item);
5998: $$photo{$key} = $value;
5999: }
6000: return $outcome;
6001: }
6002: return 'error';
6003: }
6004:
1.521 raeburn 6005: sub auto_instcode_format {
1.793 albertel 6006: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6007: $cat_order) = @_;
1.521 raeburn 6008: my $courses = '';
1.772 raeburn 6009: my @homeservers;
1.521 raeburn 6010: if ($caller eq 'global') {
1.841 albertel 6011: my %servers = &get_servers($codedom,'library');
6012: foreach my $tryserver (keys(%servers)) {
6013: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6014: push(@homeservers,$tryserver);
6015: }
1.584 raeburn 6016: }
1.1022 raeburn 6017: } elsif ($caller eq 'requests') {
6018: if ($codedom =~ /^$match_domain$/) {
6019: my $chome = &domain($codedom,'primary');
6020: unless ($chome eq 'no_host') {
6021: push(@homeservers,$chome);
6022: }
6023: }
1.521 raeburn 6024: } else {
1.772 raeburn 6025: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6026: }
1.793 albertel 6027: foreach my $code (keys(%{$instcodes})) {
6028: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6029: }
6030: chop($courses);
1.772 raeburn 6031: my $ok_response = 0;
6032: my $response;
6033: while (@homeservers > 0 && $ok_response == 0) {
6034: my $server = shift(@homeservers);
6035: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6036: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6037: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6038: split(/:/,$response);
1.772 raeburn 6039: %{$codes} = (%{$codes},&str2hash($codes_str));
6040: push(@{$codetitles},&str2array($codetitles_str));
6041: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6042: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6043: $ok_response = 1;
6044: }
6045: }
6046: if ($ok_response) {
1.521 raeburn 6047: return 'ok';
1.772 raeburn 6048: } else {
6049: return $response;
1.521 raeburn 6050: }
6051: }
6052:
1.792 raeburn 6053: sub auto_instcode_defaults {
6054: my ($domain,$returnhash,$code_order) = @_;
6055: my @homeservers;
1.841 albertel 6056:
6057: my %servers = &get_servers($domain,'library');
6058: foreach my $tryserver (keys(%servers)) {
6059: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6060: push(@homeservers,$tryserver);
6061: }
1.792 raeburn 6062: }
1.841 albertel 6063:
1.792 raeburn 6064: my $response;
1.841 albertel 6065: foreach my $server (@homeservers) {
1.792 raeburn 6066: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6067: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6068:
6069: foreach my $pair (split(/\&/,$response)) {
6070: my ($name,$value)=split(/\=/,$pair);
6071: if ($name eq 'code_order') {
6072: @{$code_order} = split(/\&/,&unescape($value));
6073: } else {
6074: $returnhash->{&unescape($name)}=&unescape($value);
6075: }
6076: }
6077: return 'ok';
1.792 raeburn 6078: }
1.841 albertel 6079:
6080: return $response;
1.1003 raeburn 6081: }
6082:
6083: sub auto_possible_instcodes {
1.1007 raeburn 6084: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6085: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6086: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6087: return;
6088: }
1.1003 raeburn 6089: my (@homeservers,$uhome);
6090: if (defined(&domain($domain,'primary'))) {
6091: $uhome=&domain($domain,'primary');
6092: push(@homeservers,&domain($domain,'primary'));
6093: } else {
6094: my %servers = &get_servers($domain,'library');
6095: foreach my $tryserver (keys(%servers)) {
6096: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6097: push(@homeservers,$tryserver);
6098: }
6099: }
6100: }
6101: my $response;
6102: foreach my $server (@homeservers) {
6103: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6104: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6105: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6106: split(':',$response);
6107: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6108: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6109: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6110: my ($name,$value)=split('=',$item);
6111: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6112: }
6113: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6114: my ($name,$value)=split('=',$item);
6115: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6116: }
6117: return 'ok';
6118: }
6119: return $response;
6120: }
1.792 raeburn 6121:
1.1010 raeburn 6122: sub auto_courserequest_checks {
6123: my ($dom) = @_;
1.1020 raeburn 6124: my ($homeserver,%validations);
6125: if ($dom =~ /^$match_domain$/) {
6126: $homeserver = &domain($dom,'primary');
6127: }
6128: unless ($homeserver eq 'no_host') {
6129: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6130: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6131: my @items = split(/&/,$response);
6132: foreach my $item (@items) {
6133: my ($key,$value) = split('=',$item);
6134: $validations{&unescape($key)} = &thaw_unescape($value);
6135: }
6136: }
6137: }
1.1010 raeburn 6138: return %validations;
6139: }
6140:
1.1020 raeburn 6141: sub auto_courserequest_validation {
6142: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6143: my ($homeserver,$response);
6144: if ($dom =~ /^$match_domain$/) {
6145: $homeserver = &domain($dom,'primary');
6146: }
6147: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6148:
1.1020 raeburn 6149: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6150: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6151: ':'.&escape($instcode).':'.&escape($instseclist),
6152: $homeserver));
6153: }
6154: return $response;
6155: }
6156:
1.777 albertel 6157: sub auto_validate_class_sec {
1.918 raeburn 6158: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6159: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6160: my $ownerlist;
6161: if (ref($owners) eq 'ARRAY') {
6162: $ownerlist = join(',',@{$owners});
6163: } else {
6164: $ownerlist = $owners;
6165: }
1.773 raeburn 6166: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6167: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6168: return $response;
6169: }
6170:
1.679 raeburn 6171: # ------------------------------------------------------- Course Group routines
6172:
6173: sub get_coursegroups {
1.809 raeburn 6174: my ($cdom,$cnum,$group,$namespace) = @_;
6175: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6176: }
6177:
1.679 raeburn 6178: sub modify_coursegroup {
6179: my ($cdom,$cnum,$groupsettings) = @_;
6180: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6181: }
6182:
1.809 raeburn 6183: sub toggle_coursegroup_status {
6184: my ($cdom,$cnum,$group,$action) = @_;
6185: my ($from_namespace,$to_namespace);
6186: if ($action eq 'delete') {
6187: $from_namespace = 'coursegroups';
6188: $to_namespace = 'deleted_groups';
6189: } else {
6190: $from_namespace = 'deleted_groups';
6191: $to_namespace = 'coursegroups';
6192: }
6193: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6194: if (my $tmp = &error(%curr_group)) {
6195: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6196: return ('read error',$tmp);
6197: } else {
6198: my %savedsettings = %curr_group;
1.809 raeburn 6199: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6200: my $deloutcome;
6201: if ($result eq 'ok') {
1.809 raeburn 6202: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6203: } else {
6204: return ('write error',$result);
6205: }
6206: if ($deloutcome eq 'ok') {
6207: return 'ok';
6208: } else {
6209: return ('delete error',$deloutcome);
6210: }
6211: }
6212: }
6213:
1.679 raeburn 6214: sub modify_group_roles {
1.957 raeburn 6215: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6216: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6217: my $role = 'gr/'.&escape($userprivs);
6218: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6219: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6220: if ($result eq 'ok') {
6221: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6222: }
1.679 raeburn 6223: return $result;
6224: }
6225:
6226: sub modify_coursegroup_membership {
6227: my ($cdom,$cnum,$membership) = @_;
6228: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6229: return $result;
6230: }
6231:
1.682 raeburn 6232: sub get_active_groups {
6233: my ($udom,$uname,$cdom,$cnum) = @_;
6234: my $now = time;
6235: my %groups = ();
6236: foreach my $key (keys(%env)) {
1.811 albertel 6237: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6238: my ($start,$end) = split(/\./,$env{$key});
6239: if (($end!=0) && ($end<$now)) { next; }
6240: if (($start!=0) && ($start>$now)) { next; }
6241: if ($1 eq $cdom && $2 eq $cnum) {
6242: $groups{$3} = $env{$key} ;
6243: }
6244: }
6245: }
6246: return %groups;
6247: }
6248:
1.683 raeburn 6249: sub get_group_membership {
6250: my ($cdom,$cnum,$group) = @_;
6251: return(&dump('groupmembership',$cdom,$cnum,$group));
6252: }
6253:
6254: sub get_users_groups {
6255: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6256: my @usersgroups;
1.683 raeburn 6257: my $cachetime=1800;
6258:
6259: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6260: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6261: if (defined($cached)) {
1.734 albertel 6262: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6263: } else {
6264: $grouplist = '';
1.816 raeburn 6265: my $courseurl = &courseid_to_courseurl($courseid);
6266: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6267: my $access_end = $env{'course.'.$courseid.
6268: '.default_enrollment_end_date'};
6269: my $now = time;
6270: foreach my $key (keys(%roleshash)) {
6271: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6272: my $group = $1;
6273: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6274: my $start = $2;
6275: my $end = $1;
6276: if ($start == -1) { next; } # deleted from group
6277: if (($start!=0) && ($start>$now)) { next; }
6278: if (($end!=0) && ($end<$now)) {
6279: if ($access_end && $access_end < $now) {
6280: if ($access_end - $end < 86400) {
6281: push(@usersgroups,$group);
1.733 raeburn 6282: }
6283: }
1.817 raeburn 6284: next;
1.733 raeburn 6285: }
1.817 raeburn 6286: push(@usersgroups,$group);
1.683 raeburn 6287: }
6288: }
6289: }
1.817 raeburn 6290: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6291: $grouplist = join(':',@usersgroups);
6292: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6293: }
1.733 raeburn 6294: return @usersgroups;
1.683 raeburn 6295: }
6296:
6297: sub devalidate_getgroups_cache {
6298: my ($udom,$uname,$cdom,$cnum)=@_;
6299: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6300:
1.683 raeburn 6301: my $hashid="$udom:$uname:$courseid";
6302: &devalidate_cache_new('getgroups',$hashid);
6303: }
6304:
1.12 www 6305: # ------------------------------------------------------------------ Plain Text
6306:
6307: sub plaintext {
1.988 raeburn 6308: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6309: if ($short =~ m{^cr/}) {
1.758 albertel 6310: return (split('/',$short))[-1];
6311: }
1.742 raeburn 6312: if (!defined($cid)) {
6313: $cid = $env{'request.course.id'};
6314: }
6315: my %rolenames = (
1.1008 raeburn 6316: Course => 'std',
6317: Community => 'alt1',
1.742 raeburn 6318: );
1.1037 raeburn 6319: if ($cid ne '') {
6320: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6321: unless ($forcedefault) {
6322: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6323: &Apache::lonlocal::mt_escape(\$roletext);
6324: return &Apache::lonlocal::mt($roletext);
6325: }
6326: }
6327: }
6328: if ((defined($type)) && (defined($rolenames{$type})) &&
6329: (defined($rolenames{$type})) &&
6330: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6331: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6332: } elsif ($cid ne '') {
6333: my $crstype = $env{'course.'.$cid.'.type'};
6334: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6335: (defined($prp{$short}{$rolenames{$crstype}}))) {
6336: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6337: }
1.742 raeburn 6338: }
1.1037 raeburn 6339: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6340: }
6341:
6342: # ----------------------------------------------------------------- Assign Role
6343:
6344: sub assignrole {
1.957 raeburn 6345: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6346: $context)=@_;
1.21 www 6347: my $mrole;
6348: if ($role =~ /^cr\//) {
1.393 www 6349: my $cwosec=$url;
1.811 albertel 6350: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6351: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6352: my $refused = 1;
6353: if ($context eq 'requestcourses') {
6354: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6355: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6356: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6357: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6358: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6359: if ($crsenv{'internal.courseowner'} eq
6360: $env{'user.name'}.':'.$env{'user.domain'}) {
6361: $refused = '';
6362: }
6363: }
6364: }
6365: }
6366: }
6367: if ($refused) {
6368: &logthis('Refused custom assignrole: '.
6369: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6370: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6371: return 'refused';
6372: }
1.104 www 6373: }
1.21 www 6374: $mrole='cr';
1.678 raeburn 6375: } elsif ($role =~ /^gr\//) {
6376: my $cwogrp=$url;
1.811 albertel 6377: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6378: unless (&allowed('mdg',$cwogrp)) {
6379: &logthis('Refused group assignrole: '.
6380: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6381: $env{'user.name'}.' at '.$env{'user.domain'});
6382: return 'refused';
6383: }
6384: $mrole='gr';
1.21 www 6385: } else {
1.82 www 6386: my $cwosec=$url;
1.811 albertel 6387: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6388: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6389: my $refused;
6390: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6391: if (!(&allowed('c'.$role,$url))) {
6392: $refused = 1;
6393: }
6394: } else {
6395: $refused = 1;
6396: }
1.947 raeburn 6397: if ($refused) {
1.1045 raeburn 6398: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6399: if (!$selfenroll && $context eq 'course') {
6400: my %crsenv;
6401: if ($role eq 'cc' || $role eq 'co') {
6402: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6403: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6404: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6405: if ($crsenv{'internal.courseowner'} eq
6406: $env{'user.name'}.':'.$env{'user.domain'}) {
6407: $refused = '';
6408: }
6409: }
6410: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6411: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6412: if ($crsenv{'internal.courseowner'} eq
6413: $env{'user.name'}.':'.$env{'user.domain'}) {
6414: $refused = '';
6415: }
6416: }
6417: }
6418: }
6419: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6420: $refused = '';
1.1017 raeburn 6421: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6422: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6423: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6424: my $wrongcc;
6425: if ($cnum =~ /^$match_community$/) {
6426: $wrongcc = 1 if ($role eq 'cc');
6427: } else {
6428: $wrongcc = 1 if ($role eq 'co');
6429: }
6430: unless ($wrongcc) {
6431: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6432: if ($crsenv{'internal.courseowner'} eq
6433: $env{'user.name'}.':'.$env{'user.domain'}) {
6434: $refused = '';
6435: }
1.1017 raeburn 6436: }
6437: }
6438: }
6439: if ($refused) {
1.947 raeburn 6440: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6441: ' '.$role.' '.$end.' '.$start.' by '.
6442: $env{'user.name'}.' at '.$env{'user.domain'});
6443: return 'refused';
6444: }
1.932 raeburn 6445: }
1.104 www 6446: }
1.21 www 6447: $mrole=$role;
6448: }
1.620 albertel 6449: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6450: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6451: if ($end) { $command.='_'.$end; }
1.21 www 6452: if ($start) {
6453: if ($end) {
1.81 www 6454: $command.='_'.$start;
1.21 www 6455: } else {
1.81 www 6456: $command.='_0_'.$start;
1.21 www 6457: }
6458: }
1.739 raeburn 6459: my $origstart = $start;
6460: my $origend = $end;
1.957 raeburn 6461: my $delflag;
1.357 www 6462: # actually delete
6463: if ($deleteflag) {
1.373 www 6464: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6465: # modify command to delete the role
1.620 albertel 6466: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6467: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6468: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6469: # set start and finish to negative values for userrolelog
6470: $start=-1;
6471: $end=-1;
1.957 raeburn 6472: $delflag = 1;
1.357 www 6473: }
6474: }
6475: # send command
1.349 www 6476: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6477: # log new user role if status is ok
1.349 www 6478: if ($answer eq 'ok') {
1.663 raeburn 6479: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6480: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6481: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6482: unless ($role =~ /^gr/) {
6483: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6484: $origstart,$selfenroll,$context);
1.739 raeburn 6485: }
1.1053 raeburn 6486: if ($role eq 'cc') {
6487: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6488: }
1.349 www 6489: }
6490: return $answer;
1.169 harris41 6491: }
6492:
1.1053 raeburn 6493: sub autoupdate_coowners {
6494: my ($url,$end,$start,$uname,$udom) = @_;
6495: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6496: if (($cdom ne '') && ($cnum ne '')) {
6497: my $now = time;
6498: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6499: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6500: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6501: my $instcode = $coursehash{'internal.coursecode'};
6502: if ($instcode ne '') {
1.1056 raeburn 6503: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6504: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6505: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6506: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6507: if ($result eq 'valid') {
6508: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6509: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6510: push(@newcoowners,$coowner);
6511: }
6512: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6513: push(@newcoowners,$uname.':'.$udom);
6514: }
6515: @newcoowners = sort(@newcoowners);
6516: } else {
6517: push(@newcoowners,$uname.':'.$udom);
6518: }
6519: } else {
6520: if ($coursehash{'internal.co-owners'}) {
6521: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6522: unless ($coowner eq $uname.':'.$udom) {
6523: push(@newcoowners,$coowner);
6524: }
6525: }
6526: unless (@newcoowners > 0) {
6527: $delcoowners = 1;
6528: $coowners = '';
6529: }
6530: }
6531: }
6532: if (@newcoowners || $delcoowners) {
6533: &store_coowners($cdom,$cnum,$coursehash{'home'},
6534: $delcoowners,@newcoowners);
6535: }
6536: }
6537: }
6538: }
6539: }
6540: }
6541: }
6542:
6543: sub store_coowners {
6544: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6545: my $cid = $cdom.'_'.$cnum;
6546: my ($coowners,$delresult,$putresult);
6547: if (@newcoowners) {
6548: $coowners = join(',',@newcoowners);
6549: my %coownershash = (
6550: 'internal.co-owners' => $coowners,
6551: );
6552: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6553: if ($putresult eq 'ok') {
6554: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6555: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6556: }
6557: }
6558: }
6559: if ($delcoowners) {
6560: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6561: if ($delresult eq 'ok') {
6562: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6563: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6564: }
6565: }
6566: }
6567: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6568: my %crsinfo =
6569: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6570: if (ref($crsinfo{$cid}) eq 'HASH') {
6571: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6572: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6573: }
6574: }
6575: }
6576:
1.169 harris41 6577: # -------------------------------------------------- Modify user authentication
1.197 www 6578: # Overrides without validation
6579:
1.169 harris41 6580: sub modifyuserauth {
6581: my ($udom,$uname,$umode,$upass)=@_;
6582: my $uhome=&homeserver($uname,$udom);
1.197 www 6583: unless (&allowed('mau',$udom)) { return 'refused'; }
6584: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6585: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6586: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6587: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6588: &escape($upass),$uhome);
1.620 albertel 6589: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6590: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6591: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6592: &log($udom,,$uname,$uhome,
1.620 albertel 6593: 'Authentication changed by '.$env{'user.domain'}.', '.
6594: $env{'user.name'}.', '.$umode.
1.197 www 6595: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6596: unless ($reply eq 'ok') {
1.197 www 6597: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6598: return 'error: '.$reply;
6599: }
1.170 harris41 6600: return 'ok';
1.80 www 6601: }
6602:
1.81 www 6603: # --------------------------------------------------------------- Modify a user
1.80 www 6604:
1.81 www 6605: sub modifyuser {
1.206 matthew 6606: my ($udom, $uname, $uid,
6607: $umode, $upass, $first,
6608: $middle, $last, $gene,
1.1058 raeburn 6609: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6610: $udom= &LONCAPA::clean_domain($udom);
6611: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6612: my $showcandelete = 'none';
6613: if (ref($candelete) eq 'ARRAY') {
6614: if (@{$candelete} > 0) {
6615: $showcandelete = join(', ',@{$candelete});
6616: }
6617: }
1.81 www 6618: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6619: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6620: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6621: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6622: ' desiredhome not specified').
1.620 albertel 6623: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6624: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6625: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6626: my $newuser;
6627: if ($uhome eq 'no_host') {
6628: $newuser = 1;
6629: }
1.80 www 6630: # ----------------------------------------------------------------- Create User
1.406 albertel 6631: if (($uhome eq 'no_host') &&
6632: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6633: my $unhome='';
1.844 albertel 6634: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6635: $unhome = $desiredhome;
1.620 albertel 6636: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6637: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6638: } else { # load balancing routine for determining $unhome
1.81 www 6639: my $loadm=10000000;
1.841 albertel 6640: my %servers = &get_servers($udom,'library');
6641: foreach my $tryserver (keys(%servers)) {
6642: my $answer=reply('load',$tryserver);
6643: if (($answer=~/\d+/) && ($answer<$loadm)) {
6644: $loadm=$answer;
6645: $unhome=$tryserver;
6646: }
1.80 www 6647: }
6648: }
6649: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6650: return 'error: unable to find a home server for '.$uname.
6651: ' in domain '.$udom;
1.80 www 6652: }
6653: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6654: &escape($upass),$unhome);
6655: unless ($reply eq 'ok') {
6656: return 'error: '.$reply;
6657: }
1.230 stredwic 6658: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6659: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6660: return 'error: unable verify users home machine.';
1.80 www 6661: }
1.209 matthew 6662: } # End of creation of new user
1.80 www 6663: # ---------------------------------------------------------------------- Add ID
6664: if ($uid) {
6665: $uid=~tr/A-Z/a-z/;
6666: my %uidhash=&idrget($udom,$uname);
1.196 www 6667: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6668: && (!$forceid)) {
1.80 www 6669: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6670: return 'error: user id "'.$uid.'" does not match '.
6671: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6672: }
6673: } else {
6674: &idput($udom,($uname => $uid));
6675: }
6676: }
6677: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6678: my @tmp=&get('environment',
1.899 raeburn 6679: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6680: 'permanentemail','inststatus'],
1.134 albertel 6681: $udom,$uname);
1.1075 raeburn 6682: my (%names,%oldnames);
1.313 matthew 6683: if ($tmp[0] =~ m/^error:.*/) {
6684: %names=();
6685: } else {
6686: %names = @tmp;
1.1075 raeburn 6687: %oldnames = %names;
1.313 matthew 6688: }
1.388 www 6689: #
1.1058 raeburn 6690: # If name, email and/or uid are blank (e.g., because an uploaded file
6691: # of users did not contain them), do not overwrite existing values
6692: # unless field is in $candelete array ref.
6693: #
6694:
6695: my @fields = ('firstname','middlename','lastname','generation',
6696: 'permanentemail','id');
6697: my %newvalues;
6698: if (ref($candelete) eq 'ARRAY') {
6699: foreach my $field (@fields) {
6700: if (grep(/^\Q$field\E$/,@{$candelete})) {
6701: if ($field eq 'firstname') {
6702: $names{$field} = $first;
6703: } elsif ($field eq 'middlename') {
6704: $names{$field} = $middle;
6705: } elsif ($field eq 'lastname') {
6706: $names{$field} = $last;
6707: } elsif ($field eq 'generation') {
6708: $names{$field} = $gene;
6709: } elsif ($field eq 'permanentemail') {
6710: $names{$field} = $email;
6711: } elsif ($field eq 'id') {
6712: $names{$field} = $uid;
6713: }
6714: }
6715: }
6716: }
1.388 www 6717: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6718: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6719: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6720: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6721: if ($email) {
6722: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6723: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6724: }
1.899 raeburn 6725: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6726: if (defined($inststatus)) {
6727: $names{'inststatus'} = '';
6728: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6729: if (ref($usertypes) eq 'HASH') {
6730: my @okstatuses;
6731: foreach my $item (split(/:/,$inststatus)) {
6732: if (defined($usertypes->{$item})) {
6733: push(@okstatuses,$item);
6734: }
6735: }
6736: if (@okstatuses) {
6737: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6738: }
6739: }
6740: }
1.1075 raeburn 6741: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6742: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6743: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6744: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6745: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6746: } else {
6747: $logmsg .= ' during self creation';
6748: }
1.1075 raeburn 6749: my $changed;
6750: if ($newuser) {
6751: $changed = 1;
6752: } else {
6753: foreach my $field (@fields) {
6754: if ($names{$field} ne $oldnames{$field}) {
6755: $changed = 1;
6756: last;
6757: }
6758: }
6759: }
6760: unless ($changed) {
6761: $logmsg = 'No changes in user information needed for: '.$logmsg;
6762: &logthis($logmsg);
6763: return 'ok';
6764: }
6765: my $reply = &put('environment', \%names, $udom,$uname);
6766: if ($reply ne 'ok') {
6767: return 'error: '.$reply;
6768: }
6769: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6770: &devalidate_cache_new('namescache',$uname.':'.$udom);
6771: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6772: &logthis($logmsg);
1.134 albertel 6773: return 'ok';
1.80 www 6774: }
6775:
1.81 www 6776: # -------------------------------------------------------------- Modify student
1.80 www 6777:
1.81 www 6778: sub modifystudent {
6779: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6780: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6781: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6782: if (!$cid) {
1.620 albertel 6783: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6784: return 'not_in_class';
6785: }
1.80 www 6786: }
6787: # --------------------------------------------------------------- Make the user
1.81 www 6788: my $reply=&modifyuser
1.209 matthew 6789: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6790: $desiredhome,$email,$inststatus);
1.80 www 6791: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6792: # This will cause &modify_student_enrollment to get the uid from the
6793: # students environment
6794: $uid = undef if (!$forceid);
1.455 albertel 6795: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6796: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6797: return $reply;
6798: }
6799:
6800: sub modify_student_enrollment {
1.957 raeburn 6801: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6802: my ($cdom,$cnum,$chome);
6803: if (!$cid) {
1.620 albertel 6804: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6805: return 'not_in_class';
6806: }
1.620 albertel 6807: $cdom=$env{'course.'.$cid.'.domain'};
6808: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6809: } else {
6810: ($cdom,$cnum)=split(/_/,$cid);
6811: }
1.620 albertel 6812: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6813: if (!$chome) {
1.457 raeburn 6814: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6815: }
1.455 albertel 6816: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6817: # Make sure the user exists
1.81 www 6818: my $uhome=&homeserver($uname,$udom);
6819: if (($uhome eq '') || ($uhome eq 'no_host')) {
6820: return 'error: no such user';
6821: }
1.297 matthew 6822: # Get student data if we were not given enough information
6823: if (!defined($first) || $first eq '' ||
6824: !defined($last) || $last eq '' ||
6825: !defined($uid) || $uid eq '' ||
6826: !defined($middle) || $middle eq '' ||
6827: !defined($gene) || $gene eq '') {
1.294 matthew 6828: # They did not supply us with enough data to enroll the student, so
6829: # we need to pick up more information.
1.297 matthew 6830: my %tmp = &get('environment',
1.294 matthew 6831: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6832: ,$udom,$uname);
6833:
1.800 albertel 6834: #foreach my $key (keys(%tmp)) {
6835: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6836: #}
1.294 matthew 6837: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6838: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6839: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6840: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6841: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6842: }
1.556 albertel 6843: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6844: my $reply=cput('classlist',
6845: {"$uname:$udom" =>
1.515 raeburn 6846: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6847: $cdom,$cnum);
1.81 www 6848: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6849: return 'error: '.$reply;
1.652 albertel 6850: } else {
6851: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6852: }
1.297 matthew 6853: # Add student role to user
1.83 www 6854: my $uurl='/'.$cid;
1.81 www 6855: $uurl=~s/\_/\//g;
6856: if ($usec) {
6857: $uurl.='/'.$usec;
6858: }
1.957 raeburn 6859: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6860: }
6861:
1.556 albertel 6862: sub format_name {
6863: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6864: my $name;
6865: if ($first ne 'lastname') {
6866: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6867: } else {
6868: if ($lastname=~/\S/) {
6869: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6870: $name=~s/\s+,/,/;
6871: } else {
6872: $name.= $firstname.' '.$middlename.' '.$generation;
6873: }
6874: }
6875: $name=~s/^\s+//;
6876: $name=~s/\s+$//;
6877: $name=~s/\s+/ /g;
6878: return $name;
6879: }
6880:
1.84 www 6881: # ------------------------------------------------- Write to course preferences
6882:
6883: sub writecoursepref {
6884: my ($courseid,%prefs)=@_;
6885: $courseid=~s/^\///;
6886: $courseid=~s/\_/\//g;
6887: my ($cdomain,$cnum)=split(/\//,$courseid);
6888: my $chome=homeserver($cnum,$cdomain);
6889: if (($chome eq '') || ($chome eq 'no_host')) {
6890: return 'error: no such course';
6891: }
6892: my $cstring='';
1.800 albertel 6893: foreach my $pref (keys(%prefs)) {
6894: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6895: }
1.84 www 6896: $cstring=~s/\&$//;
6897: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6898: }
6899:
6900: # ---------------------------------------------------------- Make/modify course
6901:
6902: sub createcourse {
1.741 raeburn 6903: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6904: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6905: $url=&declutter($url);
6906: my $cid='';
1.1028 raeburn 6907: if ($context eq 'requestcourses') {
6908: my $can_create = 0;
6909: my ($ownername,$ownerdom) = split(':',$course_owner);
6910: if ($udom eq $ownerdom) {
6911: if (&usertools_access($ownername,$ownerdom,$category,undef,
6912: $context)) {
6913: $can_create = 1;
6914: }
6915: } else {
6916: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6917: $category);
6918: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6919: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6920: if (@curr > 0) {
6921: my @options = qw(approval validate autolimit);
6922: my $optregex = join('|',@options);
6923: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6924: $can_create = 1;
6925: }
6926: }
6927: }
6928: }
6929: if ($can_create) {
6930: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6931: unless (&allowed('ccc',$udom)) {
6932: return 'refused';
6933: }
1.1017 raeburn 6934: }
6935: } else {
6936: return 'refused';
6937: }
1.1028 raeburn 6938: } elsif (!&allowed('ccc',$udom)) {
6939: return 'refused';
1.84 www 6940: }
1.1011 raeburn 6941: # --------------------------------------------------------------- Get Unique ID
6942: my $uname;
6943: if ($cnum =~ /^$match_courseid$/) {
6944: my $chome=&homeserver($cnum,$udom,'true');
6945: if (($chome eq '') || ($chome eq 'no_host')) {
6946: $uname = $cnum;
6947: } else {
1.1038 raeburn 6948: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6949: }
6950: } else {
1.1038 raeburn 6951: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6952: }
6953: return $uname if ($uname =~ /^error/);
6954: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6955: if (!defined($course_server)) {
6956: if (defined(&domain($udom,'primary'))) {
6957: $course_server = &domain($udom,'primary');
6958: } else {
6959: $course_server = $env{'user.home'};
6960: }
6961: }
6962: my %host_servers =
6963: &Apache::lonnet::get_servers($udom,'library');
6964: unless ($host_servers{$course_server}) {
6965: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6966: }
1.84 www 6967: # ------------------------------------------------------------- Make the course
6968: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6969: $course_server);
1.84 www 6970: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6971: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6972: if (($uhome eq '') || ($uhome eq 'no_host')) {
6973: return 'error: no such course';
6974: }
1.271 www 6975: # ----------------------------------------------------------------- Course made
1.516 raeburn 6976: # log existence
1.1029 raeburn 6977: my $now = time;
1.918 raeburn 6978: my $newcourse = {
6979: $udom.'_'.$uname => {
1.921 raeburn 6980: description => $description,
6981: inst_code => $inst_code,
6982: owner => $course_owner,
6983: type => $crstype,
1.1029 raeburn 6984: creator => $env{'user.name'}.':'.
6985: $env{'user.domain'},
6986: created => $now,
6987: context => $context,
1.918 raeburn 6988: },
6989: };
1.921 raeburn 6990: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6991: # set toplevel url
1.271 www 6992: my $topurl=$url;
6993: unless ($nonstandard) {
6994: # ------------------------------------------ For standard courses, make top url
6995: my $mapurl=&clutter($url);
1.278 www 6996: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6997: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6998: <map>
6999: <resource id="1" type="start"></resource>
7000: <resource id="2" src="$mapurl"></resource>
7001: <resource id="3" type="finish"></resource>
7002: <link index="1" from="1" to="2"></link>
7003: <link index="2" from="2" to="3"></link>
7004: </map>
7005: ENDINITMAP
7006: $topurl=&declutter(
1.638 albertel 7007: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7008: );
7009: }
7010: # ----------------------------------------------------------- Write preferences
1.84 www 7011: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7012: ('description' => $description,
7013: 'url' => $topurl,
7014: 'internal.creator' => $env{'user.name'}.':'.
7015: $env{'user.domain'},
7016: 'internal.created' => $now,
7017: 'internal.creationcontext' => $context)
7018: );
1.84 www 7019: return '/'.$udom.'/'.$uname;
7020: }
7021:
1.1011 raeburn 7022: # ------------------------------------------------------------------- Create ID
7023: sub generate_coursenum {
1.1038 raeburn 7024: my ($udom,$crstype) = @_;
1.1011 raeburn 7025: my $domdesc = &domain($udom);
7026: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7027: my $first;
7028: if ($crstype eq 'Community') {
7029: $first = '0';
7030: } else {
7031: $first = int(1+rand(9));
7032: }
7033: my $uname=$first.
1.1011 raeburn 7034: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7035: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7036: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7037: # ----------------------------------------------- Make sure that does not exist
7038: my $uhome=&homeserver($uname,$udom,'true');
7039: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7040: if ($crstype eq 'Community') {
7041: $first = '0';
7042: } else {
7043: $first = int(1+rand(9));
7044: }
7045: $uname=$first.
1.1011 raeburn 7046: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7047: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7048: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7049: $uhome=&homeserver($uname,$udom,'true');
7050: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7051: return 'error: unable to generate unique course-ID';
7052: }
7053: }
7054: return $uname;
7055: }
7056:
1.813 albertel 7057: sub is_course {
7058: my ($cdom,$cnum) = @_;
7059: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7060: undef,'.');
1.813 albertel 7061: if (exists($courses{$cdom.'_'.$cnum})) {
7062: return 1;
7063: }
7064: return 0;
7065: }
7066:
1.1015 raeburn 7067: sub store_userdata {
7068: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7069: my $result;
1.1016 raeburn 7070: if ($datakey ne '') {
1.1013 raeburn 7071: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7072: if ($udom eq '' || $uname eq '') {
7073: $udom = $env{'user.domain'};
7074: $uname = $env{'user.name'};
7075: }
7076: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7077: if (($uhome eq '') || ($uhome eq 'no_host')) {
7078: $result = 'error: no_host';
7079: } else {
7080: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7081: $storehash->{'host'} = $perlvar{'lonHostID'};
7082:
7083: my $namevalue='';
7084: foreach my $key (keys(%{$storehash})) {
7085: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7086: }
7087: $namevalue=~s/\&$//;
7088: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7089: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7090: }
7091: } else {
7092: $result = 'error: data to store was not a hash reference';
7093: }
7094: } else {
7095: $result= 'error: invalid requestkey';
7096: }
7097: return $result;
7098: }
7099:
1.21 www 7100: # ---------------------------------------------------------- Assign Custom Role
7101:
7102: sub assigncustomrole {
1.957 raeburn 7103: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7104: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7105: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7106: }
7107:
7108: # ----------------------------------------------------------------- Revoke Role
7109:
7110: sub revokerole {
1.957 raeburn 7111: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7112: my $now=time;
1.965 raeburn 7113: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7114: }
7115:
7116: # ---------------------------------------------------------- Revoke Custom Role
7117:
7118: sub revokecustomrole {
1.957 raeburn 7119: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7120: my $now=time;
1.357 www 7121: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7122: $deleteflag,$selfenroll,$context);
1.17 www 7123: }
7124:
1.533 banghart 7125: # ------------------------------------------------------------ Disk usage
1.535 albertel 7126: sub diskusage {
1.955 raeburn 7127: my ($udom,$uname,$directorypath,$getpropath)=@_;
7128: $directorypath =~ s/\/$//;
7129: my $listing=&reply('du2:'.&escape($directorypath).':'
7130: .&escape($getpropath).':'.&escape($uname).':'
7131: .&escape($udom),homeserver($uname,$udom));
7132: if ($listing eq 'unknown_cmd') {
7133: if ($getpropath) {
7134: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7135: }
7136: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7137: }
1.514 albertel 7138: return $listing;
1.512 banghart 7139: }
7140:
1.566 banghart 7141: sub is_locked {
7142: my ($file_name, $domain, $user) = @_;
7143: my @check;
7144: my $is_locked;
7145: push @check, $file_name;
1.613 albertel 7146: my %locked = &get('file_permissions',\@check,
1.620 albertel 7147: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7148: my ($tmp)=keys(%locked);
7149: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7150:
1.566 banghart 7151: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7152: $is_locked = 'false';
7153: foreach my $entry (@{$locked{$file_name}}) {
7154: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7155: $is_locked = 'true';
7156: last;
1.745 raeburn 7157: }
7158: }
1.566 banghart 7159: } else {
7160: $is_locked = 'false';
7161: }
7162: }
7163:
1.759 albertel 7164: sub declutter_portfile {
7165: my ($file) = @_;
1.833 albertel 7166: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7167: return $file;
7168: }
7169:
1.559 banghart 7170: # ------------------------------------------------------------- Mark as Read Only
7171:
7172: sub mark_as_readonly {
7173: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7174: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7175: my ($tmp)=keys(%current_permissions);
7176: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7177: foreach my $file (@{$files}) {
1.759 albertel 7178: $file = &declutter_portfile($file);
1.561 banghart 7179: push(@{$current_permissions{$file}},$what);
1.559 banghart 7180: }
1.613 albertel 7181: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7182: return;
7183: }
7184:
1.572 banghart 7185: # ------------------------------------------------------------Save Selected Files
7186:
7187: sub save_selected_files {
7188: my ($user, $path, @files) = @_;
7189: my $filename = $user."savedfiles";
1.573 banghart 7190: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7191: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7192: foreach my $file (@files) {
1.620 albertel 7193: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7194: }
7195: foreach my $file (@other_files) {
1.574 banghart 7196: print (OUT $file."\n");
1.572 banghart 7197: }
1.574 banghart 7198: close (OUT);
1.572 banghart 7199: return 'ok';
7200: }
7201:
1.574 banghart 7202: sub clear_selected_files {
7203: my ($user) = @_;
7204: my $filename = $user."savedfiles";
7205: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7206: print (OUT undef);
7207: close (OUT);
7208: return ("ok");
7209: }
7210:
1.572 banghart 7211: sub files_in_path {
7212: my ($user, $path) = @_;
7213: my $filename = $user."savedfiles";
7214: my %return_files;
1.574 banghart 7215: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7216: while (my $line_in = <IN>) {
1.574 banghart 7217: chomp ($line_in);
7218: my @paths_and_file = split (m!/!, $line_in);
7219: my $file_part = pop (@paths_and_file);
7220: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7221: $path_part.='/';
7222: my $path_and_file = $path_part.$file_part;
7223: if ($path_part eq $path) {
7224: $return_files{$file_part}= 'selected';
7225: }
7226: }
1.574 banghart 7227: close (IN);
7228: return (\%return_files);
1.572 banghart 7229: }
7230:
7231: # called in portfolio select mode, to show files selected NOT in current directory
7232: sub files_not_in_path {
7233: my ($user, $path) = @_;
7234: my $filename = $user."savedfiles";
7235: my @return_files;
7236: my $path_part;
1.800 albertel 7237: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7238: while (my $line = <IN>) {
1.572 banghart 7239: #ok, I know it's clunky, but I want it to work
1.800 albertel 7240: my @paths_and_file = split(m|/|, $line);
7241: my $file_part = pop(@paths_and_file);
7242: chomp($file_part);
7243: my $path_part = join('/', @paths_and_file);
1.572 banghart 7244: $path_part .= '/';
7245: my $path_and_file = $path_part.$file_part;
7246: if ($path_part ne $path) {
1.800 albertel 7247: push(@return_files, ($path_and_file));
1.572 banghart 7248: }
7249: }
1.800 albertel 7250: close(OUT);
1.574 banghart 7251: return (@return_files);
1.572 banghart 7252: }
7253:
1.745 raeburn 7254: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7255:
1.745 raeburn 7256: sub get_portfile_permissions {
7257: my ($domain,$user) = @_;
1.613 albertel 7258: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7259: my ($tmp)=keys(%current_permissions);
7260: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7261: return \%current_permissions;
7262: }
7263:
7264: #---------------------------------------------Get portfolio file access controls
7265:
1.749 raeburn 7266: sub get_access_controls {
1.745 raeburn 7267: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7268: my %access;
7269: my $real_file = $file;
7270: $file =~ s/\.meta$//;
1.745 raeburn 7271: if (defined($file)) {
1.749 raeburn 7272: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7273: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7274: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7275: }
7276: }
1.745 raeburn 7277: } else {
1.749 raeburn 7278: foreach my $key (keys(%{$current_permissions})) {
7279: if ($key =~ /\0accesscontrol$/) {
7280: if (defined($group)) {
7281: if ($key !~ m-^\Q$group\E/-) {
7282: next;
7283: }
7284: }
7285: my ($fullpath) = split(/\0/,$key);
7286: if (ref($$current_permissions{$key}) eq 'HASH') {
7287: foreach my $control (keys(%{$$current_permissions{$key}})) {
7288: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7289: }
7290: }
7291: }
7292: }
7293: }
7294: return %access;
7295: }
7296:
7297: sub modify_access_controls {
7298: my ($file_name,$changes,$domain,$user)=@_;
7299: my ($outcome,$deloutcome);
7300: my %store_permissions;
7301: my %new_values;
7302: my %new_control;
7303: my %translation;
7304: my @deletions = ();
7305: my $now = time;
7306: if (exists($$changes{'activate'})) {
7307: if (ref($$changes{'activate'}) eq 'HASH') {
7308: my @newitems = sort(keys(%{$$changes{'activate'}}));
7309: my $numnew = scalar(@newitems);
7310: for (my $i=0; $i<$numnew; $i++) {
7311: my $newkey = $newitems[$i];
7312: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7313: if ($newkey =~ /^\d+:/) {
7314: $newkey =~ s/^(\d+)/$newid/;
7315: $translation{$1} = $newid;
7316: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7317: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7318: $translation{$1} = $newid;
7319: }
1.749 raeburn 7320: $new_values{$file_name."\0".$newkey} =
7321: $$changes{'activate'}{$newitems[$i]};
7322: $new_control{$newkey} = $now;
7323: }
7324: }
7325: }
7326: my %todelete;
7327: my %changed_items;
7328: foreach my $action ('delete','update') {
7329: if (exists($$changes{$action})) {
7330: if (ref($$changes{$action}) eq 'HASH') {
7331: foreach my $key (keys(%{$$changes{$action}})) {
7332: my ($itemnum) = ($key =~ /^([^:]+):/);
7333: if ($action eq 'delete') {
7334: $todelete{$itemnum} = 1;
7335: } else {
7336: $changed_items{$itemnum} = $key;
7337: }
7338: }
1.745 raeburn 7339: }
7340: }
1.749 raeburn 7341: }
7342: # get lock on access controls for file.
7343: my $lockhash = {
7344: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7345: ':'.$env{'user.domain'},
7346: };
7347: my $tries = 0;
7348: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7349:
7350: while (($gotlock ne 'ok') && $tries <3) {
7351: $tries ++;
7352: sleep 1;
7353: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7354: }
7355: if ($gotlock eq 'ok') {
7356: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7357: my ($tmp)=keys(%curr_permissions);
7358: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7359: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7360: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7361: if (ref($curr_controls) eq 'HASH') {
7362: foreach my $control_item (keys(%{$curr_controls})) {
7363: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7364: if (defined($todelete{$itemnum})) {
7365: push(@deletions,$file_name."\0".$control_item);
7366: } else {
7367: if (defined($changed_items{$itemnum})) {
7368: $new_control{$changed_items{$itemnum}} = $now;
7369: push(@deletions,$file_name."\0".$control_item);
7370: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7371: } else {
7372: $new_control{$control_item} = $$curr_controls{$control_item};
7373: }
7374: }
1.745 raeburn 7375: }
7376: }
7377: }
1.970 raeburn 7378: my ($group);
7379: if (&is_course($domain,$user)) {
7380: ($group,my $file) = split(/\//,$file_name,2);
7381: }
1.749 raeburn 7382: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7383: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7384: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7385: # remove lock
7386: my @del_lock = ($file_name."\0".'locked_access_records');
7387: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7388: my $sqlresult =
1.970 raeburn 7389: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7390: $group);
1.749 raeburn 7391: } else {
7392: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7393: }
1.749 raeburn 7394: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7395: }
7396:
1.827 raeburn 7397: sub make_public_indefinitely {
7398: my ($requrl) = @_;
7399: my $now = time;
7400: my $action = 'activate';
7401: my $aclnum = 0;
7402: if (&is_portfolio_url($requrl)) {
7403: my (undef,$udom,$unum,$file_name,$group) =
7404: &parse_portfolio_url($requrl);
7405: my $current_perms = &get_portfile_permissions($udom,$unum);
7406: my %access_controls = &get_access_controls($current_perms,
7407: $group,$file_name);
7408: foreach my $key (keys(%{$access_controls{$file_name}})) {
7409: my ($num,$scope,$end,$start) =
7410: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7411: if ($scope eq 'public') {
7412: if ($start <= $now && $end == 0) {
7413: $action = 'none';
7414: } else {
7415: $action = 'update';
7416: $aclnum = $num;
7417: }
7418: last;
7419: }
7420: }
7421: if ($action eq 'none') {
7422: return 'ok';
7423: } else {
7424: my %changes;
7425: my $newend = 0;
7426: my $newstart = $now;
7427: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7428: $changes{$action}{$newkey} = {
7429: type => 'public',
7430: time => {
7431: start => $newstart,
7432: end => $newend,
7433: },
7434: };
7435: my ($outcome,$deloutcome,$new_values,$translation) =
7436: &modify_access_controls($file_name,\%changes,$udom,$unum);
7437: return $outcome;
7438: }
7439: } else {
7440: return 'invalid';
7441: }
7442: }
7443:
1.745 raeburn 7444: #------------------------------------------------------Get Marked as Read Only
7445:
7446: sub get_marked_as_readonly {
7447: my ($domain,$user,$what,$group) = @_;
7448: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7449: my @readonly_files;
1.629 banghart 7450: my $cmp1=$what;
7451: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7452: while (my ($file_name,$value) = each(%{$current_permissions})) {
7453: if (defined($group)) {
7454: if ($file_name !~ m-^\Q$group\E/-) {
7455: next;
7456: }
7457: }
1.561 banghart 7458: if (ref($value) eq "ARRAY"){
7459: foreach my $stored_what (@{$value}) {
1.629 banghart 7460: my $cmp2=$stored_what;
1.759 albertel 7461: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7462: $cmp2=join('',@{$stored_what});
1.745 raeburn 7463: }
1.629 banghart 7464: if ($cmp1 eq $cmp2) {
1.561 banghart 7465: push(@readonly_files, $file_name);
1.745 raeburn 7466: last;
1.563 banghart 7467: } elsif (!defined($what)) {
7468: push(@readonly_files, $file_name);
1.745 raeburn 7469: last;
1.561 banghart 7470: }
7471: }
1.745 raeburn 7472: }
1.561 banghart 7473: }
7474: return @readonly_files;
7475: }
1.577 banghart 7476: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7477:
1.577 banghart 7478: sub get_marked_as_readonly_hash {
1.745 raeburn 7479: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7480: my %readonly_files;
1.745 raeburn 7481: while (my ($file_name,$value) = each(%{$current_permissions})) {
7482: if (defined($group)) {
7483: if ($file_name !~ m-^\Q$group\E/-) {
7484: next;
7485: }
7486: }
1.577 banghart 7487: if (ref($value) eq "ARRAY"){
7488: foreach my $stored_what (@{$value}) {
1.745 raeburn 7489: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7490: foreach my $lock_descriptor(@{$stored_what}) {
7491: if ($lock_descriptor eq 'graded') {
7492: $readonly_files{$file_name} = 'graded';
7493: } elsif ($lock_descriptor eq 'handback') {
7494: $readonly_files{$file_name} = 'handback';
7495: } else {
7496: if (!exists($readonly_files{$file_name})) {
7497: $readonly_files{$file_name} = 'locked';
7498: }
7499: }
1.745 raeburn 7500: }
1.750 banghart 7501: }
1.577 banghart 7502: }
7503: }
7504: }
7505: return %readonly_files;
7506: }
1.559 banghart 7507: # ------------------------------------------------------------ Unmark as Read Only
7508:
7509: sub unmark_as_readonly {
1.629 banghart 7510: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7511: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7512: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7513: $file_name = &declutter_portfile($file_name);
1.634 albertel 7514: my $symb_crs = $what;
7515: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7516: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7517: my ($tmp)=keys(%current_permissions);
7518: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7519: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7520: foreach my $file (@readonly_files) {
1.759 albertel 7521: my $clean_file = &declutter_portfile($file);
7522: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7523: my $current_locks = $current_permissions{$file};
1.563 banghart 7524: my @new_locks;
7525: my @del_keys;
7526: if (ref($current_locks) eq "ARRAY"){
7527: foreach my $locker (@{$current_locks}) {
1.632 albertel 7528: my $compare=$locker;
1.749 raeburn 7529: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7530: $compare=join('',@{$locker});
1.746 raeburn 7531: if ($compare ne $symb_crs) {
7532: push(@new_locks, $locker);
7533: }
1.563 banghart 7534: }
7535: }
1.650 albertel 7536: if (scalar(@new_locks) > 0) {
1.563 banghart 7537: $current_permissions{$file} = \@new_locks;
7538: } else {
7539: push(@del_keys, $file);
1.613 albertel 7540: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7541: delete($current_permissions{$file});
1.563 banghart 7542: }
7543: }
1.561 banghart 7544: }
1.613 albertel 7545: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7546: return;
7547: }
1.512 banghart 7548:
1.17 www 7549: # ------------------------------------------------------------ Directory lister
7550:
7551: sub dirlist {
1.955 raeburn 7552: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7553: $uri=~s/^\///;
7554: $uri=~s/\/$//;
1.253 stredwic 7555: my ($udom, $uname);
1.955 raeburn 7556: if ($getuserdir) {
1.253 stredwic 7557: $udom = $userdomain;
7558: $uname = $username;
1.955 raeburn 7559: } else {
7560: (undef,$udom,$uname)=split(/\//,$uri);
7561: if(defined($userdomain)) {
7562: $udom = $userdomain;
7563: }
7564: if(defined($username)) {
7565: $uname = $username;
7566: }
1.253 stredwic 7567: }
1.955 raeburn 7568: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7569:
1.955 raeburn 7570: $dirRoot = $perlvar{'lonDocRoot'};
7571: if (defined($getpropath)) {
7572: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7573: $dirRoot =~ s/\/$//;
1.955 raeburn 7574: } elsif (defined($getuserdir)) {
7575: my $subdir=$uname.'__';
7576: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7577: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7578: ."/$udom/$subdir/$uname";
7579: } elsif (defined($alternateRoot)) {
7580: $dirRoot = $alternateRoot;
1.751 banghart 7581: }
1.253 stredwic 7582:
7583: if($udom) {
7584: if($uname) {
1.955 raeburn 7585: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7586: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7587: .':'.&escape($uname).':'.&escape($udom),
7588: &homeserver($uname,$udom));
7589: if ($listing eq 'unknown_cmd') {
7590: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7591: &homeserver($uname,$udom));
7592: } else {
7593: @listing_results = map { &unescape($_); } split(/:/,$listing);
7594: }
1.605 matthew 7595: if ($listing eq 'unknown_cmd') {
1.800 albertel 7596: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7597: &homeserver($uname,$udom));
1.605 matthew 7598: @listing_results = split(/:/,$listing);
7599: } else {
7600: @listing_results = map { &unescape($_); } split(/:/,$listing);
7601: }
7602: return @listing_results;
1.955 raeburn 7603: } elsif(!$alternateRoot) {
1.800 albertel 7604: my %allusers;
1.841 albertel 7605: my %servers = &get_servers($udom,'library');
1.955 raeburn 7606: foreach my $tryserver (keys(%servers)) {
7607: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7608: &escape($udom),$tryserver);
7609: if ($listing eq 'unknown_cmd') {
7610: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7611: $udom, $tryserver);
7612: } else {
7613: @listing_results = map { &unescape($_); } split(/:/,$listing);
7614: }
1.841 albertel 7615: if ($listing eq 'unknown_cmd') {
7616: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7617: $udom, $tryserver);
7618: @listing_results = split(/:/,$listing);
7619: } else {
7620: @listing_results =
7621: map { &unescape($_); } split(/:/,$listing);
7622: }
7623: if ($listing_results[0] ne 'no_such_dir' &&
7624: $listing_results[0] ne 'empty' &&
7625: $listing_results[0] ne 'con_lost') {
7626: foreach my $line (@listing_results) {
7627: my ($entry) = split(/&/,$line,2);
7628: $allusers{$entry} = 1;
7629: }
7630: }
1.253 stredwic 7631: }
7632: my $alluserstr='';
1.800 albertel 7633: foreach my $user (sort(keys(%allusers))) {
7634: $alluserstr.=$user.'&user:';
1.253 stredwic 7635: }
7636: $alluserstr=~s/:$//;
7637: return split(/:/,$alluserstr);
7638: } else {
1.800 albertel 7639: return ('missing user name');
1.253 stredwic 7640: }
1.955 raeburn 7641: } elsif(!defined($getpropath)) {
1.841 albertel 7642: my @all_domains = sort(&all_domains());
1.955 raeburn 7643: foreach my $domain (@all_domains) {
7644: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7645: }
7646: return @all_domains;
7647: } else {
1.800 albertel 7648: return ('missing domain');
1.275 stredwic 7649: }
7650: }
7651:
7652: # --------------------------------------------- GetFileTimestamp
7653: # This function utilizes dirlist and returns the date stamp for
7654: # when it was last modified. It will also return an error of -1
7655: # if an error occurs
7656:
7657: sub GetFileTimestamp {
1.955 raeburn 7658: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7659: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7660: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7661: my ($fileStat) =
7662: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7663: undef,$getuserdir);
1.275 stredwic 7664: my @stats = split('&', $fileStat);
7665: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7666: # @stats contains first the filename, then the stat output
7667: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7668: } else {
7669: return -1;
1.253 stredwic 7670: }
1.26 www 7671: }
7672:
1.712 albertel 7673: sub stat_file {
7674: my ($uri) = @_;
1.787 albertel 7675: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7676:
1.955 raeburn 7677: my ($udom,$uname,$file);
1.712 albertel 7678: if ($uri =~ m-^/(uploaded|editupload)/-) {
7679: ($udom,$uname,$file) =
1.811 albertel 7680: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7681: $file = 'userfiles/'.$file;
7682: }
7683: if ($uri =~ m-^/res/-) {
7684: ($udom,$uname) =
1.807 albertel 7685: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7686: $file = $uri;
7687: }
7688:
7689: if (!$udom || !$uname || !$file) {
7690: # unable to handle the uri
7691: return ();
7692: }
1.956 raeburn 7693: my $getpropath;
7694: if ($file =~ /^userfiles\//) {
7695: $getpropath = 1;
7696: }
1.955 raeburn 7697: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7698: my @stats = split('&', $result);
1.721 banghart 7699:
1.712 albertel 7700: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7701: shift(@stats); #filename is first
7702: return @stats;
7703: }
7704: return ();
7705: }
7706:
1.26 www 7707: # -------------------------------------------------------- Value of a Condition
7708:
1.713 albertel 7709: # gets the value of a specific preevaluated condition
7710: # stored in the string $env{user.state.<cid>}
7711: # or looks up a condition reference in the bighash and if if hasn't
7712: # already been evaluated recurses into docondval to get the value of
7713: # the condition, then memoizing it to
7714: # $env{user.state.<cid>.<condition>}
1.40 www 7715: sub directcondval {
7716: my $number=shift;
1.620 albertel 7717: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7718: &Apache::lonuserstate::evalstate();
7719: }
1.713 albertel 7720: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7721: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7722: } elsif ($number =~ /^_/) {
7723: my $sub_condition;
7724: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7725: &GDBM_READER(),0640)) {
7726: $sub_condition=$bighash{'conditions'.$number};
7727: untie(%bighash);
7728: }
7729: my $value = &docondval($sub_condition);
1.949 raeburn 7730: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7731: return $value;
7732: }
1.620 albertel 7733: if ($env{'user.state.'.$env{'request.course.id'}}) {
7734: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7735: } else {
7736: return 2;
7737: }
7738: }
7739:
1.713 albertel 7740: # get the collection of conditions for this resource
1.26 www 7741: sub condval {
7742: my $condidx=shift;
1.54 www 7743: my $allpathcond='';
1.713 albertel 7744: foreach my $cond (split(/\|/,$condidx)) {
7745: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7746: $allpathcond.=
7747: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7748: }
1.191 harris41 7749: }
1.54 www 7750: $allpathcond=~s/\|$//;
1.713 albertel 7751: return &docondval($allpathcond);
7752: }
7753:
7754: #evaluates an expression of conditions
7755: sub docondval {
7756: my ($allpathcond) = @_;
7757: my $result=0;
7758: if ($env{'request.course.id'}
7759: && defined($allpathcond)) {
7760: my $operand='|';
7761: my @stack;
7762: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7763: if ($chunk eq '(') {
7764: push @stack,($operand,$result);
7765: } elsif ($chunk eq ')') {
7766: my $before=pop @stack;
7767: if (pop @stack eq '&') {
7768: $result=$result>$before?$before:$result;
7769: } else {
7770: $result=$result>$before?$result:$before;
7771: }
7772: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7773: $operand=$chunk;
7774: } else {
7775: my $new=directcondval($chunk);
7776: if ($operand eq '&') {
7777: $result=$result>$new?$new:$result;
7778: } else {
7779: $result=$result>$new?$result:$new;
7780: }
7781: }
7782: }
1.26 www 7783: }
7784: return $result;
1.421 albertel 7785: }
7786:
7787: # ---------------------------------------------------- Devalidate courseresdata
7788:
7789: sub devalidatecourseresdata {
7790: my ($coursenum,$coursedomain)=@_;
7791: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7792: &devalidate_cache_new('courseres',$hashid);
1.28 www 7793: }
7794:
1.763 www 7795:
1.200 www 7796: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7797: #
7798: # Parameters:
7799: # $coursenum - Number of the course.
7800: # $coursedomain - Domain at which the course was created.
7801: # Returns:
7802: # A hash of the course parameters along (I think) with timestamps
7803: # and version info.
1.877 foxr 7804:
1.624 albertel 7805: sub get_courseresdata {
7806: my ($coursenum,$coursedomain)=@_;
1.200 www 7807: my $coursehom=&homeserver($coursenum,$coursedomain);
7808: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7809: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7810: my %dumpreply;
1.417 albertel 7811: unless (defined($cached)) {
1.624 albertel 7812: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7813: $result=\%dumpreply;
1.251 albertel 7814: my ($tmp) = keys(%dumpreply);
7815: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7816: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7817: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7818: return $tmp;
1.416 albertel 7819: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7820: $result=undef;
1.599 albertel 7821: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7822: }
7823: }
1.624 albertel 7824: return $result;
7825: }
7826:
1.633 albertel 7827: sub devalidateuserresdata {
7828: my ($uname,$udom)=@_;
7829: my $hashid="$udom:$uname";
7830: &devalidate_cache_new('userres',$hashid);
7831: }
7832:
1.624 albertel 7833: sub get_userresdata {
7834: my ($uname,$udom)=@_;
7835: #most student don\'t have any data set, check if there is some data
7836: if (&EXT_cache_status($udom,$uname)) { return undef; }
7837:
7838: my $hashid="$udom:$uname";
7839: my ($result,$cached)=&is_cached_new('userres',$hashid);
7840: if (!defined($cached)) {
7841: my %resourcedata=&dump('resourcedata',$udom,$uname);
7842: $result=\%resourcedata;
7843: &do_cache_new('userres',$hashid,$result,600);
7844: }
7845: my ($tmp)=keys(%$result);
7846: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7847: return $result;
7848: }
7849: #error 2 occurs when the .db doesn't exist
7850: if ($tmp!~/error: 2 /) {
1.672 albertel 7851: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7852: " Trying to get resource data for ".
7853: $uname." at ".$udom.": ".
7854: $tmp."</font>");
7855: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7856: #&EXT_cache_set($udom,$uname);
7857: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7858: undef($tmp); # not really an error so don't send it back
1.624 albertel 7859: }
7860: return $tmp;
7861: }
1.879 foxr 7862: #----------------------------------------------- resdata - return resource data
7863: # Purpose:
7864: # Return resource data for either users or for a course.
7865: # Parameters:
7866: # $name - Course/user name.
7867: # $domain - Name of the domain the user/course is registered on.
7868: # $type - Type of thing $name is (must be 'course' or 'user'
7869: # @which - Array of names of resources desired.
7870: # Returns:
7871: # The value of the first reasource in @which that is found in the
7872: # resource hash.
7873: # Exceptional Conditions:
7874: # If the $type passed in is not valid (not the string 'course' or
7875: # 'user', an undefined reference is returned.
7876: # If none of the resources are found, an undef is returned
1.624 albertel 7877: sub resdata {
7878: my ($name,$domain,$type,@which)=@_;
7879: my $result;
7880: if ($type eq 'course') {
7881: $result=&get_courseresdata($name,$domain);
7882: } elsif ($type eq 'user') {
7883: $result=&get_userresdata($name,$domain);
7884: }
7885: if (!ref($result)) { return $result; }
1.251 albertel 7886: foreach my $item (@which) {
1.927 albertel 7887: if (defined($result->{$item->[0]})) {
7888: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7889: }
1.250 albertel 7890: }
1.291 albertel 7891: return undef;
1.200 www 7892: }
7893:
1.379 matthew 7894: #
7895: # EXT resource caching routines
7896: #
7897:
7898: sub clear_EXT_cache_status {
1.383 albertel 7899: &delenv('cache.EXT.');
1.379 matthew 7900: }
7901:
7902: sub EXT_cache_status {
7903: my ($target_domain,$target_user) = @_;
1.383 albertel 7904: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7905: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7906: # We know already the user has no data
7907: return 1;
7908: } else {
7909: return 0;
7910: }
7911: }
7912:
7913: sub EXT_cache_set {
7914: my ($target_domain,$target_user) = @_;
1.383 albertel 7915: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7916: #&appenv({$cachename => time});
1.379 matthew 7917: }
7918:
1.28 www 7919: # --------------------------------------------------------- Value of a Variable
1.58 www 7920: sub EXT {
1.715 albertel 7921:
1.395 albertel 7922: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7923: unless ($varname) { return ''; }
1.218 albertel 7924: #get real user name/domain, courseid and symb
7925: my $courseid;
1.359 albertel 7926: my $publicuser;
1.427 www 7927: if ($symbparm) {
7928: $symbparm=&get_symb_from_alias($symbparm);
7929: }
1.218 albertel 7930: if (!($uname && $udom)) {
1.790 albertel 7931: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7932: if (!$symbparm) { $symbparm=$cursymb; }
7933: } else {
1.620 albertel 7934: $courseid=$env{'request.course.id'};
1.218 albertel 7935: }
1.48 www 7936: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7937: my $rest;
1.320 albertel 7938: if (defined($therest[0])) {
1.48 www 7939: $rest=join('.',@therest);
7940: } else {
7941: $rest='';
7942: }
1.320 albertel 7943:
1.57 www 7944: my $qualifierrest=$qualifier;
7945: if ($rest) { $qualifierrest.='.'.$rest; }
7946: my $spacequalifierrest=$space;
7947: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7948: if ($realm eq 'user') {
1.48 www 7949: # --------------------------------------------------------------- user.resource
7950: if ($space eq 'resource') {
1.651 albertel 7951: if ( (defined($Apache::lonhomework::parsing_a_problem)
7952: || defined($Apache::lonhomework::parsing_a_task))
7953: &&
1.744 albertel 7954: ($symbparm eq &symbread()) ) {
7955: # if we are in the middle of processing the resource the
7956: # get the value we are planning on committing
7957: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7958: return $Apache::lonhomework::results{$qualifierrest};
7959: } else {
7960: return $Apache::lonhomework::history{$qualifierrest};
7961: }
1.335 albertel 7962: } else {
1.359 albertel 7963: my %restored;
1.620 albertel 7964: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7965: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7966: } else {
7967: %restored=&restore($symbparm,$courseid,$udom,$uname);
7968: }
1.335 albertel 7969: return $restored{$qualifierrest};
7970: }
1.48 www 7971: # ----------------------------------------------------------------- user.access
7972: } elsif ($space eq 'access') {
1.218 albertel 7973: # FIXME - not supporting calls for a specific user
1.48 www 7974: return &allowed($qualifier,$rest);
7975: # ------------------------------------------ user.preferences, user.environment
7976: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7977: if (($uname eq $env{'user.name'}) &&
7978: ($udom eq $env{'user.domain'})) {
7979: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7980: } else {
1.359 albertel 7981: my %returnhash;
7982: if (!$publicuser) {
7983: %returnhash=&userenvironment($udom,$uname,
7984: $qualifierrest);
7985: }
1.218 albertel 7986: return $returnhash{$qualifierrest};
7987: }
1.48 www 7988: # ----------------------------------------------------------------- user.course
7989: } elsif ($space eq 'course') {
1.218 albertel 7990: # FIXME - not supporting calls for a specific user
1.620 albertel 7991: return $env{join('.',('request.course',$qualifier))};
1.48 www 7992: # ------------------------------------------------------------------- user.role
7993: } elsif ($space eq 'role') {
1.218 albertel 7994: # FIXME - not supporting calls for a specific user
1.620 albertel 7995: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7996: if ($qualifier eq 'value') {
7997: return $role;
7998: } elsif ($qualifier eq 'extent') {
7999: return $where;
8000: }
8001: # ----------------------------------------------------------------- user.domain
8002: } elsif ($space eq 'domain') {
1.218 albertel 8003: return $udom;
1.48 www 8004: # ------------------------------------------------------------------- user.name
8005: } elsif ($space eq 'name') {
1.218 albertel 8006: return $uname;
1.48 www 8007: # ---------------------------------------------------- Any other user namespace
1.29 www 8008: } else {
1.359 albertel 8009: my %reply;
8010: if (!$publicuser) {
8011: %reply=&get($space,[$qualifierrest],$udom,$uname);
8012: }
8013: return $reply{$qualifierrest};
1.48 www 8014: }
1.236 www 8015: } elsif ($realm eq 'query') {
8016: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8017: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8018: [$spacequalifierrest]);
1.620 albertel 8019: return $env{'form.'.$spacequalifierrest};
1.236 www 8020: } elsif ($realm eq 'request') {
1.48 www 8021: # ------------------------------------------------------------- request.browser
8022: if ($space eq 'browser') {
1.430 www 8023: if ($qualifier eq 'textremote') {
1.676 albertel 8024: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8025: return 1;
8026: } else {
8027: return 0;
8028: }
8029: } else {
1.620 albertel 8030: return $env{'browser.'.$qualifier};
1.430 www 8031: }
1.57 www 8032: # ------------------------------------------------------------ request.filename
8033: } else {
1.620 albertel 8034: return $env{'request.'.$spacequalifierrest};
1.29 www 8035: }
1.28 www 8036: } elsif ($realm eq 'course') {
1.48 www 8037: # ---------------------------------------------------------- course.description
1.620 albertel 8038: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8039: } elsif ($realm eq 'resource') {
1.165 www 8040:
1.620 albertel 8041: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8042: if (!$symbparm) { $symbparm=&symbread(); }
8043: }
1.693 albertel 8044:
8045: if ($space eq 'title') {
8046: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8047: return &gettitle($symbparm);
8048: }
8049:
8050: if ($space eq 'map') {
8051: my ($map) = &decode_symb($symbparm);
8052: return &symbread($map);
8053: }
1.905 albertel 8054: if ($space eq 'filename') {
8055: if ($symbparm) {
8056: return &clutter((&decode_symb($symbparm))[2]);
8057: }
8058: return &hreflocation('',$env{'request.filename'});
8059: }
1.693 albertel 8060:
8061: my ($section, $group, @groups);
1.593 albertel 8062: my ($courselevelm,$courselevel);
1.539 albertel 8063: if ($symbparm && defined($courseid) &&
1.620 albertel 8064: $courseid eq $env{'request.course.id'}) {
1.165 www 8065:
1.218 albertel 8066: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8067:
1.60 www 8068: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8069: my $symbp=$symbparm;
1.735 albertel 8070: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8071:
8072: my $symbparm=$symbp.'.'.$spacequalifierrest;
8073: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8074:
1.620 albertel 8075: if (($env{'user.name'} eq $uname) &&
8076: ($env{'user.domain'} eq $udom)) {
8077: $section=$env{'request.course.sec'};
1.733 raeburn 8078: @groups = split(/:/,$env{'request.course.groups'});
8079: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8080: } else {
1.539 albertel 8081: if (! defined($usection)) {
1.551 albertel 8082: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8083: } else {
8084: $section = $usection;
8085: }
1.733 raeburn 8086: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8087: }
8088:
8089: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8090: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8091: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8092:
1.593 albertel 8093: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8094: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8095: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8096:
1.60 www 8097: # ----------------------------------------------------------- first, check user
1.624 albertel 8098:
8099: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8100: ([$courselevelr,'resource'],
8101: [$courselevelm,'map' ],
8102: [$courselevel, 'course' ]));
1.931 albertel 8103: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8104:
1.594 albertel 8105: # ------------------------------------------------ second, check some of course
1.684 raeburn 8106: my $coursereply;
1.691 raeburn 8107: if (@groups > 0) {
8108: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8109: $mapparm,$spacequalifierrest);
1.927 albertel 8110: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8111: }
1.96 www 8112:
1.684 raeburn 8113: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8114: $env{'course.'.$courseid.'.domain'},
8115: 'course',
8116: ([$seclevelr, 'resource'],
8117: [$seclevelm, 'map' ],
8118: [$seclevel, 'course' ],
8119: [$courselevelr,'resource']));
8120: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8121:
1.60 www 8122: # ------------------------------------------------------ third, check map parms
1.218 albertel 8123: my %parmhash=();
8124: my $thisparm='';
8125: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8126: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8127: &GDBM_READER(),0640)) {
1.218 albertel 8128: $thisparm=$parmhash{$symbparm};
8129: untie(%parmhash);
8130: }
1.927 albertel 8131: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8132: }
1.594 albertel 8133: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8134:
1.218 albertel 8135: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8136: my $filename;
8137: if (!$symbparm) { $symbparm=&symbread(); }
8138: if ($symbparm) {
1.409 www 8139: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8140: } else {
1.620 albertel 8141: $filename=$env{'request.filename'};
1.282 albertel 8142: }
8143: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8144: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8145: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8146: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8147:
1.927 albertel 8148: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8149: if ($symbparm && defined($courseid) &&
1.620 albertel 8150: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8151: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8152: $env{'course.'.$courseid.'.domain'},
8153: 'course',
1.927 albertel 8154: ([$courselevelm,'map' ],
8155: [$courselevel, 'course']));
8156: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8157: }
1.145 www 8158: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8159: unless ($space eq '0') {
1.336 albertel 8160: my @parts=split(/_/,$space);
8161: my $id=pop(@parts);
8162: my $part=join('_',@parts);
8163: if ($part eq '') { $part='0'; }
1.927 albertel 8164: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8165: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8166: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8167: }
1.395 albertel 8168: if ($recurse) { return undef; }
8169: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8170: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8171: # ---------------------------------------------------- Any other user namespace
8172: } elsif ($realm eq 'environment') {
8173: # ----------------------------------------------------------------- environment
1.620 albertel 8174: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8175: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8176: } else {
1.770 albertel 8177: if ($uname eq 'anonymous' && $udom eq '') {
8178: return '';
8179: }
1.219 albertel 8180: my %returnhash=&userenvironment($udom,$uname,
8181: $spacequalifierrest);
8182: return $returnhash{$spacequalifierrest};
8183: }
1.28 www 8184: } elsif ($realm eq 'system') {
1.48 www 8185: # ----------------------------------------------------------------- system.time
8186: if ($space eq 'time') {
8187: return time;
8188: }
1.696 albertel 8189: } elsif ($realm eq 'server') {
8190: # ----------------------------------------------------------------- system.time
8191: if ($space eq 'name') {
8192: return $ENV{'SERVER_NAME'};
8193: }
1.28 www 8194: }
1.48 www 8195: return '';
1.61 www 8196: }
8197:
1.927 albertel 8198: sub get_reply {
8199: my ($reply_value) = @_;
1.940 raeburn 8200: if (ref($reply_value) eq 'ARRAY') {
8201: if (wantarray) {
8202: return @$reply_value;
8203: }
8204: return $reply_value->[0];
8205: } else {
8206: return $reply_value;
1.927 albertel 8207: }
8208: }
8209:
1.691 raeburn 8210: sub check_group_parms {
8211: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8212: my @groupitems = ();
8213: my $resultitem;
1.927 albertel 8214: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8215: foreach my $group (@{$groups}) {
8216: foreach my $level (@levels) {
1.927 albertel 8217: my $item = $courseid.'.['.$group.'].'.$level->[0];
8218: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8219: }
8220: }
8221: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8222: $env{'course.'.$courseid.'.domain'},
8223: 'course',@groupitems);
8224: return $coursereply;
8225: }
8226:
8227: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8228: my ($courseid,@groups) = @_;
8229: @groups = sort(@groups);
1.691 raeburn 8230: return @groups;
8231: }
8232:
1.395 albertel 8233: sub packages_tab_default {
8234: my ($uri,$varname)=@_;
8235: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8236:
8237: my (@extension,@specifics,$do_default);
8238: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8239: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8240: if ($pack_type eq 'default') {
8241: $do_default=1;
8242: } elsif ($pack_type eq 'extension') {
8243: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8244: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8245: # only look at packages defaults for packages that this id is
1.738 albertel 8246: push(@specifics,[$package,$pack_type,$pack_part]);
8247: }
8248: }
8249: # first look for a package that matches the requested part id
8250: foreach my $package (@specifics) {
8251: my (undef,$pack_type,$pack_part)=@{$package};
8252: next if ($pack_part ne $part);
8253: if (defined($packagetab{"$pack_type&$name&default"})) {
8254: return $packagetab{"$pack_type&$name&default"};
8255: }
8256: }
8257: # look for any possible matching non extension_ package
8258: foreach my $package (@specifics) {
8259: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8260: if (defined($packagetab{"$pack_type&$name&default"})) {
8261: return $packagetab{"$pack_type&$name&default"};
8262: }
1.585 albertel 8263: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8264: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8265: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8266: }
8267: }
1.738 albertel 8268: # look for any posible extension_ match
8269: foreach my $package (@extension) {
8270: my ($package,$pack_type)=@{$package};
8271: if (defined($packagetab{"$pack_type&$name&default"})) {
8272: return $packagetab{"$pack_type&$name&default"};
8273: }
8274: if (defined($packagetab{$package."&$name&default"})) {
8275: return $packagetab{$package."&$name&default"};
8276: }
8277: }
8278: # look for a global default setting
8279: if ($do_default && defined($packagetab{"default&$name&default"})) {
8280: return $packagetab{"default&$name&default"};
8281: }
1.395 albertel 8282: return undef;
8283: }
8284:
1.334 albertel 8285: sub add_prefix_and_part {
8286: my ($prefix,$part)=@_;
8287: my $keyroot;
8288: if (defined($prefix) && $prefix !~ /^__/) {
8289: # prefix that has a part already
8290: $keyroot=$prefix;
8291: } elsif (defined($prefix)) {
8292: # prefix that is missing a part
8293: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8294: } else {
8295: # no prefix at all
8296: if (defined($part)) { $keyroot='_'.$part; }
8297: }
8298: return $keyroot;
8299: }
8300:
1.71 www 8301: # ---------------------------------------------------------------- Get metadata
8302:
1.599 albertel 8303: my %metaentry;
1.1070 www 8304: my %importedpartids;
1.71 www 8305: sub metadata {
1.176 www 8306: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8307: $uri=&declutter($uri);
1.288 albertel 8308: # if it is a non metadata possible uri return quickly
1.529 albertel 8309: if (($uri eq '') ||
8310: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8311: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8312: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8313: return undef;
8314: }
8315: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8316: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8317: return undef;
1.288 albertel 8318: }
1.73 www 8319: my $filename=$uri;
8320: $uri=~s/\.meta$//;
1.172 www 8321: #
8322: # Is the metadata already cached?
1.177 www 8323: # Look at timestamp of caching
1.172 www 8324: # Everything is cached by the main uri, libraries are never directly cached
8325: #
1.428 albertel 8326: if (!defined($liburi)) {
1.599 albertel 8327: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8328: if (defined($cached)) { return $result->{':'.$what}; }
8329: }
8330: {
1.1069 www 8331: # Imported parts would go here
1.1070 www 8332: my %importedids=();
8333: my @origfileimportpartids=();
1.1069 www 8334: my $importedparts=0;
1.172 www 8335: #
8336: # Is this a recursive call for a library?
8337: #
1.599 albertel 8338: # if (! exists($metacache{$uri})) {
8339: # $metacache{$uri}={};
8340: # }
1.924 albertel 8341: my $cachetime = 60*60;
1.171 www 8342: if ($liburi) {
8343: $liburi=&declutter($liburi);
8344: $filename=$liburi;
1.401 bowersj2 8345: } else {
1.599 albertel 8346: &devalidate_cache_new('meta',$uri);
8347: undef(%metaentry);
1.401 bowersj2 8348: }
1.140 www 8349: my %metathesekeys=();
1.73 www 8350: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8351: my $metastring;
1.924 albertel 8352: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8353: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8354: $metastring =
1.929 albertel 8355: &Apache::lonnet::ssi_body($which,
1.924 albertel 8356: ('grade_target' => 'meta'));
8357: $cachetime = 1; # only want this cached in the child not long term
8358: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8359: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8360: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8361: $metastring=&getfile($file);
1.489 albertel 8362: }
1.208 albertel 8363: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8364: my $token;
1.140 www 8365: undef %metathesekeys;
1.71 www 8366: while ($token=$parser->get_token) {
1.339 albertel 8367: if ($token->[0] eq 'S') {
8368: if (defined($token->[2]->{'package'})) {
1.172 www 8369: #
8370: # This is a package - get package info
8371: #
1.339 albertel 8372: my $package=$token->[2]->{'package'};
8373: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8374: if (defined($token->[2]->{'id'})) {
8375: $keyroot.='_'.$token->[2]->{'id'};
8376: }
1.599 albertel 8377: if ($metaentry{':packages'}) {
8378: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8379: } else {
1.599 albertel 8380: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8381: }
1.736 albertel 8382: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8383: my $part=$keyroot;
8384: $part=~s/^\_//;
1.736 albertel 8385: if ($pack_entry=~/^\Q$package\E\&/ ||
8386: $pack_entry=~/^\Q$package\E_0\&/) {
8387: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8388: # ignore package.tab specified default values
8389: # here &package_tab_default() will fetch those
8390: if ($subp eq 'default') { next; }
1.736 albertel 8391: my $value=$packagetab{$pack_entry};
1.432 albertel 8392: my $unikey;
8393: if ($pack =~ /_0$/) {
8394: $unikey='parameter_0_'.$name;
8395: $part=0;
8396: } else {
8397: $unikey='parameter'.$keyroot.'_'.$name;
8398: }
1.339 albertel 8399: if ($subp eq 'display') {
8400: $value.=' [Part: '.$part.']';
8401: }
1.599 albertel 8402: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8403: $metathesekeys{$unikey}=1;
1.599 albertel 8404: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8405: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8406: }
1.599 albertel 8407: if (defined($metaentry{':'.$unikey.'.default'})) {
8408: $metaentry{':'.$unikey}=
8409: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8410: }
1.339 albertel 8411: }
8412: }
8413: } else {
1.172 www 8414: #
8415: # This is not a package - some other kind of start tag
1.339 albertel 8416: #
8417: my $entry=$token->[1];
1.1068 www 8418: my $unikey='';
1.175 www 8419:
1.339 albertel 8420: if ($entry eq 'import') {
1.175 www 8421: #
8422: # Importing a library here
1.339 albertel 8423: #
1.1067 www 8424: my $location=$parser->get_text('/import');
8425: my $dir=$filename;
8426: $dir=~s|[^/]*$||;
8427: $location=&filelocation($dir,$location);
1.1069 www 8428:
1.1068 www 8429: my $importmode=$token->[2]->{'importmode'};
8430: if ($importmode eq 'problem') {
1.1069 www 8431: # Import as problem/response
1.1068 www 8432: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8433: } elsif ($importmode eq 'part') {
8434: # Import as part(s)
1.1069 www 8435: $importedparts=1;
8436: # We need to get the original file and the imported file to get the part order correct
8437: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8438: # Load and inspect original file
1.1070 www 8439: if ($#origfileimportpartids<0) {
8440: undef(%importedpartids);
8441: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8442: my $origfile=&getfile($origfilelocation);
8443: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8444: }
8445:
1.1069 www 8446: # Load and inspect imported file
8447: my $impfile=&getfile($location);
8448: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8449: if ($#impfilepartids>=0) {
8450: # This problem had parts
1.1070 www 8451: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8452: } else {
8453: # Importing by turning a single problem into a problem part
8454: # It gets the import-tags ID as part-ID
8455: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8456: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8457: }
1.1068 www 8458: } else {
8459: # Normal import
8460: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8461: if (defined($token->[2]->{'id'})) {
8462: $unikey.='_'.$token->[2]->{'id'};
8463: }
1.1067 www 8464: }
8465:
1.339 albertel 8466: if ($depthcount<20) {
1.736 albertel 8467: my $metadata =
8468: &metadata($uri,'keys', $location,$unikey,
8469: $depthcount+1);
8470: foreach my $meta (split(',',$metadata)) {
8471: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8472: $metathesekeys{$meta}=1;
1.339 albertel 8473: }
1.1068 www 8474:
8475: }
1.1067 www 8476: } else {
8477: #
8478: # Not importing, some other kind of non-package, non-library start tag
8479: #
8480: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8481: if (defined($token->[2]->{'id'})) {
8482: $unikey.='_'.$token->[2]->{'id'};
8483: }
1.339 albertel 8484: if (defined($token->[2]->{'name'})) {
8485: $unikey.='_'.$token->[2]->{'name'};
8486: }
8487: $metathesekeys{$unikey}=1;
1.736 albertel 8488: foreach my $param (@{$token->[3]}) {
8489: $metaentry{':'.$unikey.'.'.$param} =
8490: $token->[2]->{$param};
1.339 albertel 8491: }
8492: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8493: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8494: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8495: # only ws inside the tag, and not in default, so use default
8496: # as value
1.599 albertel 8497: $metaentry{':'.$unikey}=$default;
1.908 albertel 8498: } elsif ( $internaltext =~ /\S/ ) {
8499: # something interesting inside the tag
8500: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8501: } else {
1.908 albertel 8502: # no interesting values, don't set a default
1.339 albertel 8503: }
1.172 www 8504: # end of not-a-package not-a-library import
1.339 albertel 8505: }
1.172 www 8506: # end of not-a-package start tag
1.339 albertel 8507: }
1.172 www 8508: # the next is the end of "start tag"
1.339 albertel 8509: }
8510: }
1.483 albertel 8511: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8512: $extension = lc($extension);
8513: if ($extension eq 'htm') { $extension='html'; }
8514:
1.737 albertel 8515: foreach my $key (keys(%packagetab)) {
1.483 albertel 8516: #no specific packages #how's our extension
8517: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8518: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8519: \%metathesekeys);
8520: }
1.883 albertel 8521:
8522: if (!exists($metaentry{':packages'})
8523: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8524: foreach my $key (keys(%packagetab)) {
1.483 albertel 8525: #no specific packages well let's get default then
8526: if ($key!~/^default&/) { next; }
1.488 albertel 8527: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8528: \%metathesekeys);
8529: }
8530: }
1.338 www 8531: # are there custom rights to evaluate
1.599 albertel 8532: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8533:
1.338 www 8534: #
8535: # Importing a rights file here
1.339 albertel 8536: #
8537: unless ($depthcount) {
1.599 albertel 8538: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8539: my $dir=$filename;
8540: $dir=~s|[^/]*$||;
8541: $location=&filelocation($dir,$location);
1.736 albertel 8542: my $rights_metadata =
8543: &metadata($uri,'keys',$location,'_rights',
8544: $depthcount+1);
8545: foreach my $rights (split(',',$rights_metadata)) {
8546: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8547: $metathesekeys{$rights}=1;
1.339 albertel 8548: }
8549: }
8550: }
1.737 albertel 8551: # uniqifiy package listing
8552: my %seen;
8553: my @uniq_packages =
8554: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8555: $metaentry{':packages'} = join(',',@uniq_packages);
8556:
1.1070 www 8557: if ($importedparts) {
8558: # We had imported parts and need to rebuild partorder
8559: $metaentry{':partorder'}='';
8560: $metathesekeys{'partorder'}=1;
8561: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8562: if ($origfileimportpartids[$index] eq 'part') {
8563: # original part, part of the problem
8564: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8565: } else {
8566: # we have imported parts at this position
8567: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8568: }
8569: }
8570: $metaentry{':partorder'}=~s/^\,//;
8571: }
8572:
1.737 albertel 8573: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8574: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8575: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8576: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8577: # this is the end of "was not already recently cached
1.71 www 8578: }
1.599 albertel 8579: return $metaentry{':'.$what};
1.261 albertel 8580: }
8581:
1.488 albertel 8582: sub metadata_create_package_def {
1.483 albertel 8583: my ($uri,$key,$package,$metathesekeys)=@_;
8584: my ($pack,$name,$subp)=split(/\&/,$key);
8585: if ($subp eq 'default') { next; }
8586:
1.599 albertel 8587: if (defined($metaentry{':packages'})) {
8588: $metaentry{':packages'}.=','.$package;
1.483 albertel 8589: } else {
1.599 albertel 8590: $metaentry{':packages'}=$package;
1.483 albertel 8591: }
8592: my $value=$packagetab{$key};
8593: my $unikey;
8594: $unikey='parameter_0_'.$name;
1.599 albertel 8595: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8596: $$metathesekeys{$unikey}=1;
1.599 albertel 8597: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8598: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8599: }
1.599 albertel 8600: if (defined($metaentry{':'.$unikey.'.default'})) {
8601: $metaentry{':'.$unikey}=
8602: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8603: }
8604: }
8605:
1.261 albertel 8606: sub metadata_generate_part0 {
8607: my ($metadata,$metacache,$uri) = @_;
8608: my %allnames;
1.737 albertel 8609: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8610: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8611: my $part=$$metacache{':'.$metakey.'.part'};
8612: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8613: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8614: $allnames{$name}=$part;
8615: }
8616: }
8617: }
8618: foreach my $name (keys(%allnames)) {
8619: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8620: my $key=":parameter_0_$name";
1.261 albertel 8621: $$metacache{"$key.part"}='0';
8622: $$metacache{"$key.name"}=$name;
1.428 albertel 8623: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8624: $allnames{$name}.'_'.$name.
8625: '.type'};
1.428 albertel 8626: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8627: '.display'};
1.644 www 8628: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8629: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8630: $$metacache{"$key.display"}=$olddis;
8631: }
1.71 www 8632: }
8633:
1.764 albertel 8634: # ------------------------------------------------------ Devalidate title cache
8635:
8636: sub devalidate_title_cache {
8637: my ($url)=@_;
8638: if (!$env{'request.course.id'}) { return; }
8639: my $symb=&symbread($url);
8640: if (!$symb) { return; }
8641: my $key=$env{'request.course.id'}."\0".$symb;
8642: &devalidate_cache_new('title',$key);
8643: }
8644:
1.1014 droeschl 8645: # ------------------------------------------------- Get the title of a course
8646:
8647: sub current_course_title {
8648: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8649: }
1.301 www 8650: # ------------------------------------------------- Get the title of a resource
8651:
8652: sub gettitle {
8653: my $urlsymb=shift;
8654: my $symb=&symbread($urlsymb);
1.534 albertel 8655: if ($symb) {
1.620 albertel 8656: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8657: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8658: if (defined($cached)) {
8659: return $result;
8660: }
1.534 albertel 8661: my ($map,$resid,$url)=&decode_symb($symb);
8662: my $title='';
1.907 albertel 8663: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8664: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8665: } else {
8666: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8667: &GDBM_READER(),0640)) {
8668: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8669: $title=$bighash{'title_'.$mapid.'.'.$resid};
8670: untie(%bighash);
8671: }
1.534 albertel 8672: }
8673: $title=~s/\&colon\;/\:/gs;
8674: if ($title) {
1.599 albertel 8675: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8676: }
8677: $urlsymb=$url;
8678: }
8679: my $title=&metadata($urlsymb,'title');
8680: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8681: return $title;
1.301 www 8682: }
1.613 albertel 8683:
1.614 albertel 8684: sub get_slot {
8685: my ($which,$cnum,$cdom)=@_;
8686: if (!$cnum || !$cdom) {
1.790 albertel 8687: (undef,my $courseid)=&whichuser();
1.620 albertel 8688: $cdom=$env{'course.'.$courseid.'.domain'};
8689: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8690: }
1.703 albertel 8691: my $key=join("\0",'slots',$cdom,$cnum,$which);
8692: my %slotinfo;
8693: if (exists($remembered{$key})) {
8694: $slotinfo{$which} = $remembered{$key};
8695: } else {
8696: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8697: &Apache::lonhomework::showhash(%slotinfo);
8698: my ($tmp)=keys(%slotinfo);
8699: if ($tmp=~/^error:/) { return (); }
8700: $remembered{$key} = $slotinfo{$which};
8701: }
1.616 albertel 8702: if (ref($slotinfo{$which}) eq 'HASH') {
8703: return %{$slotinfo{$which}};
8704: }
8705: return $slotinfo{$which};
1.614 albertel 8706: }
1.31 www 8707: # ------------------------------------------------- Update symbolic store links
8708:
8709: sub symblist {
8710: my ($mapname,%newhash)=@_;
1.438 www 8711: $mapname=&deversion(&declutter($mapname));
1.31 www 8712: my %hash;
1.620 albertel 8713: if (($env{'request.course.fn'}) && (%newhash)) {
8714: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8715: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8716: foreach my $url (keys(%newhash)) {
1.711 albertel 8717: next if ($url eq 'last_known'
8718: && $env{'form.no_update_last_known'});
8719: $hash{declutter($url)}=&encode_symb($mapname,
8720: $newhash{$url}->[1],
8721: $newhash{$url}->[0]);
1.191 harris41 8722: }
1.31 www 8723: if (untie(%hash)) {
8724: return 'ok';
8725: }
8726: }
8727: }
8728: return 'error';
1.212 www 8729: }
8730:
8731: # --------------------------------------------------------------- Verify a symb
8732:
8733: sub symbverify {
1.510 www 8734: my ($symb,$thisurl)=@_;
8735: my $thisfn=$thisurl;
1.439 www 8736: $thisfn=&declutter($thisfn);
1.215 www 8737: # direct jump to resource in page or to a sequence - will construct own symbs
8738: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8739: # check URL part
1.409 www 8740: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8741:
1.431 www 8742: unless ($url eq $thisfn) { return 0; }
1.213 www 8743:
1.216 www 8744: $symb=&symbclean($symb);
1.510 www 8745: $thisurl=&deversion($thisurl);
1.439 www 8746: $thisfn=&deversion($thisfn);
1.213 www 8747:
8748: my %bighash;
8749: my $okay=0;
1.431 www 8750:
1.620 albertel 8751: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8752: &GDBM_READER(),0640)) {
1.1032 raeburn 8753: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8754: $thisurl =~ s/\?.+$//;
8755: }
1.510 www 8756: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8757: unless ($ids) {
1.510 www 8758: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8759: }
8760: if ($ids) {
8761: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8762: foreach my $id (split(/\,/,$ids)) {
8763: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8764: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8765: $symb =~ s/\?.+$//;
8766: }
1.216 www 8767: if (
8768: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8769: eq $symb) {
1.620 albertel 8770: if (($env{'request.role.adv'}) ||
1.800 albertel 8771: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8772: $okay=1;
8773: }
8774: }
1.216 www 8775: }
8776: }
1.213 www 8777: untie(%bighash);
8778: }
8779: return $okay;
1.31 www 8780: }
8781:
1.210 www 8782: # --------------------------------------------------------------- Clean-up symb
8783:
8784: sub symbclean {
8785: my $symb=shift;
1.568 albertel 8786: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8787: # remove version from map
8788: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8789:
1.210 www 8790: # remove version from URL
8791: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8792:
1.507 www 8793: # remove wrapper
8794:
1.510 www 8795: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8796: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8797: return $symb;
1.409 www 8798: }
8799:
8800: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8801:
8802: sub encode_symb {
8803: my ($map,$resid,$url)=@_;
8804: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8805: }
1.409 www 8806:
8807: sub decode_symb {
1.568 albertel 8808: my $symb=shift;
8809: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8810: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8811: return (&fixversion($map),$resid,&fixversion($url));
8812: }
8813:
8814: sub fixversion {
8815: my $fn=shift;
1.609 banghart 8816: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8817: my %bighash;
8818: my $uri=&clutter($fn);
1.620 albertel 8819: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8820: # is this cached?
1.599 albertel 8821: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8822: if (defined($cached)) { return $result; }
8823: # unfortunately not cached, or expired
1.620 albertel 8824: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8825: &GDBM_READER(),0640)) {
8826: if ($bighash{'version_'.$uri}) {
8827: my $version=$bighash{'version_'.$uri};
1.444 www 8828: unless (($version eq 'mostrecent') ||
8829: ($version==&getversion($uri))) {
1.440 www 8830: $uri=~s/\.(\w+)$/\.$version\.$1/;
8831: }
8832: }
8833: untie %bighash;
1.413 www 8834: }
1.599 albertel 8835: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8836: }
8837:
8838: sub deversion {
8839: my $url=shift;
8840: $url=~s/\.\d+\.(\w+)$/\.$1/;
8841: return $url;
1.210 www 8842: }
8843:
1.31 www 8844: # ------------------------------------------------------ Return symb list entry
8845:
8846: sub symbread {
1.249 www 8847: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8848: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8849: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8850: # no filename provided? try from environment
1.44 www 8851: unless ($thisfn) {
1.620 albertel 8852: if ($env{'request.symb'}) {
8853: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8854: }
1.620 albertel 8855: $thisfn=$env{'request.filename'};
1.44 www 8856: }
1.569 albertel 8857: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8858: # is that filename actually a symb? Verify, clean, and return
8859: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8860: if (&symbverify($thisfn,$1)) {
1.620 albertel 8861: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8862: }
1.242 www 8863: }
1.44 www 8864: $thisfn=declutter($thisfn);
1.31 www 8865: my %hash;
1.37 www 8866: my %bighash;
8867: my $syval='';
1.620 albertel 8868: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8869: my $targetfn = $thisfn;
1.609 banghart 8870: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8871: $targetfn = 'adm/wrapper/'.$thisfn;
8872: }
1.687 albertel 8873: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8874: $targetfn=$1;
8875: }
1.620 albertel 8876: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8877: &GDBM_READER(),0640)) {
1.481 raeburn 8878: $syval=$hash{$targetfn};
1.37 www 8879: untie(%hash);
8880: }
8881: # ---------------------------------------------------------- There was an entry
8882: if ($syval) {
1.601 albertel 8883: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8884: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8885: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8886: #return $env{$cache_str}='';
1.601 albertel 8887: #}
8888: #$syval.=$1;
8889: #}
1.37 www 8890: } else {
8891: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8892: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8893: &GDBM_READER(),0640)) {
1.37 www 8894: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8895: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8896: unless ($ids) {
8897: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8898: }
8899: unless ($ids) {
8900: # alias?
8901: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8902: }
1.37 www 8903: if ($ids) {
8904: # ------------------------------------------------------------------- Has ID(s)
8905: my @possibilities=split(/\,/,$ids);
1.39 www 8906: if ($#possibilities==0) {
8907: # ----------------------------------------------- There is only one possibility
1.37 www 8908: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8909: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8910: $resid,$thisfn);
1.249 www 8911: } elsif (!$donotrecurse) {
1.39 www 8912: # ------------------------------------------ There is more than one possibility
8913: my $realpossible=0;
1.800 albertel 8914: foreach my $id (@possibilities) {
8915: my $file=$bighash{'src_'.$id};
1.39 www 8916: if (&allowed('bre',$file)) {
1.800 albertel 8917: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8918: if ($bighash{'map_type_'.$mapid} ne 'page') {
8919: $realpossible++;
1.626 albertel 8920: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8921: $resid,$thisfn);
1.39 www 8922: }
8923: }
1.191 harris41 8924: }
1.39 www 8925: if ($realpossible!=1) { $syval=''; }
1.249 www 8926: } else {
8927: $syval='';
1.37 www 8928: }
8929: }
8930: untie(%bighash)
1.481 raeburn 8931: }
1.31 www 8932: }
1.62 www 8933: if ($syval) {
1.620 albertel 8934: return $env{$cache_str}=$syval;
1.62 www 8935: }
1.31 www 8936: }
1.949 raeburn 8937: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8938: return $env{$cache_str}='';
1.31 www 8939: }
8940:
8941: # ---------------------------------------------------------- Return random seed
8942:
1.32 www 8943: sub numval {
8944: my $txt=shift;
8945: $txt=~tr/A-J/0-9/;
8946: $txt=~tr/a-j/0-9/;
8947: $txt=~tr/K-T/0-9/;
8948: $txt=~tr/k-t/0-9/;
8949: $txt=~tr/U-Z/0-5/;
8950: $txt=~tr/u-z/0-5/;
8951: $txt=~s/\D//g;
1.564 albertel 8952: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8953: return int($txt);
1.368 albertel 8954: }
8955:
1.484 albertel 8956: sub numval2 {
8957: my $txt=shift;
8958: $txt=~tr/A-J/0-9/;
8959: $txt=~tr/a-j/0-9/;
8960: $txt=~tr/K-T/0-9/;
8961: $txt=~tr/k-t/0-9/;
8962: $txt=~tr/U-Z/0-5/;
8963: $txt=~tr/u-z/0-5/;
8964: $txt=~s/\D//g;
8965: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8966: my $total;
8967: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8968: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8969: return int($total);
8970: }
8971:
1.575 albertel 8972: sub numval3 {
8973: use integer;
8974: my $txt=shift;
8975: $txt=~tr/A-J/0-9/;
8976: $txt=~tr/a-j/0-9/;
8977: $txt=~tr/K-T/0-9/;
8978: $txt=~tr/k-t/0-9/;
8979: $txt=~tr/U-Z/0-5/;
8980: $txt=~tr/u-z/0-5/;
8981: $txt=~s/\D//g;
8982: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8983: my $total;
8984: foreach my $val (@txts) { $total+=$val; }
8985: if ($_64bit) { $total=(($total<<32)>>32); }
8986: return $total;
8987: }
8988:
1.675 albertel 8989: sub digest {
8990: my ($data)=@_;
8991: my $digest=&Digest::MD5::md5($data);
8992: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8993: my ($e,$f);
8994: {
8995: use integer;
8996: $e=($a+$b);
8997: $f=($c+$d);
8998: if ($_64bit) {
8999: $e=(($e<<32)>>32);
9000: $f=(($f<<32)>>32);
9001: }
9002: }
9003: if (wantarray) {
9004: return ($e,$f);
9005: } else {
9006: my $g;
9007: {
9008: use integer;
9009: $g=($e+$f);
9010: if ($_64bit) {
9011: $g=(($g<<32)>>32);
9012: }
9013: }
9014: return $g;
9015: }
9016: }
9017:
1.368 albertel 9018: sub latest_rnd_algorithm_id {
1.675 albertel 9019: return '64bit5';
1.366 albertel 9020: }
1.32 www 9021:
1.503 albertel 9022: sub get_rand_alg {
9023: my ($courseid)=@_;
1.790 albertel 9024: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9025: if ($courseid) {
1.620 albertel 9026: return $env{"course.$courseid.rndseed"};
1.503 albertel 9027: }
9028: return &latest_rnd_algorithm_id();
9029: }
9030:
1.562 albertel 9031: sub validCODE {
9032: my ($CODE)=@_;
9033: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9034: return 0;
9035: }
9036:
1.491 albertel 9037: sub getCODE {
1.620 albertel 9038: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9039: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9040: defined($Apache::lonhomework::parsing_a_task) ) &&
9041: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9042: return $Apache::lonhomework::history{'resource.CODE'};
9043: }
9044: return undef;
9045: }
9046:
1.31 www 9047: sub rndseed {
1.155 albertel 9048: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9049: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9050: if (!defined($symb)) {
1.366 albertel 9051: unless ($symb=$wsymb) { return time; }
9052: }
9053: if (!$courseid) { $courseid=$wcourseid; }
9054: if (!$domain) { $domain=$wdomain; }
9055: if (!$username) { $username=$wusername }
1.503 albertel 9056: my $which=&get_rand_alg();
1.803 albertel 9057:
1.491 albertel 9058: if (defined(&getCODE())) {
1.675 albertel 9059: if ($which eq '64bit5') {
9060: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9061: } elsif ($which eq '64bit4') {
1.575 albertel 9062: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9063: } else {
9064: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9065: }
1.675 albertel 9066: } elsif ($which eq '64bit5') {
9067: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9068: } elsif ($which eq '64bit4') {
9069: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9070: } elsif ($which eq '64bit3') {
9071: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9072: } elsif ($which eq '64bit2') {
9073: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9074: } elsif ($which eq '64bit') {
9075: return &rndseed_64bit($symb,$courseid,$domain,$username);
9076: }
9077: return &rndseed_32bit($symb,$courseid,$domain,$username);
9078: }
9079:
9080: sub rndseed_32bit {
9081: my ($symb,$courseid,$domain,$username)=@_;
9082: {
9083: use integer;
9084: my $symbchck=unpack("%32C*",$symb) << 27;
9085: my $symbseed=numval($symb) << 22;
9086: my $namechck=unpack("%32C*",$username) << 17;
9087: my $nameseed=numval($username) << 12;
9088: my $domainseed=unpack("%32C*",$domain) << 7;
9089: my $courseseed=unpack("%32C*",$courseid);
9090: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9091: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9092: #&logthis("rndseed :$num:$symb");
1.564 albertel 9093: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9094: return $num;
9095: }
9096: }
9097:
9098: sub rndseed_64bit {
9099: my ($symb,$courseid,$domain,$username)=@_;
9100: {
9101: use integer;
9102: my $symbchck=unpack("%32S*",$symb) << 21;
9103: my $symbseed=numval($symb) << 10;
9104: my $namechck=unpack("%32S*",$username);
9105:
9106: my $nameseed=numval($username) << 21;
9107: my $domainseed=unpack("%32S*",$domain) << 10;
9108: my $courseseed=unpack("%32S*",$courseid);
9109:
9110: my $num1=$symbchck+$symbseed+$namechck;
9111: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9112: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9113: #&logthis("rndseed :$num:$symb");
1.564 albertel 9114: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9115: return "$num1,$num2";
1.155 albertel 9116: }
1.366 albertel 9117: }
9118:
1.443 albertel 9119: sub rndseed_64bit2 {
9120: my ($symb,$courseid,$domain,$username)=@_;
9121: {
9122: use integer;
9123: # strings need to be an even # of cahracters long, it it is odd the
9124: # last characters gets thrown away
9125: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9126: my $symbseed=numval($symb) << 10;
9127: my $namechck=unpack("%32S*",$username.' ');
9128:
9129: my $nameseed=numval($username) << 21;
1.501 albertel 9130: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9131: my $courseseed=unpack("%32S*",$courseid.' ');
9132:
9133: my $num1=$symbchck+$symbseed+$namechck;
9134: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9135: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9136: #&logthis("rndseed :$num:$symb");
1.803 albertel 9137: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9138: return "$num1,$num2";
9139: }
9140: }
9141:
9142: sub rndseed_64bit3 {
9143: my ($symb,$courseid,$domain,$username)=@_;
9144: {
9145: use integer;
9146: # strings need to be an even # of cahracters long, it it is odd the
9147: # last characters gets thrown away
9148: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9149: my $symbseed=numval2($symb) << 10;
9150: my $namechck=unpack("%32S*",$username.' ');
9151:
9152: my $nameseed=numval2($username) << 21;
1.443 albertel 9153: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9154: my $courseseed=unpack("%32S*",$courseid.' ');
9155:
9156: my $num1=$symbchck+$symbseed+$namechck;
9157: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9158: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9159: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9160: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9161:
1.503 albertel 9162: return "$num1:$num2";
1.443 albertel 9163: }
9164: }
9165:
1.575 albertel 9166: sub rndseed_64bit4 {
9167: my ($symb,$courseid,$domain,$username)=@_;
9168: {
9169: use integer;
9170: # strings need to be an even # of cahracters long, it it is odd the
9171: # last characters gets thrown away
9172: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9173: my $symbseed=numval3($symb) << 10;
9174: my $namechck=unpack("%32S*",$username.' ');
9175:
9176: my $nameseed=numval3($username) << 21;
9177: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9178: my $courseseed=unpack("%32S*",$courseid.' ');
9179:
9180: my $num1=$symbchck+$symbseed+$namechck;
9181: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9182: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9183: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9184: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9185:
9186: return "$num1:$num2";
9187: }
9188: }
9189:
1.675 albertel 9190: sub rndseed_64bit5 {
9191: my ($symb,$courseid,$domain,$username)=@_;
9192: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9193: return "$num1:$num2";
9194: }
9195:
1.366 albertel 9196: sub rndseed_CODE_64bit {
9197: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9198: {
1.366 albertel 9199: use integer;
1.443 albertel 9200: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9201: my $symbseed=numval2($symb);
1.491 albertel 9202: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9203: my $CODEseed=numval(&getCODE());
1.443 albertel 9204: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9205: my $num1=$symbseed+$CODEchck;
9206: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9207: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9208: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9209: if ($_64bit) { $num1=(($num1<<32)>>32); }
9210: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9211: return "$num1:$num2";
1.366 albertel 9212: }
9213: }
9214:
1.575 albertel 9215: sub rndseed_CODE_64bit4 {
9216: my ($symb,$courseid,$domain,$username)=@_;
9217: {
9218: use integer;
9219: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9220: my $symbseed=numval3($symb);
9221: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9222: my $CODEseed=numval3(&getCODE());
9223: my $courseseed=unpack("%32S*",$courseid.' ');
9224: my $num1=$symbseed+$CODEchck;
9225: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9226: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9227: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9228: if ($_64bit) { $num1=(($num1<<32)>>32); }
9229: if ($_64bit) { $num2=(($num2<<32)>>32); }
9230: return "$num1:$num2";
9231: }
9232: }
9233:
1.675 albertel 9234: sub rndseed_CODE_64bit5 {
9235: my ($symb,$courseid,$domain,$username)=@_;
9236: my $code = &getCODE();
9237: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9238: return "$num1:$num2";
9239: }
9240:
1.366 albertel 9241: sub setup_random_from_rndseed {
9242: my ($rndseed)=@_;
1.503 albertel 9243: if ($rndseed =~/([,:])/) {
9244: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9245: &Math::Random::random_set_seed(abs($num1),abs($num2));
9246: } else {
9247: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9248: }
1.36 albertel 9249: }
9250:
1.474 albertel 9251: sub latest_receipt_algorithm_id {
1.835 albertel 9252: return 'receipt3';
1.474 albertel 9253: }
9254:
1.480 www 9255: sub recunique {
9256: my $fucourseid=shift;
9257: my $unique;
1.835 albertel 9258: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9259: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9260: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9261: } else {
9262: $unique=$perlvar{'lonReceipt'};
9263: }
9264: return unpack("%32C*",$unique);
9265: }
9266:
9267: sub recprefix {
9268: my $fucourseid=shift;
9269: my $prefix;
1.835 albertel 9270: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9271: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9272: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9273: } else {
9274: $prefix=$perlvar{'lonHostID'};
9275: }
9276: return unpack("%32C*",$prefix);
9277: }
9278:
1.76 www 9279: sub ireceipt {
1.474 albertel 9280: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9281:
9282: my $return =&recprefix($fucourseid).'-';
9283:
9284: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9285: $env{'request.state'} eq 'construct') {
9286: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9287: return $return;
9288: }
9289:
1.76 www 9290: my $cuname=unpack("%32C*",$funame);
9291: my $cudom=unpack("%32C*",$fudom);
9292: my $cucourseid=unpack("%32C*",$fucourseid);
9293: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9294: my $cunique=&recunique($fucourseid);
1.474 albertel 9295: my $cpart=unpack("%32S*",$part);
1.835 albertel 9296: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9297:
1.790 albertel 9298: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9299:
9300: $return.= ($cunique%$cuname+
9301: $cunique%$cudom+
9302: $cusymb%$cuname+
9303: $cusymb%$cudom+
9304: $cucourseid%$cuname+
9305: $cucourseid%$cudom+
9306: $cpart%$cuname+
9307: $cpart%$cudom);
9308: } else {
9309: $return.= ($cunique%$cuname+
9310: $cunique%$cudom+
9311: $cusymb%$cuname+
9312: $cusymb%$cudom+
9313: $cucourseid%$cuname+
9314: $cucourseid%$cudom);
9315: }
9316: return $return;
1.76 www 9317: }
9318:
9319: sub receipt {
1.474 albertel 9320: my ($part)=@_;
1.790 albertel 9321: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9322: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9323: }
1.260 ng 9324:
1.790 albertel 9325: sub whichuser {
9326: my ($passedsymb)=@_;
9327: my ($symb,$courseid,$domain,$name,$publicuser);
9328: if (defined($env{'form.grade_symb'})) {
9329: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9330: my $allowed=&allowed('vgr',$tmp_courseid);
9331: if (!$allowed &&
9332: exists($env{'request.course.sec'}) &&
9333: $env{'request.course.sec'} !~ /^\s*$/) {
9334: $allowed=&allowed('vgr',$tmp_courseid.
9335: '/'.$env{'request.course.sec'});
9336: }
9337: if ($allowed) {
9338: ($symb)=&get_env_multiple('form.grade_symb');
9339: $courseid=$tmp_courseid;
9340: ($domain)=&get_env_multiple('form.grade_domain');
9341: ($name)=&get_env_multiple('form.grade_username');
9342: return ($symb,$courseid,$domain,$name,$publicuser);
9343: }
9344: }
9345: if (!$passedsymb) {
9346: $symb=&symbread();
9347: } else {
9348: $symb=$passedsymb;
9349: }
9350: $courseid=$env{'request.course.id'};
9351: $domain=$env{'user.domain'};
9352: $name=$env{'user.name'};
9353: if ($name eq 'public' && $domain eq 'public') {
9354: if (!defined($env{'form.username'})) {
9355: $env{'form.username'}.=time.rand(10000000);
9356: }
9357: $name.=$env{'form.username'};
9358: }
9359: return ($symb,$courseid,$domain,$name,$publicuser);
9360:
9361: }
9362:
1.36 albertel 9363: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9364: # returns either the contents of the file or
9365: # -1 if the file doesn't exist
1.481 raeburn 9366: #
9367: # if the target is a file that was uploaded via DOCS,
9368: # a check will be made to see if a current copy exists on the local server,
9369: # if it does this will be served, otherwise a copy will be retrieved from
9370: # the home server for the course and stored in /home/httpd/html/userfiles on
9371: # the local server.
1.472 albertel 9372:
1.36 albertel 9373: sub getfile {
1.538 albertel 9374: my ($file) = @_;
1.609 banghart 9375: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9376: &repcopy($file);
9377: return &readfile($file);
9378: }
9379:
9380: sub repcopy_userfile {
9381: my ($file)=@_;
1.609 banghart 9382: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9383: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9384: my ($cdom,$cnum,$filename) =
1.811 albertel 9385: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9386: my $uri="/uploaded/$cdom/$cnum/$filename";
9387: if (-e "$file") {
1.828 www 9388: # we already have a local copy, check it out
1.538 albertel 9389: my @fileinfo = stat($file);
1.828 www 9390: my $rtncode;
9391: my $info;
1.538 albertel 9392: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9393: if ($lwpresp ne 'ok') {
1.828 www 9394: # there is no such file anymore, even though we had a local copy
1.482 albertel 9395: if ($rtncode eq '404') {
1.538 albertel 9396: unlink($file);
1.482 albertel 9397: }
9398: return -1;
9399: }
9400: if ($info < $fileinfo[9]) {
1.828 www 9401: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9402: return 'ok';
1.828 www 9403: } else {
9404: # the file is outdated, get rid of it
9405: unlink($file);
1.482 albertel 9406: }
1.828 www 9407: }
9408: # one way or the other, at this point, we don't have the file
9409: # construct the correct path for the file
9410: my @parts = ($cdom,$cnum);
9411: if ($filename =~ m|^(.+)/[^/]+$|) {
9412: push @parts, split(/\//,$1);
9413: }
9414: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9415: foreach my $part (@parts) {
9416: $path .= '/'.$part;
9417: if (!-e $path) {
9418: mkdir($path,0770);
1.482 albertel 9419: }
9420: }
1.828 www 9421: # now the path exists for sure
9422: # get a user agent
9423: my $ua=new LWP::UserAgent;
9424: my $transferfile=$file.'.in.transfer';
9425: # FIXME: this should flock
9426: if (-e $transferfile) { return 'ok'; }
9427: my $request;
9428: $uri=~s/^\///;
1.980 raeburn 9429: my $homeserver = &homeserver($cnum,$cdom);
9430: my $protocol = $protocol{$homeserver};
9431: $protocol = 'http' if ($protocol ne 'https');
9432: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9433: my $response=$ua->request($request,$transferfile);
9434: # did it work?
9435: if ($response->is_error()) {
9436: unlink($transferfile);
9437: &logthis("Userfile repcopy failed for $uri");
9438: return -1;
9439: }
9440: # worked, rename the transfer file
9441: rename($transferfile,$file);
1.607 raeburn 9442: return 'ok';
1.481 raeburn 9443: }
9444:
1.517 albertel 9445: sub tokenwrapper {
9446: my $uri=shift;
1.980 raeburn 9447: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9448: $uri=~s|^/||;
1.620 albertel 9449: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9450: my $token=$1;
1.552 albertel 9451: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9452: if ($udom && $uname && $file) {
9453: $file=~s|(\?\.*)*$||;
1.949 raeburn 9454: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9455: my $homeserver = &homeserver($uname,$udom);
9456: my $protocol = $protocol{$homeserver};
9457: $protocol = 'http' if ($protocol ne 'https');
9458: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9459: (($uri=~/\?/)?'&':'?').'token='.$token.
9460: '&tokenissued='.$perlvar{'lonHostID'};
9461: } else {
9462: return '/adm/notfound.html';
9463: }
9464: }
9465:
1.828 www 9466: # call with reqtype HEAD: get last modification time
9467: # call with reqtype GET: get the file contents
9468: # Do not call this with reqtype GET for large files! It loads everything into memory
9469: #
1.481 raeburn 9470: sub getuploaded {
9471: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9472: $uri=~s/^\///;
1.980 raeburn 9473: my $homeserver = &homeserver($cnum,$cdom);
9474: my $protocol = $protocol{$homeserver};
9475: $protocol = 'http' if ($protocol ne 'https');
9476: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9477: my $ua=new LWP::UserAgent;
9478: my $request=new HTTP::Request($reqtype,$uri);
9479: my $response=$ua->request($request);
9480: $$rtncode = $response->code;
1.482 albertel 9481: if (! $response->is_success()) {
9482: return 'failed';
9483: }
9484: if ($reqtype eq 'HEAD') {
1.486 www 9485: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9486: } elsif ($reqtype eq 'GET') {
9487: $$info = $response->content;
1.472 albertel 9488: }
1.482 albertel 9489: return 'ok';
1.36 albertel 9490: }
9491:
1.481 raeburn 9492: sub readfile {
9493: my $file = shift;
9494: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9495: my $fh;
9496: open($fh,"<$file");
9497: my $a='';
1.800 albertel 9498: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9499: return $a;
9500: }
9501:
1.36 albertel 9502: sub filelocation {
1.590 banghart 9503: my ($dir,$file) = @_;
9504: my $location;
9505: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9506:
9507: if ($file =~ m-^/adm/-) {
9508: $file=~s-^/adm/wrapper/-/-;
9509: $file=~s-^/adm/coursedocs/showdoc/-/-;
9510: }
1.882 albertel 9511:
1.590 banghart 9512: if ($file=~m:^/~:) { # is a contruction space reference
9513: $location = $file;
9514: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9515: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9516: # is a correct contruction space reference
9517: $location = $file;
1.956 raeburn 9518: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9519: $location = $file;
1.609 banghart 9520: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9521: my ($udom,$uname,$filename)=
1.811 albertel 9522: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9523: my $home=&homeserver($uname,$udom);
9524: my $is_me=0;
9525: my @ids=¤t_machine_ids();
9526: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9527: if ($is_me) {
1.955 raeburn 9528: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9529: } else {
9530: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9531: $udom.'/'.$uname.'/'.$filename;
9532: }
1.882 albertel 9533: } elsif ($file =~ m-^/adm/-) {
9534: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9535: } else {
9536: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9537: $file=~s:^/res/:/:;
9538: if ( !( $file =~ m:^/:) ) {
9539: $location = $dir. '/'.$file;
9540: } else {
9541: $location = '/home/httpd/html/res'.$file;
9542: }
1.59 albertel 9543: }
1.590 banghart 9544: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9545: while ($location=~m{/\.\./}) {
9546: if ($location =~ m{/[^/]+/\.\./}) {
9547: $location=~ s{/[^/]+/\.\./}{/}g;
9548: } else {
9549: $location=~ s{/\.\./}{/}g;
9550: }
9551: } #remove dir/..
1.590 banghart 9552: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9553: return $location;
1.46 www 9554: }
1.36 albertel 9555:
1.46 www 9556: sub hreflocation {
9557: my ($dir,$file)=@_;
1.980 raeburn 9558: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9559: $file=filelocation($dir,$file);
1.700 albertel 9560: } elsif ($file=~m-^/adm/-) {
9561: $file=~s-^/adm/wrapper/-/-;
9562: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9563: }
9564: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9565: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9566: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9567: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9568: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9569: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9570: -/uploaded/$1/$2/-x;
1.46 www 9571: }
1.913 albertel 9572: if ($file=~ m{^/userfiles/}) {
9573: $file =~ s{^/userfiles/}{/uploaded/};
9574: }
1.462 albertel 9575: return $file;
1.465 albertel 9576: }
9577:
9578: sub current_machine_domains {
1.853 albertel 9579: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9580: }
9581:
9582: sub machine_domains {
9583: my ($hostname) = @_;
1.465 albertel 9584: my @domains;
1.838 albertel 9585: my %hostname = &all_hostnames();
1.465 albertel 9586: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9587: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9588: if ($hostname eq $name) {
1.844 albertel 9589: push(@domains,&host_domain($id));
1.465 albertel 9590: }
9591: }
9592: return @domains;
9593: }
9594:
9595: sub current_machine_ids {
1.853 albertel 9596: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9597: }
9598:
9599: sub machine_ids {
9600: my ($hostname) = @_;
9601: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9602: my @ids;
1.888 albertel 9603: my %name_to_host = &all_names();
1.889 albertel 9604: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9605: return @{ $name_to_host{$hostname} };
9606: }
9607: return;
1.31 www 9608: }
9609:
1.824 raeburn 9610: sub additional_machine_domains {
9611: my @domains;
9612: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9613: while( my $line = <$fh>) {
9614: $line =~ s/\s//g;
9615: push(@domains,$line);
9616: }
9617: return @domains;
9618: }
9619:
9620: sub default_login_domain {
9621: my $domain = $perlvar{'lonDefDomain'};
9622: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9623: foreach my $posdom (¤t_machine_domains(),
9624: &additional_machine_domains()) {
9625: if (lc($posdom) eq lc($testdomain)) {
9626: $domain=$posdom;
9627: last;
9628: }
9629: }
9630: return $domain;
9631: }
9632:
1.31 www 9633: # ------------------------------------------------------------- Declutters URLs
9634:
9635: sub declutter {
9636: my $thisfn=shift;
1.569 albertel 9637: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9638: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9639: $thisfn=~s/^\///;
1.697 albertel 9640: $thisfn=~s|^adm/wrapper/||;
9641: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9642: $thisfn=~s/^res\///;
1.1032 raeburn 9643: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9644: $thisfn=~s/\?.+$//;
9645: }
1.268 www 9646: return $thisfn;
9647: }
9648:
9649: # ------------------------------------------------------------- Clutter up URLs
9650:
9651: sub clutter {
9652: my $thisfn='/'.&declutter(shift);
1.887 albertel 9653: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9654: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9655: $thisfn='/res'.$thisfn;
9656: }
1.1031 raeburn 9657: if ($thisfn !~m|^/adm|) {
9658: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9659: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9660: } else {
9661: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9662: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9663: if ($embstyle eq 'ssi'
9664: || ($embstyle eq 'hdn')
9665: || ($embstyle eq 'rat')
9666: || ($embstyle eq 'prv')
9667: || ($embstyle eq 'ign')) {
9668: #do nothing with these
9669: } elsif (($embstyle eq 'img')
1.695 albertel 9670: || ($embstyle eq 'emb')
9671: || ($embstyle eq 'wrp')) {
9672: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9673: } elsif ($embstyle eq 'unk'
9674: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9675: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9676: } else {
1.718 www 9677: # &logthis("Got a blank emb style");
1.695 albertel 9678: }
1.694 albertel 9679: }
9680: }
1.31 www 9681: return $thisfn;
1.12 www 9682: }
9683:
1.787 albertel 9684: sub clutter_with_no_wrapper {
9685: my $uri = &clutter(shift);
9686: if ($uri =~ m-^/adm/-) {
9687: $uri =~ s-^/adm/wrapper/-/-;
9688: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9689: }
9690: return $uri;
9691: }
9692:
1.557 albertel 9693: sub freeze_escape {
9694: my ($value)=@_;
9695: if (ref($value)) {
9696: $value=&nfreeze($value);
9697: return '__FROZEN__'.&escape($value);
9698: }
9699: return &escape($value);
9700: }
9701:
1.11 www 9702:
1.557 albertel 9703: sub thaw_unescape {
9704: my ($value)=@_;
9705: if ($value =~ /^__FROZEN__/) {
9706: substr($value,0,10,undef);
9707: $value=&unescape($value);
9708: return &thaw($value);
9709: }
9710: return &unescape($value);
9711: }
9712:
1.436 albertel 9713: sub correct_line_ends {
9714: my ($result)=@_;
9715: $$result =~s/\r\n/\n/mg;
9716: $$result =~s/\r/\n/mg;
1.415 albertel 9717: }
1.1 albertel 9718: # ================================================================ Main Program
9719:
1.184 www 9720: sub goodbye {
1.204 albertel 9721: &logthis("Starting Shut down");
1.443 albertel 9722: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9723: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9724: #converted
1.599 albertel 9725: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9726: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9727: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9728: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9729: #1.1 only
1.870 albertel 9730: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9731: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9732: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9733: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9734: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9735: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9736: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9737: &flushcourselogs();
9738: &logthis("Shutting down");
9739: }
9740:
1.852 albertel 9741: sub get_dns {
1.869 albertel 9742: my ($url,$func,$ignore_cache) = @_;
9743: if (!$ignore_cache) {
9744: my ($content,$cached)=
9745: &Apache::lonnet::is_cached_new('dns',$url);
9746: if ($cached) {
9747: &$func($content);
9748: return;
9749: }
9750: }
9751:
9752: my %alldns;
1.852 albertel 9753: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9754: foreach my $dns (<$config>) {
9755: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9756: my $line = $1;
9757: my ($host,$protocol) = split(/:/,$line);
9758: if ($protocol ne 'https') {
9759: $protocol = 'http';
9760: }
9761: $alldns{$host} = $protocol;
1.869 albertel 9762: }
9763: while (%alldns) {
9764: my ($dns) = keys(%alldns);
1.852 albertel 9765: my $ua=new LWP::UserAgent;
1.979 raeburn 9766: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9767: my $response=$ua->request($request);
1.979 raeburn 9768: delete($alldns{$dns});
1.852 albertel 9769: next if ($response->is_error());
9770: my @content = split("\n",$response->content);
1.869 albertel 9771: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9772: &$func(\@content);
1.869 albertel 9773: return;
1.852 albertel 9774: }
9775: close($config);
1.871 albertel 9776: my $which = (split('/',$url))[3];
9777: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9778: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9779: my @content = <$config>;
9780: &$func(\@content);
9781: return;
1.852 albertel 9782: }
1.327 albertel 9783: # ------------------------------------------------------------ Read domain file
9784: {
1.852 albertel 9785: my $loaded;
1.846 albertel 9786: my %domain;
9787:
1.852 albertel 9788: sub parse_domain_tab {
9789: my ($lines) = @_;
9790: foreach my $line (@$lines) {
9791: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9792:
1.846 albertel 9793: chomp($line);
1.852 albertel 9794: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9795: my %this_domain;
9796: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9797: 'lang_def', 'city', 'longi', 'lati',
9798: 'primary') {
9799: $this_domain{$field} = shift(@elements);
9800: }
9801: $domain{$name} = \%this_domain;
1.852 albertel 9802: }
9803: }
1.864 albertel 9804:
9805: sub reset_domain_info {
9806: undef($loaded);
9807: undef(%domain);
9808: }
9809:
1.852 albertel 9810: sub load_domain_tab {
1.869 albertel 9811: my ($ignore_cache) = @_;
9812: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9813: my $fh;
9814: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9815: my @lines = <$fh>;
9816: &parse_domain_tab(\@lines);
1.448 albertel 9817: }
1.852 albertel 9818: close($fh);
9819: $loaded = 1;
1.327 albertel 9820: }
1.846 albertel 9821:
9822: sub domain {
1.852 albertel 9823: &load_domain_tab() if (!$loaded);
9824:
1.846 albertel 9825: my ($name,$what) = @_;
9826: return if ( !exists($domain{$name}) );
9827:
9828: if (!$what) {
9829: return $domain{$name}{'description'};
9830: }
9831: return $domain{$name}{$what};
9832: }
1.974 raeburn 9833:
9834: sub domain_info {
9835: &load_domain_tab() if (!$loaded);
9836: return %domain;
9837: }
9838:
1.327 albertel 9839: }
9840:
9841:
1.1 albertel 9842: # ------------------------------------------------------------- Read hosts file
9843: {
1.838 albertel 9844: my %hostname;
1.844 albertel 9845: my %hostdom;
1.845 albertel 9846: my %libserv;
1.852 albertel 9847: my $loaded;
1.888 albertel 9848: my %name_to_host;
1.1074 raeburn 9849: my %internetdom;
1.852 albertel 9850:
9851: sub parse_hosts_tab {
9852: my ($file) = @_;
9853: foreach my $configline (@$file) {
9854: next if ($configline =~ /^(\#|\s*$ )/x);
9855: next if ($configline =~ /^\^/);
9856: chomp($configline);
1.1074 raeburn 9857: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 9858: $name=~s/\s//g;
9859: if ($id && $domain && $role && $name) {
9860: $hostname{$id}=$name;
1.888 albertel 9861: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9862: $hostdom{$id}=$domain;
9863: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9864: if (defined($protocol)) {
9865: if ($protocol eq 'https') {
9866: $protocol{$id} = $protocol;
9867: } else {
9868: $protocol{$id} = 'http';
9869: }
1.968 raeburn 9870: } else {
1.969 raeburn 9871: $protocol{$id} = 'http';
1.968 raeburn 9872: }
1.1074 raeburn 9873: if (defined($intdom)) {
9874: $internetdom{$id} = $intdom;
9875: }
1.852 albertel 9876: }
9877: }
9878: }
1.864 albertel 9879:
9880: sub reset_hosts_info {
1.897 albertel 9881: &purge_remembered();
1.864 albertel 9882: &reset_domain_info();
9883: &reset_hosts_ip_info();
1.892 albertel 9884: undef(%name_to_host);
1.864 albertel 9885: undef(%hostname);
9886: undef(%hostdom);
9887: undef(%libserv);
9888: undef($loaded);
9889: }
1.1 albertel 9890:
1.852 albertel 9891: sub load_hosts_tab {
1.869 albertel 9892: my ($ignore_cache) = @_;
9893: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9894: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9895: my @config = <$config>;
9896: &parse_hosts_tab(\@config);
9897: close($config);
9898: $loaded=1;
1.1 albertel 9899: }
1.852 albertel 9900:
1.838 albertel 9901: sub hostname {
1.852 albertel 9902: &load_hosts_tab() if (!$loaded);
9903:
1.838 albertel 9904: my ($lonid) = @_;
9905: return $hostname{$lonid};
9906: }
1.845 albertel 9907:
1.838 albertel 9908: sub all_hostnames {
1.852 albertel 9909: &load_hosts_tab() if (!$loaded);
9910:
1.838 albertel 9911: return %hostname;
9912: }
1.845 albertel 9913:
1.888 albertel 9914: sub all_names {
9915: &load_hosts_tab() if (!$loaded);
9916:
9917: return %name_to_host;
9918: }
9919:
1.974 raeburn 9920: sub all_host_domain {
9921: &load_hosts_tab() if (!$loaded);
9922: return %hostdom;
9923: }
9924:
1.845 albertel 9925: sub is_library {
1.852 albertel 9926: &load_hosts_tab() if (!$loaded);
9927:
1.845 albertel 9928: return exists($libserv{$_[0]});
9929: }
9930:
9931: sub all_library {
1.852 albertel 9932: &load_hosts_tab() if (!$loaded);
9933:
1.845 albertel 9934: return %libserv;
9935: }
9936:
1.1062 droeschl 9937: sub unique_library {
9938: #2x reverse removes all hostnames that appear more than once
9939: my %unique = reverse &all_library();
9940: return reverse %unique;
9941: }
9942:
1.841 albertel 9943: sub get_servers {
1.852 albertel 9944: &load_hosts_tab() if (!$loaded);
9945:
1.841 albertel 9946: my ($domain,$type) = @_;
9947: my %possible_hosts = ($type eq 'library') ? %libserv
9948: : %hostname;
9949: my %result;
1.842 albertel 9950: if (ref($domain) eq 'ARRAY') {
9951: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9952: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9953: $result{$host} = $hostname;
9954: }
9955: }
9956: } else {
9957: while ( my ($host,$hostname) = each(%possible_hosts)) {
9958: if ($hostdom{$host} eq $domain) {
9959: $result{$host} = $hostname;
9960: }
1.841 albertel 9961: }
9962: }
9963: return %result;
9964: }
1.845 albertel 9965:
1.1062 droeschl 9966: sub get_unique_servers {
9967: my %unique = reverse &get_servers(@_);
9968: return reverse %unique;
9969: }
9970:
1.844 albertel 9971: sub host_domain {
1.852 albertel 9972: &load_hosts_tab() if (!$loaded);
9973:
1.844 albertel 9974: my ($lonid) = @_;
9975: return $hostdom{$lonid};
9976: }
9977:
1.841 albertel 9978: sub all_domains {
1.852 albertel 9979: &load_hosts_tab() if (!$loaded);
9980:
1.841 albertel 9981: my %seen;
9982: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9983: return @uniq;
9984: }
1.1074 raeburn 9985:
9986: sub internet_dom {
9987: &load_hosts_tab() if (!$loaded);
9988:
9989: my ($lonid) = @_;
9990: return $internetdom{$lonid};
9991: }
1.1 albertel 9992: }
9993:
1.847 albertel 9994: {
9995: my %iphost;
1.856 albertel 9996: my %name_to_ip;
9997: my %lonid_to_ip;
1.869 albertel 9998:
1.847 albertel 9999: sub get_hosts_from_ip {
10000: my ($ip) = @_;
10001: my %iphosts = &get_iphost();
10002: if (ref($iphosts{$ip})) {
10003: return @{$iphosts{$ip}};
10004: }
10005: return;
1.839 albertel 10006: }
1.864 albertel 10007:
10008: sub reset_hosts_ip_info {
10009: undef(%iphost);
10010: undef(%name_to_ip);
10011: undef(%lonid_to_ip);
10012: }
1.856 albertel 10013:
10014: sub get_host_ip {
10015: my ($lonid) = @_;
10016: if (exists($lonid_to_ip{$lonid})) {
10017: return $lonid_to_ip{$lonid};
10018: }
10019: my $name=&hostname($lonid);
10020: my $ip = gethostbyname($name);
10021: return if (!$ip || length($ip) ne 4);
10022: $ip=inet_ntoa($ip);
10023: $name_to_ip{$name} = $ip;
10024: $lonid_to_ip{$lonid} = $ip;
10025: return $ip;
10026: }
1.847 albertel 10027:
10028: sub get_iphost {
1.869 albertel 10029: my ($ignore_cache) = @_;
1.894 albertel 10030:
1.869 albertel 10031: if (!$ignore_cache) {
10032: if (%iphost) {
10033: return %iphost;
10034: }
10035: my ($ip_info,$cached)=
10036: &Apache::lonnet::is_cached_new('iphost','iphost');
10037: if ($cached) {
10038: %iphost = %{$ip_info->[0]};
10039: %name_to_ip = %{$ip_info->[1]};
10040: %lonid_to_ip = %{$ip_info->[2]};
10041: return %iphost;
10042: }
10043: }
1.894 albertel 10044:
10045: # get yesterday's info for fallback
10046: my %old_name_to_ip;
10047: my ($ip_info,$cached)=
10048: &Apache::lonnet::is_cached_new('iphost','iphost');
10049: if ($cached) {
10050: %old_name_to_ip = %{$ip_info->[1]};
10051: }
10052:
1.888 albertel 10053: my %name_to_host = &all_names();
10054: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10055: my $ip;
10056: if (!exists($name_to_ip{$name})) {
10057: $ip = gethostbyname($name);
10058: if (!$ip || length($ip) ne 4) {
1.894 albertel 10059: if (defined($old_name_to_ip{$name})) {
10060: $ip = $old_name_to_ip{$name};
10061: &logthis("Can't find $name defaulting to old $ip");
10062: } else {
10063: &logthis("Name $name no IP found");
10064: next;
10065: }
10066: } else {
10067: $ip=inet_ntoa($ip);
1.847 albertel 10068: }
10069: $name_to_ip{$name} = $ip;
10070: } else {
10071: $ip = $name_to_ip{$name};
1.653 albertel 10072: }
1.888 albertel 10073: foreach my $id (@{ $name_to_host{$name} }) {
10074: $lonid_to_ip{$id} = $ip;
10075: }
10076: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10077: }
1.869 albertel 10078: &Apache::lonnet::do_cache_new('iphost','iphost',
10079: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10080: 48*60*60);
1.869 albertel 10081:
1.847 albertel 10082: return %iphost;
1.598 albertel 10083: }
10084:
1.992 raeburn 10085: #
10086: # Given a DNS returns the loncapa host name for that DNS
10087: #
10088: sub host_from_dns {
10089: my ($dns) = @_;
10090: my @hosts;
10091: my $ip;
10092:
1.993 raeburn 10093: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10094: $ip = $name_to_ip{$dns};
10095: }
10096: if (!$ip) {
10097: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10098: if (length($ip) == 4) {
10099: $ip = &IO::Socket::inet_ntoa($ip);
10100: }
10101: }
10102: if ($ip) {
10103: @hosts = get_hosts_from_ip($ip);
10104: return $hosts[0];
10105: }
10106: return undef;
1.986 foxr 10107: }
1.992 raeburn 10108:
1.1074 raeburn 10109: sub get_internet_names {
10110: my ($lonid) = @_;
10111: return if ($lonid eq '');
10112: my ($idnref,$cached)=
10113: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10114: if ($cached) {
10115: return $idnref;
10116: }
10117: my $ip = &get_host_ip($lonid);
10118: my @hosts = &get_hosts_from_ip($ip);
10119: my %iphost = &get_iphost();
10120: my (@idns,%seen);
10121: foreach my $id (@hosts) {
10122: my $dom = &host_domain($id);
10123: my $prim_id = &domain($dom,'primary');
10124: my $prim_ip = &get_host_ip($prim_id);
10125: next if ($seen{$prim_ip});
10126: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10127: foreach my $id (@{$iphost{$prim_ip}}) {
10128: my $intdom = &internet_dom($id);
10129: unless (grep(/^\Q$intdom\E$/,@idns)) {
10130: push(@idns,$intdom);
10131: }
10132: }
10133: }
10134: $seen{$prim_ip} = 1;
10135: }
10136: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10137: }
10138:
1.986 foxr 10139: }
10140:
1.862 albertel 10141: BEGIN {
10142:
10143: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10144: unless ($readit) {
10145: {
10146: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10147: %perlvar = (%perlvar,%{$configvars});
10148: }
10149:
10150:
1.1 albertel 10151: # ------------------------------------------------------ Read spare server file
10152: {
1.448 albertel 10153: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10154:
10155: while (my $configline=<$config>) {
10156: chomp($configline);
1.284 matthew 10157: if ($configline) {
1.784 albertel 10158: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10159: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10160: push(@{ $spareid{$type} }, $host);
1.1 albertel 10161: }
10162: }
1.448 albertel 10163: close($config);
1.1 albertel 10164: }
1.11 www 10165: # ------------------------------------------------------------ Read permissions
10166: {
1.448 albertel 10167: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10168:
10169: while (my $configline=<$config>) {
1.448 albertel 10170: chomp($configline);
10171: if ($configline) {
10172: my ($role,$perm)=split(/ /,$configline);
10173: if ($perm ne '') { $pr{$role}=$perm; }
10174: }
1.11 www 10175: }
1.448 albertel 10176: close($config);
1.11 www 10177: }
10178:
10179: # -------------------------------------------- Read plain texts for permissions
10180: {
1.448 albertel 10181: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10182:
10183: while (my $configline=<$config>) {
1.448 albertel 10184: chomp($configline);
10185: if ($configline) {
1.742 raeburn 10186: my ($short,@plain)=split(/:/,$configline);
10187: %{$prp{$short}} = ();
10188: if (@plain > 0) {
10189: $prp{$short}{'std'} = $plain[0];
10190: for (my $i=1; $i<@plain; $i++) {
10191: $prp{$short}{'alt'.$i} = $plain[$i];
10192: }
10193: }
1.448 albertel 10194: }
1.135 www 10195: }
1.448 albertel 10196: close($config);
1.135 www 10197: }
10198:
10199: # ---------------------------------------------------------- Read package table
10200: {
1.448 albertel 10201: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10202:
10203: while (my $configline=<$config>) {
1.483 albertel 10204: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10205: chomp($configline);
10206: my ($short,$plain)=split(/:/,$configline);
10207: my ($pack,$name)=split(/\&/,$short);
10208: if ($plain ne '') {
10209: $packagetab{$pack.'&'.$name.'&name'}=$name;
10210: $packagetab{$short}=$plain;
10211: }
1.11 www 10212: }
1.448 albertel 10213: close($config);
1.329 matthew 10214: }
10215:
1.1073 raeburn 10216: # ---------------------------------------------------------- Read loncaparev table
10217: {
10218: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10219: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10220: while (my $configline=<$config>) {
10221: chomp($configline);
10222: my ($hostid,$loncaparev)=split(/:/,$configline);
10223: $loncaparevs{$hostid}=$loncaparev;
10224: }
10225: close($config);
10226: }
10227: }
10228: }
10229:
1.1074 raeburn 10230: # ---------------------------------------------------------- Read serverhostID table
10231: {
10232: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10233: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10234: while (my $configline=<$config>) {
10235: chomp($configline);
10236: my ($name,$id)=split(/:/,$configline);
10237: $serverhomeIDs{$name}=$id;
10238: }
10239: close($config);
10240: }
10241: }
10242: }
10243:
1.1073 raeburn 10244: sub all_loncaparevs {
10245: 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);
10246: }
10247:
1.329 matthew 10248: # ------------- set up temporary directory
10249: {
10250: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10251:
1.11 www 10252: }
10253:
1.794 albertel 10254: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10255: 'compress_threshold'=> 20_000,
10256: });
1.185 www 10257:
1.281 www 10258: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10259: $dumpcount=0;
1.958 www 10260: $locknum=0;
1.22 www 10261:
1.163 harris41 10262: &logtouch();
1.672 albertel 10263: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10264: $readit=1;
1.564 albertel 10265: {
10266: use integer;
10267: my $test=(2**32)+1;
1.568 albertel 10268: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10269: &logthis(" Detected 64bit platform ($_64bit)");
10270: }
1.195 www 10271: }
1.1 albertel 10272: }
1.179 www 10273:
1.1 albertel 10274: 1;
1.191 harris41 10275: __END__
10276:
1.243 albertel 10277: =pod
10278:
1.191 harris41 10279: =head1 NAME
10280:
1.243 albertel 10281: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10282:
10283: =head1 SYNOPSIS
10284:
1.243 albertel 10285: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10286:
10287: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10288:
1.243 albertel 10289: Common parameters:
10290:
10291: =over 4
10292:
10293: =item *
10294:
10295: $uname : an internal username (if $cname expecting a course Id specifically)
10296:
10297: =item *
10298:
10299: $udom : a domain (if $cdom expecting a course's domain specifically)
10300:
10301: =item *
10302:
10303: $symb : a resource instance identifier
10304:
10305: =item *
10306:
10307: $namespace : the name of a .db file that contains the data needed or
10308: being set.
10309:
10310: =back
10311:
1.394 bowersj2 10312: =head1 OVERVIEW
1.191 harris41 10313:
1.394 bowersj2 10314: lonnet provides subroutines which interact with the
10315: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10316: about classes, users, and resources.
1.243 albertel 10317:
10318: For many of these objects you can also use this to store data about
10319: them or modify them in various ways.
1.191 harris41 10320:
1.394 bowersj2 10321: =head2 Symbs
1.191 harris41 10322:
1.394 bowersj2 10323: To identify a specific instance of a resource, LON-CAPA uses symbols
10324: or "symbs"X<symb>. These identifiers are built from the URL of the
10325: map, the resource number of the resource in the map, and the URL of
10326: the resource itself. The latter is somewhat redundant, but might help
10327: if maps change.
10328:
10329: An example is
10330:
10331: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10332:
10333: The respective map entry is
10334:
10335: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10336: title="Problem 2">
10337: </resource>
10338:
10339: Symbs are used by the random number generator, as well as to store and
10340: restore data specific to a certain instance of for example a problem.
10341:
10342: =head2 Storing And Retrieving Data
10343:
10344: X<store()>X<cstore()>X<restore()>Three of the most important functions
10345: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10346: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10347: is is the non-critical message twin of cstore. These functions are for
10348: handlers to store a perl hash to a user's permanent data space in an
10349: easy manner, and to retrieve it again on another call. It is expected
10350: that a handler would use this once at the beginning to retrieve data,
10351: and then again once at the end to send only the new data back.
10352:
10353: The data is stored in the user's data directory on the user's
10354: homeserver under the ID of the course.
10355:
10356: The hash that is returned by restore will have all of the previous
10357: value for all of the elements of the hash.
10358:
10359: Example:
10360:
10361: #creating a hash
10362: my %hash;
10363: $hash{'foo'}='bar';
10364:
10365: #storing it
10366: &Apache::lonnet::cstore(\%hash);
10367:
10368: #changing a value
10369: $hash{'foo'}='notbar';
10370:
10371: #adding a new value
10372: $hash{'bar'}='foo';
10373: &Apache::lonnet::cstore(\%hash);
10374:
10375: #retrieving the hash
10376: my %history=&Apache::lonnet::restore();
10377:
10378: #print the hash
10379: foreach my $key (sort(keys(%history))) {
10380: print("\%history{$key} = $history{$key}");
10381: }
10382:
10383: Will print out:
1.191 harris41 10384:
1.394 bowersj2 10385: %history{1:foo} = bar
10386: %history{1:keys} = foo:timestamp
10387: %history{1:timestamp} = 990455579
10388: %history{2:bar} = foo
10389: %history{2:foo} = notbar
10390: %history{2:keys} = foo:bar:timestamp
10391: %history{2:timestamp} = 990455580
10392: %history{bar} = foo
10393: %history{foo} = notbar
10394: %history{timestamp} = 990455580
10395: %history{version} = 2
10396:
10397: Note that the special hash entries C<keys>, C<version> and
10398: C<timestamp> were added to the hash. C<version> will be equal to the
10399: total number of versions of the data that have been stored. The
10400: C<timestamp> attribute will be the UNIX time the hash was
10401: stored. C<keys> is available in every historical section to list which
10402: keys were added or changed at a specific historical revision of a
10403: hash.
10404:
10405: B<Warning>: do not store the hash that restore returns directly. This
10406: will cause a mess since it will restore the historical keys as if the
10407: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10408:
1.394 bowersj2 10409: Calling convention:
1.191 harris41 10410:
1.394 bowersj2 10411: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10412: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10413:
1.394 bowersj2 10414: For more detailed information, see lonnet specific documentation.
1.191 harris41 10415:
1.394 bowersj2 10416: =head1 RETURN MESSAGES
1.191 harris41 10417:
1.394 bowersj2 10418: =over 4
1.191 harris41 10419:
1.394 bowersj2 10420: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10421:
1.394 bowersj2 10422: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10423: when the connection is brought back up
1.191 harris41 10424:
1.394 bowersj2 10425: =item * B<con_failed>: unable to contact remote host and unable to save message
10426: for later delivery
1.191 harris41 10427:
1.967 bisitz 10428: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10429:
1.394 bowersj2 10430: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10431: that was requested
1.191 harris41 10432:
1.243 albertel 10433: =back
1.191 harris41 10434:
1.243 albertel 10435: =head1 PUBLIC SUBROUTINES
1.191 harris41 10436:
1.243 albertel 10437: =head2 Session Environment Functions
1.191 harris41 10438:
1.243 albertel 10439: =over 4
1.191 harris41 10440:
1.394 bowersj2 10441: =item *
10442: X<appenv()>
1.949 raeburn 10443: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10444: the user envirnoment file, and will be restored for each access this
1.620 albertel 10445: user makes during this session, also modifies the %env for the current
1.949 raeburn 10446: process. Optional rolesarrayref - if defined contains a reference to an array
10447: of roles which are exempt from the restriction on modifying user.role entries
10448: in the user's environment.db and in %env.
1.191 harris41 10449:
10450: =item *
1.394 bowersj2 10451: X<delenv()>
1.987 raeburn 10452: B<delenv($delthis,$regexp)>: removes all items from the session
10453: environment file that begin with $delthis. If the
10454: optional second arg - $regexp - is true, $delthis is treated as a
10455: regular expression, otherwise \Q$delthis\E is used.
10456: The values are also deleted from the current processes %env.
1.191 harris41 10457:
1.795 albertel 10458: =item * get_env_multiple($name)
10459:
10460: gets $name from the %env hash, it seemlessly handles the cases where multiple
10461: values may be defined and end up as an array ref.
10462:
10463: returns an array of values
10464:
1.243 albertel 10465: =back
10466:
10467: =head2 User Information
1.191 harris41 10468:
1.243 albertel 10469: =over 4
1.191 harris41 10470:
10471: =item *
1.394 bowersj2 10472: X<queryauthenticate()>
10473: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10474: authentication scheme
10475:
10476: =item *
1.394 bowersj2 10477: X<authenticate()>
1.1073 raeburn 10478: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10479: authenticate user from domain's lib servers (first use the current
10480: one). C<$upass> should be the users password.
1.1073 raeburn 10481: $checkdefauth is optional (value is 1 if a check should be made to
10482: authenticate user using default authentication method, and allow
10483: account creation if username does not have account in the domain).
10484: $clientcancheckhost is optional (value is 1 if checking whether the
10485: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10486:
10487: =item *
1.394 bowersj2 10488: X<homeserver()>
10489: B<homeserver($uname,$udom)>: find the server which has
10490: the user's directory and files (there must be only one), this caches
10491: the answer, and also caches if there is a borken connection.
1.191 harris41 10492:
10493: =item *
1.394 bowersj2 10494: X<idget()>
10495: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10496: (IDs are a unique resource in a domain, there must be only 1 ID per
10497: username, and only 1 username per ID in a specific domain) (returns
10498: hash: id=>name,id=>name)
1.191 harris41 10499:
10500: =item *
1.394 bowersj2 10501: X<idrget()>
10502: B<idrget($udom,@unames)>: find the IDs behind a list of
10503: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10504:
10505: =item *
1.394 bowersj2 10506: X<idput()>
10507: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10508:
10509: =item *
1.394 bowersj2 10510: X<rolesinit()>
10511: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10512:
10513: =item *
1.551 albertel 10514: X<getsection()>
10515: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10516: course $cname, return section name/number or '' for "not in course"
10517: and '-1' for "no section"
10518:
10519: =item *
1.394 bowersj2 10520: X<userenvironment()>
10521: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10522: passed in @what from the requested user's environment, returns a hash
10523:
1.858 raeburn 10524: =item *
10525: X<userlog_query()>
1.859 albertel 10526: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10527: activity.log file. %filters defines filters applied when parsing the
10528: log file. These can be start or end timestamps, or the type of action
10529: - log to look for Login or Logout events, check for Checkin or
10530: Checkout, role for role selection. The response is in the form
10531: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10532: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10533:
1.243 albertel 10534: =back
10535:
10536: =head2 User Roles
10537:
10538: =over 4
10539:
10540: =item *
10541:
1.810 raeburn 10542: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10543: F: full access
10544: U,I,K: authentication modes (cxx only)
10545: '': forbidden
10546: 1: user needs to choose course
10547: 2: browse allowed
1.766 albertel 10548: A: passphrase authentication needed
1.243 albertel 10549:
10550: =item *
10551:
10552: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10553: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10554: and course level
10555:
10556: =item *
10557:
1.988 raeburn 10558: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10559: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10560: $type is Course (default) or Community.
1.988 raeburn 10561: If $forcedefault evaluates to true, text returned will be default
10562: text for $type. Otherwise, if this is a course, the text returned
10563: will be a custom name for the role (if defined in the course's
10564: environment). If no custom name is defined the default is returned.
10565:
1.832 raeburn 10566: =item *
10567:
1.935 raeburn 10568: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10569: All arguments are optional. Returns a hash of a roles, either for
10570: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10571: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10572: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10573: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10574: For each key, value is set to colon-separated start and end times for
10575: the role. If no username and domain are specified, will default to
1.934 raeburn 10576: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10577: of role statuses (active, future or previous), roles
10578: (e.g., cc,in, st etc.) and domains of the roles which can be used
10579: to restrict the list of roles reported. If no array ref is
10580: provided for types, will default to return only active roles.
1.834 albertel 10581:
1.243 albertel 10582: =back
10583:
10584: =head2 User Modification
10585:
10586: =over 4
10587:
10588: =item *
10589:
1.957 raeburn 10590: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10591: user for the level given by URL. Optional start and end dates (leave empty
10592: string or zero for "no date")
1.191 harris41 10593:
10594: =item *
10595:
1.243 albertel 10596: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10597: change a users, password, possible return values are: ok,
10598: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10599: refused
1.191 harris41 10600:
10601: =item *
10602:
1.243 albertel 10603: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10604:
10605: =item *
10606:
1.1058 raeburn 10607: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10608: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10609:
10610: will update user information (firstname,middlename,lastname,generation,
10611: permanentemail), and if forceid is true, student/employee ID also.
10612: A user's institutional affiliation(s) can also be updated.
10613: User information fields will not be overwritten with empty entries
10614: unless the field is included in the $candelete array reference.
10615: This array is included when a single user is modified via "Manage Users",
10616: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10617:
10618: =item *
10619:
1.286 matthew 10620: modifystudent
10621:
1.957 raeburn 10622: modify a student's enrollment and identification information.
1.286 matthew 10623: The course id is resolved based on the current users environment.
10624: This means the envoking user must be a course coordinator or otherwise
10625: associated with a course.
10626:
1.297 matthew 10627: This call is essentially a wrapper for lonnet::modifyuser and
10628: lonnet::modify_student_enrollment
1.286 matthew 10629:
10630: Inputs:
10631:
10632: =over 4
10633:
1.957 raeburn 10634: =item B<$udom> Student's loncapa domain
1.286 matthew 10635:
1.957 raeburn 10636: =item B<$uname> Student's loncapa login name
1.286 matthew 10637:
1.964 bisitz 10638: =item B<$uid> Student/Employee ID
1.286 matthew 10639:
1.957 raeburn 10640: =item B<$umode> Student's authentication mode
1.286 matthew 10641:
1.957 raeburn 10642: =item B<$upass> Student's password
1.286 matthew 10643:
1.957 raeburn 10644: =item B<$first> Student's first name
1.286 matthew 10645:
1.957 raeburn 10646: =item B<$middle> Student's middle name
1.286 matthew 10647:
1.957 raeburn 10648: =item B<$last> Student's last name
1.286 matthew 10649:
1.957 raeburn 10650: =item B<$gene> Student's generation
1.286 matthew 10651:
1.957 raeburn 10652: =item B<$usec> Student's section in course
1.286 matthew 10653:
10654: =item B<$end> Unix time of the roles expiration
10655:
10656: =item B<$start> Unix time of the roles start date
10657:
10658: =item B<$forceid> If defined, allow $uid to be changed
10659:
10660: =item B<$desiredhome> server to use as home server for student
10661:
1.957 raeburn 10662: =item B<$email> Student's permanent e-mail address
10663:
10664: =item B<$type> Type of enrollment (auto or manual)
10665:
1.963 raeburn 10666: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10667:
10668: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10669:
1.963 raeburn 10670: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10671:
1.963 raeburn 10672: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10673:
1.963 raeburn 10674: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10675:
1.286 matthew 10676: =back
1.297 matthew 10677:
10678: =item *
10679:
10680: modify_student_enrollment
10681:
10682: Change a students enrollment status in a class. The environment variable
10683: 'role.request.course' must be defined for this function to proceed.
10684:
10685: Inputs:
10686:
10687: =over 4
10688:
10689: =item $udom, students domain
10690:
10691: =item $uname, students name
10692:
10693: =item $uid, students user id
10694:
10695: =item $first, students first name
10696:
10697: =item $middle
10698:
10699: =item $last
10700:
10701: =item $gene
10702:
10703: =item $usec
10704:
10705: =item $end
10706:
10707: =item $start
10708:
1.957 raeburn 10709: =item $type
10710:
10711: =item $locktype
10712:
10713: =item $cid
10714:
10715: =item $selfenroll
10716:
10717: =item $context
10718:
1.297 matthew 10719: =back
10720:
1.191 harris41 10721:
10722: =item *
10723:
1.243 albertel 10724: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10725: custom role; give a custom role to a user for the level given by URL. Specify
10726: name and domain of role author, and role name
1.191 harris41 10727:
10728: =item *
10729:
1.243 albertel 10730: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10731:
10732: =item *
10733:
1.243 albertel 10734: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10735:
10736: =back
10737:
10738: =head2 Course Infomation
10739:
10740: =over 4
1.191 harris41 10741:
10742: =item *
10743:
1.631 albertel 10744: coursedescription($courseid) : returns a hash of information about the
10745: specified course id, including all environment settings for the
10746: course, the description of the course will be in the hash under the
10747: key 'description'
1.191 harris41 10748:
10749: =item *
10750:
1.624 albertel 10751: resdata($name,$domain,$type,@which) : request for current parameter
10752: setting for a specific $type, where $type is either 'course' or 'user',
10753: @what should be a list of parameters to ask about. This routine caches
10754: answers for 5 minutes.
1.243 albertel 10755:
1.877 foxr 10756: =item *
10757:
10758: get_courseresdata($courseid, $domain) : dump the entire course resource
10759: data base, returning a hash that is keyed by the resource name and has
10760: values that are the resource value. I believe that the timestamps and
10761: versions are also returned.
10762:
10763:
1.243 albertel 10764: =back
10765:
10766: =head2 Course Modification
10767:
10768: =over 4
1.191 harris41 10769:
10770: =item *
10771:
1.243 albertel 10772: writecoursepref($courseid,%prefs) : write preferences (environment
10773: database) for a course
1.191 harris41 10774:
10775: =item *
10776:
1.1011 raeburn 10777: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10778:
10779: =item *
10780:
1.1038 raeburn 10781: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10782:
10783: =back
10784:
10785: =head2 Resource Subroutines
10786:
10787: =over 4
1.191 harris41 10788:
10789: =item *
10790:
1.243 albertel 10791: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10792:
10793: =item *
10794:
1.243 albertel 10795: repcopy($filename) : subscribes to the requested file, and attempts to
10796: replicate from the owning library server, Might return
1.607 raeburn 10797: 'unavailable', 'not_found', 'forbidden', 'ok', or
10798: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10799: resource. Expects the local filesystem pathname
10800: (/home/httpd/html/res/....)
10801:
10802: =back
10803:
10804: =head2 Resource Information
10805:
10806: =over 4
1.191 harris41 10807:
10808: =item *
10809:
1.243 albertel 10810: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10811: a vairety of different possible values, $varname should be a request
10812: string, and the other parameters can be used to specify who and what
10813: one is asking about.
10814:
10815: Possible values for $varname are environment.lastname (or other item
10816: from the envirnment hash), user.name (or someother aspect about the
10817: user), resource.0.maxtries (or some other part and parameter of a
10818: resource)
1.204 albertel 10819:
10820: =item *
10821:
1.243 albertel 10822: directcondval($number) : get current value of a condition; reads from a state
10823: string
1.204 albertel 10824:
10825: =item *
10826:
1.243 albertel 10827: condval($condidx) : value of condition index based on state
1.204 albertel 10828:
10829: =item *
10830:
1.243 albertel 10831: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10832: resource's metadata, $what should be either a specific key, or either
10833: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10834: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10835:
10836: this function automatically caches all requests
1.191 harris41 10837:
10838: =item *
10839:
1.243 albertel 10840: metadata_query($query,$custom,$customshow) : make a metadata query against the
10841: network of library servers; returns file handle of where SQL and regex results
10842: will be stored for query
1.191 harris41 10843:
10844: =item *
10845:
1.243 albertel 10846: symbread($filename) : return symbolic list entry (filename argument optional);
10847: returns the data handle
1.191 harris41 10848:
10849: =item *
10850:
1.243 albertel 10851: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10852: a possible symb for the URL in $thisfn, and if is an encryypted
10853: resource that the user accessed using /enc/ returns a 1 on success, 0
10854: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10855: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10856:
1.191 harris41 10857:
10858: =item *
10859:
1.243 albertel 10860: symbclean($symb) : removes versions numbers from a symb, returns the
10861: cleaned symb
1.191 harris41 10862:
10863: =item *
10864:
1.243 albertel 10865: is_on_map($uri) : checks if the $uri is somewhere on the current
10866: course map, user must be in a course for it to work.
1.191 harris41 10867:
10868: =item *
10869:
1.243 albertel 10870: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10871:
10872: =item *
10873:
1.243 albertel 10874: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10875: a random seed, all arguments are optional, if they aren't sent it uses the
10876: environment to derive them. Note: if symb isn't sent and it can't get one
10877: from &symbread it will use the current time as its return value
1.191 harris41 10878:
10879: =item *
10880:
1.243 albertel 10881: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10882: unfakeable, receipt
1.191 harris41 10883:
10884: =item *
10885:
1.620 albertel 10886: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10887:
10888: =item *
10889:
1.243 albertel 10890: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10891:
10892: =item *
10893:
1.243 albertel 10894: 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 10895:
10896: =item *
10897:
1.243 albertel 10898: 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 10899:
10900: =item *
10901:
1.243 albertel 10902: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10903:
10904: =item *
10905:
1.243 albertel 10906: devalidate($symb) : devalidate temporary spreadsheet calculations,
10907: forcing spreadsheet to reevaluate the resource scores next time.
10908:
10909: =back
10910:
10911: =head2 Storing/Retreiving Data
10912:
10913: =over 4
1.191 harris41 10914:
10915: =item *
10916:
1.243 albertel 10917: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10918: for this url; hashref needs to be given and should be a \%hashname; the
10919: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10920: be derived from the env
1.191 harris41 10921:
10922: =item *
10923:
1.243 albertel 10924: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10925: uses critical subroutine
1.191 harris41 10926:
10927: =item *
10928:
1.243 albertel 10929: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10930: all args are optional
1.191 harris41 10931:
10932: =item *
10933:
1.717 albertel 10934: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10935: dumps the complete (or key matching regexp) namespace into a hash
10936: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10937: normally &store()ed into
10938:
10939: $range should be either an integer '100' (give me the first 100
10940: matching records)
10941: or be two integers sperated by a - with no spaces
10942: '30-50' (give me the 30th through the 50th matching
10943: records)
10944:
10945:
10946: =item *
10947:
10948: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10949: replaces a &store() version of data with a replacement set of data
10950: for a particular resource in a namespace passed in the $storehash hash
10951: reference
10952:
10953: =item *
10954:
1.243 albertel 10955: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10956: works very similar to store/cstore, but all data is stored in a
10957: temporary location and can be reset using tmpreset, $storehash should
10958: be a hash reference, returns nothing on success
1.191 harris41 10959:
10960: =item *
10961:
1.243 albertel 10962: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10963: similar to restore, but all data is stored in a temporary location and
10964: can be reset using tmpreset. Returns a hash of values on success,
10965: error string otherwise.
1.191 harris41 10966:
10967: =item *
10968:
1.243 albertel 10969: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10970: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10971:
10972: =item *
10973:
1.243 albertel 10974: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10975: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10976:
10977: =item *
10978:
1.243 albertel 10979: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10980: namesp ($udom and $uname are optional)
1.191 harris41 10981:
10982: =item *
10983:
1.702 albertel 10984: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10985: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10986: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10987:
1.702 albertel 10988: $range should be either an integer '100' (give me the first 100
10989: matching records)
10990: or be two integers sperated by a - with no spaces
10991: '30-50' (give me the 30th through the 50th matching
10992: records)
1.449 matthew 10993: =item *
10994:
10995: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10996: $store can be a scalar, an array reference, or if the amount to be
10997: incremented is > 1, a hash reference.
10998:
10999: ($udom and $uname are optional)
1.191 harris41 11000:
11001: =item *
11002:
1.243 albertel 11003: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11004: ($udom and $uname are optional)
1.191 harris41 11005:
11006: =item *
11007:
1.243 albertel 11008: cput($namespace,$storehash,$udom,$uname) : critical put
11009: ($udom and $uname are optional)
1.191 harris41 11010:
11011: =item *
11012:
1.748 albertel 11013: newput($namespace,$storehash,$udom,$uname) :
11014:
11015: Attempts to store the items in the $storehash, but only if they don't
11016: currently exist, if this succeeds you can be certain that you have
11017: successfully created a new key value pair in the $namespace db.
11018:
11019:
11020: Args:
11021: $namespace: name of database to store values to
11022: $storehash: hashref to store to the db
11023: $udom: (optional) domain of user containing the db
11024: $uname: (optional) name of user caontaining the db
11025:
11026: Returns:
11027: 'ok' -> succeeded in storing all keys of $storehash
11028: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11029: least <key> already existed in the db (other
11030: requested keys may also already exist)
1.967 bisitz 11031: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11032: 'con_lost' -> unable to contact request server
11033: 'refused' -> action was not allowed by remote machine
11034:
11035:
11036: =item *
11037:
1.243 albertel 11038: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11039: reference filled in from namesp (encrypts the return communication)
11040: ($udom and $uname are optional)
1.191 harris41 11041:
11042: =item *
11043:
1.243 albertel 11044: log($udom,$name,$home,$message) : write to permanent log for user; use
11045: critical subroutine
11046:
1.806 raeburn 11047: =item *
11048:
1.860 raeburn 11049: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11050: array reference filled in from namespace found in domain level on either
11051: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11052:
11053: =item *
11054:
1.860 raeburn 11055: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11056: domain level either on specified domain server ($uhome) or primary domain
11057: server ($udom and $uhome are optional)
1.806 raeburn 11058:
1.943 raeburn 11059: =item *
11060:
11061: get_domain_defaults($target_domain) : returns hash with defaults for
11062: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11063: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11064: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11065: Values are retrieved from cache (if current), or from domain's configuration.db
11066: (if available), or lastly from values in lonTabs/dns_domain,tab,
11067: or lonTabs/domain.tab.
11068:
11069: %domdefaults = &get_auth_defaults($target_domain);
11070:
1.243 albertel 11071: =back
11072:
11073: =head2 Network Status Functions
11074:
11075: =over 4
1.191 harris41 11076:
11077: =item *
11078:
11079: dirlist($uri) : return directory list based on URI
11080:
11081: =item *
11082:
1.243 albertel 11083: spareserver() : find server with least workload from spare.tab
11084:
1.986 foxr 11085:
11086: =item *
11087:
11088: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11089: if there is no corresponding loncapa host.
11090:
1.243 albertel 11091: =back
11092:
1.986 foxr 11093:
1.243 albertel 11094: =head2 Apache Request
11095:
11096: =over 4
1.191 harris41 11097:
11098: =item *
11099:
1.243 albertel 11100: ssi($url,%hash) : server side include, does a complete request cycle on url to
11101: localhost, posts hash
11102:
11103: =back
11104:
11105: =head2 Data to String to Data
11106:
11107: =over 4
1.191 harris41 11108:
11109: =item *
11110:
1.243 albertel 11111: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11112: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11113:
11114: =item *
11115:
1.243 albertel 11116: hashref2str($hashref) : convert a hashref into a string complete with
11117: escaping and '=' and '&' separators, supports elements that are
11118: arrayrefs and hashrefs
1.191 harris41 11119:
11120: =item *
11121:
1.243 albertel 11122: arrayref2str($arrayref) : convert an arrayref into a string complete
11123: with escaping and '&' separators, supports elements that are arrayrefs
11124: and hashrefs
1.191 harris41 11125:
11126: =item *
11127:
1.243 albertel 11128: str2hash($string) : convert string to hash using unescaping and
11129: splitting on '=' and '&', supports elements that are arrayrefs and
11130: hashrefs
1.191 harris41 11131:
11132: =item *
11133:
1.243 albertel 11134: str2array($string) : convert string to hash using unescaping and
11135: splitting on '&', supports elements that are arrayrefs and hashrefs
11136:
11137: =back
11138:
11139: =head2 Logging Routines
11140:
11141: =over 4
11142:
11143: These routines allow one to make log messages in the lonnet.log and
11144: lonnet.perm logfiles.
1.191 harris41 11145:
11146: =item *
11147:
1.243 albertel 11148: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11149:
11150: =item *
11151:
1.243 albertel 11152: logthis() : append message to the normal lonnet.log file, it gets
11153: preiodically rolled over and deleted.
1.191 harris41 11154:
11155: =item *
11156:
1.243 albertel 11157: logperm() : append a permanent message to lonnet.perm.log, this log
11158: file never gets deleted by any automated portion of the system, only
11159: messages of critical importance should go in here.
11160:
11161: =back
11162:
11163: =head2 General File Helper Routines
11164:
11165: =over 4
1.191 harris41 11166:
11167: =item *
11168:
1.481 raeburn 11169: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11170: (a) files in /uploaded
11171: (i) If a local copy of the file exists -
11172: compares modification date of local copy with last-modified date for
11173: definitive version stored on home server for course. If local copy is
11174: stale, requests a new version from the home server and stores it.
11175: If the original has been removed from the home server, then local copy
11176: is unlinked.
11177: (ii) If local copy does not exist -
11178: requests the file from the home server and stores it.
11179:
11180: If $caller is 'uploadrep':
11181: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11182: for request for files originally uploaded via DOCS.
11183: - returns 'ok' if fresh local copy now available, -1 otherwise.
11184:
11185: Otherwise:
11186: This indicates a call from the content generation phase of the request.
11187: - returns the entire contents of the file or -1.
11188:
11189: (b) files in /res
11190: - returns the entire contents of a file or -1;
11191: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11192:
1.712 albertel 11193:
11194: =item *
11195:
11196: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11197: reference
11198:
11199: returns either a stat() list of data about the file or an empty list
11200: if the file doesn't exist or couldn't find out about it (connection
11201: problems or user unknown)
11202:
1.191 harris41 11203: =item *
11204:
1.243 albertel 11205: filelocation($dir,$file) : returns file system location of a file
11206: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11207: directory that relative $file lookups are to looked in ($dir of /a/dir
11208: and a file of ../bob will become /a/bob)
1.191 harris41 11209:
11210: =item *
11211:
11212: hreflocation($dir,$file) : returns file system location or a URL; same as
11213: filelocation except for hrefs
11214:
11215: =item *
11216:
11217: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11218:
1.243 albertel 11219: =back
11220:
1.608 albertel 11221: =head2 Usererfile file routines (/uploaded*)
11222:
11223: =over 4
11224:
11225: =item *
11226:
11227: userfileupload(): main rotine for putting a file in a user or course's
11228: filespace, arguments are,
11229:
1.620 albertel 11230: formname - required - this is the name of the element in $env where the
1.608 albertel 11231: filename, and the contents of the file to create/modifed exist
1.620 albertel 11232: the filename is in $env{'form.'.$formname.'.filename'} and the
11233: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11234: coursedoc - if true, store the file in the course of the active role
11235: of the current user
11236: subdir - required - subdirectory to put the file in under ../userfiles/
11237: if undefined, it will be placed in "unknown"
11238:
11239: (This routine calls clean_filename() to remove any dangerous
11240: characters from the filename, and then calls finuserfileupload() to
11241: complete the transaction)
11242:
11243: returns either the url of the uploaded file (/uploaded/....) if successful
11244: and /adm/notfound.html if unsuccessful
11245:
11246: =item *
11247:
11248: clean_filename(): routine for cleaing a filename up for storage in
11249: userfile space, argument is:
11250:
11251: filename - proposed filename
11252:
11253: returns: the new clean filename
11254:
11255: =item *
11256:
11257: finishuserfileupload(): routine that creaes and sends the file to
11258: userspace, probably shouldn't be called directly
11259:
11260: docuname: username or courseid of destination for the file
11261: docudom: domain of user/course of destination for the file
11262: formname: same as for userfileupload()
11263: fname: filename (inculding subdirectories) for the file
11264:
11265: returns either the url of the uploaded file (/uploaded/....) if successful
11266: and /adm/notfound.html if unsuccessful
11267:
11268: =item *
11269:
11270: renameuserfile(): renames an existing userfile to a new name
11271:
11272: Args:
11273: docuname: username or courseid of destination for the file
11274: docudom: domain of user/course of destination for the file
11275: old: current file name (including any subdirs under userfiles)
11276: new: desired file name (including any subdirs under userfiles)
11277:
11278: =item *
11279:
11280: mkdiruserfile(): creates a directory is a userfiles dir
11281:
11282: Args:
11283: docuname: username or courseid of destination for the file
11284: docudom: domain of user/course of destination for the file
11285: dir: dir to create (including any subdirs under userfiles)
11286:
11287: =item *
11288:
11289: removeuserfile(): removes a file that exists in userfiles
11290:
11291: Args:
11292: docuname: username or courseid of destination for the file
11293: docudom: domain of user/course of destination for the file
11294: fname: filname to delete (including any subdirs under userfiles)
11295:
11296: =item *
11297:
11298: removeuploadedurl(): convience function for removeuserfile()
11299:
11300: Args:
11301: url: a full /uploaded/... url to delete
11302:
1.747 albertel 11303: =item *
11304:
11305: get_portfile_permissions():
11306: Args:
11307: domain: domain of user or course contain the portfolio files
11308: user: name of user or num of course contain the portfolio files
11309: Returns:
11310: hashref of a dump of the proper file_permissions.db
11311:
11312:
11313: =item *
11314:
11315: get_access_controls():
11316:
11317: Args:
11318: current_permissions: the hash ref returned from get_portfile_permissions()
11319: group: (optional) the group you want the files associated with
11320: file: (optional) the file you want access info on
11321:
11322: Returns:
1.749 raeburn 11323: a hash (keys are file names) of hashes containing
11324: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11325: values are XML containing access control settings (see below)
1.747 albertel 11326:
11327: Internal notes:
11328:
1.749 raeburn 11329: access controls are stored in file_permissions.db as key=value pairs.
11330: key -> path to file/file_name\0uniqueID:scope_end_start
11331: where scope -> public,guest,course,group,domains or users.
11332: end -> UNIX time for end of access (0 -> no end date)
11333: start -> UNIX time for start of access
11334:
11335: value -> XML description of access control
11336: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11337: <start></start>
11338: <end></end>
11339:
11340: <password></password> for scope type = guest
11341:
11342: <domain></domain> for scope type = course or group
11343: <number></number>
11344: <roles id="">
11345: <role></role>
11346: <access></access>
11347: <section></section>
11348: <group></group>
11349: </roles>
11350:
11351: <dom></dom> for scope type = domains
11352:
11353: <users> for scope type = users
11354: <user>
11355: <uname></uname>
11356: <udom></udom>
11357: </user>
11358: </users>
11359: </scope>
11360:
11361: Access data is also aggregated for each file in an additional key=value pair:
11362: key -> path to file/file_name\0accesscontrol
11363: value -> reference to hash
11364: hash contains key = value pairs
11365: where key = uniqueID:scope_end_start
11366: value = UNIX time record was last updated
11367:
11368: Used to improve speed of look-ups of access controls for each file.
11369:
11370: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11371:
11372: modify_access_controls():
11373:
11374: Modifies access controls for a portfolio file
11375: Args
11376: 1. file name
11377: 2. reference to hash of required changes,
11378: 3. domain
11379: 4. username
11380: where domain,username are the domain of the portfolio owner
11381: (either a user or a course)
11382:
11383: Returns:
11384: 1. result of additions or updates ('ok' or 'error', with error message).
11385: 2. result of deletions ('ok' or 'error', with error message).
11386: 3. reference to hash of any new or updated access controls.
11387: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11388: key = integer (inbound ID)
11389: value = uniqueID
1.747 albertel 11390:
1.608 albertel 11391: =back
11392:
1.243 albertel 11393: =head2 HTTP Helper Routines
11394:
11395: =over 4
11396:
1.191 harris41 11397: =item *
11398:
11399: escape() : unpack non-word characters into CGI-compatible hex codes
11400:
11401: =item *
11402:
11403: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11404:
1.243 albertel 11405: =back
11406:
11407: =head1 PRIVATE SUBROUTINES
11408:
11409: =head2 Underlying communication routines (Shouldn't call)
11410:
11411: =over 4
11412:
11413: =item *
11414:
11415: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11416:
11417: =item *
11418:
11419: reply() : uses subreply to send a message to remote machine, logs all failures
11420:
11421: =item *
11422:
11423: critical() : passes a critical message to another server; if cannot
11424: get through then place message in connection buffer directory and
11425: returns con_delayed, if incapable of saving message, returns
11426: con_failed
11427:
11428: =item *
11429:
11430: reconlonc() : tries to reconnect lonc client processes.
11431:
11432: =back
11433:
11434: =head2 Resource Access Logging
11435:
11436: =over 4
11437:
11438: =item *
11439:
11440: flushcourselogs() : flush (save) buffer logs and access logs
11441:
11442: =item *
11443:
11444: courselog($what) : save message for course in hash
11445:
11446: =item *
11447:
11448: courseacclog($what) : save message for course using &courselog(). Perform
11449: special processing for specific resource types (problems, exams, quizzes, etc).
11450:
1.191 harris41 11451: =item *
11452:
11453: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11454: as a PerlChildExitHandler
1.243 albertel 11455:
11456: =back
11457:
11458: =head2 Other
11459:
11460: =over 4
11461:
11462: =item *
11463:
11464: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11465:
11466: =back
11467:
11468: =cut
1.877 foxr 11469:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>