Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.2.10
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.2.10! raeburn 4: # $Id: lonnet.pm,v 1.1056.2.9 2010/11/11 20:56:04 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.968 raeburn 79: $_64bit %env %protocol);
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 {
199: my ($dom,$lonhost) = @_;
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)) {
214: my $cachetime = 24*3600;
215: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
216: if (defined($cached)) {
217: return $loncaparev;
218: } else {
219: my $loncaparev = &reply('serverloncaparev',$lonhost);
220: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
221: }
222: }
223: }
224:
1.1 albertel 225: # -------------------------------------------------- Non-critical communication
226: sub subreply {
227: my ($cmd,$server)=@_;
1.838 albertel 228: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 229: #
230: # With loncnew process trimming, there's a timing hole between lonc server
231: # process exit and the master server picking up the listen on the AF_UNIX
232: # socket. In that time interval, a lock file will exist:
233:
234: my $lockfile=$peerfile.".lock";
235: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
236: sleep(1);
237: }
238: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 239: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 240: #
1.550 foxr 241: # We'll give the connection a few tries before abandoning it. If
242: # connection is not possible, we'll con_lost back to the client.
243: #
244: my $client;
245: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
246: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
247: Type => SOCK_STREAM,
248: Timeout => 10);
1.869 albertel 249: if ($client) {
1.550 foxr 250: last; # Connected!
1.850 albertel 251: } else {
1.853 albertel 252: &create_connection(&hostname($server),$server);
1.550 foxr 253: }
1.850 albertel 254: sleep(1); # Try again later if failed connection.
1.550 foxr 255: }
256: my $answer;
257: if ($client) {
1.704 albertel 258: print $client "sethost:$server:$cmd\n";
1.550 foxr 259: $answer=<$client>;
260: if (!$answer) { $answer="con_lost"; }
261: chomp($answer);
262: } else {
263: $answer = 'con_lost'; # Failed connection.
264: }
1.1 albertel 265: return $answer;
266: }
267:
268: sub reply {
269: my ($cmd,$server)=@_;
1.838 albertel 270: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 271: my $answer=subreply($cmd,$server);
1.65 www 272: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 273: &logthis("<font color=\"blue\">WARNING:".
1.12 www 274: " $cmd to $server returned $answer</font>");
275: }
1.1 albertel 276: return $answer;
277: }
278:
279: # ----------------------------------------------------------- Send USR1 to lonc
280:
281: sub reconlonc {
1.891 albertel 282: my ($lonid) = @_;
283: my $hostname = &hostname($lonid);
284: if ($lonid) {
285: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
286: if ($hostname && -e $peerfile) {
287: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
288: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
289: Type => SOCK_STREAM,
290: Timeout => 10);
291: if ($client) {
292: print $client ("reset_retries\n");
293: my $answer=<$client>;
294: #reset just this one.
295: }
296: }
297: return;
298: }
299:
1.836 www 300: &logthis("Trying to reconnect lonc");
1.1 albertel 301: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 302: if (open(my $fh,"<$loncfile")) {
1.1 albertel 303: my $loncpid=<$fh>;
304: chomp($loncpid);
305: if (kill 0 => $loncpid) {
306: &logthis("lonc at pid $loncpid responding, sending USR1");
307: kill USR1 => $loncpid;
308: sleep 1;
1.836 www 309: } else {
1.12 www 310: &logthis(
1.672 albertel 311: "<font color=\"blue\">WARNING:".
1.12 www 312: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 313: }
314: } else {
1.836 www 315: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 316: }
317: }
318:
319: # ------------------------------------------------------ Critical communication
1.12 www 320:
1.1 albertel 321: sub critical {
322: my ($cmd,$server)=@_;
1.838 albertel 323: unless (&hostname($server)) {
1.672 albertel 324: &logthis("<font color=\"blue\">WARNING:".
1.89 www 325: " Critical message to unknown server ($server)</font>");
326: return 'no_such_host';
327: }
1.1 albertel 328: my $answer=reply($cmd,$server);
329: if ($answer eq 'con_lost') {
330: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 331: my $answer=reply($cmd,$server);
1.1 albertel 332: if ($answer eq 'con_lost') {
333: my $now=time;
334: my $middlename=$cmd;
1.5 www 335: $middlename=substr($middlename,0,16);
1.1 albertel 336: $middlename=~s/\W//g;
337: my $dfilename=
1.305 www 338: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
339: $dumpcount++;
1.1 albertel 340: {
1.448 albertel 341: my $dfh;
342: if (open($dfh,">$dfilename")) {
343: print $dfh "$cmd\n";
344: close($dfh);
345: }
1.1 albertel 346: }
347: sleep 2;
348: my $wcmd='';
349: {
1.448 albertel 350: my $dfh;
351: if (open($dfh,"<$dfilename")) {
352: $wcmd=<$dfh>;
353: close($dfh);
354: }
1.1 albertel 355: }
356: chomp($wcmd);
1.7 www 357: if ($wcmd eq $cmd) {
1.672 albertel 358: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 359: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 360: &logperm("D:$server:$cmd");
361: return 'con_delayed';
362: } else {
1.672 albertel 363: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 364: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 365: &logperm("F:$server:$cmd");
366: return 'con_failed';
367: }
368: }
369: }
370: return $answer;
1.405 albertel 371: }
372:
1.755 albertel 373: # ------------------------------------------- check if return value is an error
374:
375: sub error {
376: my ($result) = @_;
1.756 albertel 377: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 378: if ($2 == 2) { return undef; }
379: return $1;
380: }
381: return undef;
382: }
383:
1.783 albertel 384: sub convert_and_load_session_env {
385: my ($lonidsdir,$handle)=@_;
386: my @profile;
387: {
1.917 albertel 388: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
389: if (!$opened) {
1.915 albertel 390: return 0;
391: }
1.783 albertel 392: flock($idf,LOCK_SH);
393: @profile=<$idf>;
394: close($idf);
395: }
396: my %temp_env;
397: foreach my $line (@profile) {
1.786 albertel 398: if ($line !~ m/=/) {
399: return 0;
400: }
1.783 albertel 401: chomp($line);
402: my ($envname,$envvalue)=split(/=/,$line,2);
403: $temp_env{&unescape($envname)} = &unescape($envvalue);
404: }
405: unlink("$lonidsdir/$handle.id");
406: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
407: 0640)) {
408: %disk_env = %temp_env;
409: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
410: untie(%disk_env);
411: }
1.786 albertel 412: return 1;
1.783 albertel 413: }
414:
1.374 www 415: # ------------------------------------------- Transfer profile into environment
1.780 albertel 416: my $env_loaded;
417: sub transfer_profile_to_env {
1.788 albertel 418: my ($lonidsdir,$handle,$force_transfer) = @_;
419: if (!$force_transfer && $env_loaded) { return; }
1.374 www 420:
1.720 albertel 421: if (!defined($lonidsdir)) {
422: $lonidsdir = $perlvar{'lonIDsDir'};
423: }
424: if (!defined($handle)) {
425: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
426: }
427:
1.786 albertel 428: my $convert;
429: {
1.917 albertel 430: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
431: if (!$opened) {
1.915 albertel 432: return;
433: }
1.786 albertel 434: flock($idf,LOCK_SH);
435: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
436: &GDBM_READER(),0640)) {
437: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
438: untie(%disk_env);
439: } else {
440: $convert = 1;
441: }
442: }
443: if ($convert) {
444: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
445: &logthis("Failed to load session, or convert session.");
446: }
1.374 www 447: }
1.783 albertel 448:
1.786 albertel 449: my %remove;
1.783 albertel 450: while ( my $envname = each(%env) ) {
1.433 matthew 451: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
452: if ($time < time-300) {
1.783 albertel 453: $remove{$key}++;
1.433 matthew 454: }
455: }
456: }
1.783 albertel 457:
1.619 albertel 458: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 459: $env_loaded=1;
1.783 albertel 460: foreach my $expired_key (keys(%remove)) {
1.433 matthew 461: &delenv($expired_key);
1.374 www 462: }
1.1 albertel 463: }
464:
1.916 albertel 465: # ---------------------------------------------------- Check for valid session
466: sub check_for_valid_session {
467: my ($r) = @_;
468: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
469: my $lonid=$cookies{'lonID'};
470: return undef if (!$lonid);
471:
472: my $handle=&LONCAPA::clean_handle($lonid->value);
473: my $lonidsdir=$r->dir_config('lonIDsDir');
474: return undef if (!-e "$lonidsdir/$handle.id");
475:
1.917 albertel 476: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
477: return undef if (!$opened);
1.916 albertel 478:
479: flock($idf,LOCK_SH);
480: my %disk_env;
481: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
482: &GDBM_READER(),0640)) {
483: return undef;
484: }
485:
486: if (!defined($disk_env{'user.name'})
487: || !defined($disk_env{'user.domain'})) {
488: return undef;
489: }
490: return $handle;
491: }
492:
1.830 albertel 493: sub timed_flock {
494: my ($file,$lock_type) = @_;
495: my $failed=0;
496: eval {
497: local $SIG{__DIE__}='DEFAULT';
498: local $SIG{ALRM}=sub {
499: $failed=1;
500: die("failed lock");
501: };
502: alarm(13);
503: flock($file,$lock_type);
504: alarm(0);
505: };
506: if ($failed) {
507: return undef;
508: } else {
509: return 1;
510: }
511: }
512:
1.5 www 513: # ---------------------------------------------------------- Append Environment
514:
515: sub appenv {
1.949 raeburn 516: my ($newenv,$roles) = @_;
517: if (ref($newenv) eq 'HASH') {
518: foreach my $key (keys(%{$newenv})) {
519: my $refused = 0;
520: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
521: $refused = 1;
522: if (ref($roles) eq 'ARRAY') {
523: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
524: if (grep(/^\Q$role\E$/,@{$roles})) {
525: $refused = 0;
526: }
527: }
528: }
529: if ($refused) {
530: &logthis("<font color=\"blue\">WARNING: ".
531: "Attempt to modify environment ".$key." to ".$newenv->{$key}
532: .'</font>');
533: delete($newenv->{$key});
534: } else {
535: $env{$key}=$newenv->{$key};
536: }
537: }
538: my $opened = open(my $env_file,'+<',$env{'user.environment'});
539: if ($opened
540: && &timed_flock($env_file,LOCK_EX)
541: &&
542: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
543: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
544: while (my ($key,$value) = each(%{$newenv})) {
545: $disk_env{$key} = $value;
546: }
547: untie(%disk_env);
1.35 www 548: }
1.191 harris41 549: }
1.56 www 550: return 'ok';
551: }
552: # ----------------------------------------------------- Delete from Environment
553:
554: sub delenv {
1.987 raeburn 555: my ($delthis,$regexp) = @_;
1.56 www 556: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 557: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 558: "Attempt to delete from environment ".$delthis);
559: return 'error';
560: }
1.917 albertel 561: my $opened = open(my $env_file,'+<',$env{'user.environment'});
562: if ($opened
1.915 albertel 563: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 564: &&
565: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
566: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 567: foreach my $key (keys(%disk_env)) {
1.987 raeburn 568: if ($regexp) {
569: if ($key=~/^$delthis/) {
570: delete($env{$key});
571: delete($disk_env{$key});
572: }
573: } else {
574: if ($key=~/^\Q$delthis\E/) {
575: delete($env{$key});
576: delete($disk_env{$key});
577: }
578: }
1.448 albertel 579: }
1.783 albertel 580: untie(%disk_env);
1.5 www 581: }
582: return 'ok';
1.369 albertel 583: }
584:
1.790 albertel 585: sub get_env_multiple {
586: my ($name) = @_;
587: my @values;
588: if (defined($env{$name})) {
589: # exists is it an array
590: if (ref($env{$name})) {
591: @values=@{ $env{$name} };
592: } else {
593: $values[0]=$env{$name};
594: }
595: }
596: return(@values);
597: }
598:
1.958 www 599: # ------------------------------------------------------------------- Locking
600:
601: sub set_lock {
602: my ($text)=@_;
603: $locknum++;
604: my $id=$$.'-'.$locknum;
605: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
606: 'session.lock.'.$id => $text});
607: return $id;
608: }
609:
610: sub get_locks {
611: my $num=0;
612: my %texts=();
613: foreach my $lock (split(/\,/,$env{'session.locks'})) {
614: if ($lock=~/\w/) {
615: $num++;
616: $texts{$lock}=$env{'session.lock.'.$lock};
617: }
618: }
619: return ($num,%texts);
620: }
621:
622: sub remove_lock {
623: my ($id)=@_;
624: my $newlocks='';
625: foreach my $lock (split(/\,/,$env{'session.locks'})) {
626: if (($lock=~/\w/) && ($lock ne $id)) {
627: $newlocks.=','.$lock;
628: }
629: }
630: &appenv({'session.locks' => $newlocks});
631: &delenv('session.lock.'.$id);
632: }
633:
634: sub remove_all_locks {
635: my $activelocks=$env{'session.locks'};
636: foreach my $lock (split(/\,/,$env{'session.locks'})) {
637: if ($lock=~/\w/) {
638: &remove_lock($lock);
639: }
640: }
641: }
642:
643:
1.369 albertel 644: # ------------------------------------------ Find out current server userload
645: sub userload {
646: my $numusers=0;
647: {
648: opendir(LONIDS,$perlvar{'lonIDsDir'});
649: my $filename;
650: my $curtime=time;
651: while ($filename=readdir(LONIDS)) {
1.925 albertel 652: next if ($filename eq '.' || $filename eq '..');
653: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 654: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 655: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 656: }
657: closedir(LONIDS);
658: }
659: my $userloadpercent=0;
660: my $maxuserload=$perlvar{'lonUserLoadLim'};
661: if ($maxuserload) {
1.371 albertel 662: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 663: }
1.372 albertel 664: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 665: return $userloadpercent;
1.283 www 666: }
667:
668: # ------------------------------------------ Fight off request when overloaded
669:
670: sub overloaderror {
671: my ($r,$checkserver)=@_;
672: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
673: my $loadavg;
674: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 675: open(my $loadfile,'/proc/loadavg');
1.283 www 676: $loadavg=<$loadfile>;
677: $loadavg =~ s/\s.*//g;
1.285 matthew 678: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 679: close($loadfile);
1.283 www 680: } else {
681: $loadavg=&reply('load',$checkserver);
682: }
1.285 matthew 683: my $overload=$loadavg-100;
1.283 www 684: if ($overload>0) {
1.285 matthew 685: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 686: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 687: return 413;
1.283 www 688: }
689: return '';
1.5 www 690: }
1.1 albertel 691:
692: # ------------------------------ Find server with least workload from spare.tab
1.11 www 693:
1.1 albertel 694: sub spareserver {
1.670 albertel 695: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 696: my $spare_server;
1.370 albertel 697: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 698: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
699: : $userloadpercent;
700:
701: foreach my $try_server (@{ $spareid{'primary'} }) {
702: ($spare_server, $lowest_load) =
703: &compare_server_load($try_server, $spare_server, $lowest_load);
704: }
705:
706: my $found_server = ($spare_server ne '' && $lowest_load < 100);
707:
708: if (!$found_server) {
709: foreach my $try_server (@{ $spareid{'default'} }) {
710: ($spare_server, $lowest_load) =
711: &compare_server_load($try_server, $spare_server, $lowest_load);
712: }
713: }
714:
715: if (!$want_server_name) {
1.968 raeburn 716: my $protocol = 'http';
717: if ($protocol{$spare_server} eq 'https') {
718: $protocol = $protocol{$spare_server};
719: }
1.1001 raeburn 720: if (defined($spare_server)) {
721: my $hostname = &hostname($spare_server);
722: if (defined($hostname)) {
723: $spare_server = $protocol.'://'.$hostname;
724: }
725: }
1.784 albertel 726: }
727: return $spare_server;
728: }
729:
730: sub compare_server_load {
731: my ($try_server, $spare_server, $lowest_load) = @_;
732:
733: my $loadans = &reply('load', $try_server);
734: my $userloadans = &reply('userload',$try_server);
735:
736: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
737: next; #didn't get a number from the server
738: }
739:
740: my $load;
741: if ($loadans =~ /\d/) {
742: if ($userloadans =~ /\d/) {
743: #both are numbers, pick the bigger one
744: $load = ($loadans > $userloadans) ? $loadans
745: : $userloadans;
1.411 albertel 746: } else {
1.784 albertel 747: $load = $loadans;
1.411 albertel 748: }
1.784 albertel 749: } else {
750: $load = $userloadans;
751: }
752:
753: if (($load =~ /\d/) && ($load < $lowest_load)) {
754: $spare_server = $try_server;
755: $lowest_load = $load;
1.370 albertel 756: }
1.784 albertel 757: return ($spare_server,$lowest_load);
1.202 matthew 758: }
1.914 albertel 759:
760: # --------------------------- ask offload servers if user already has a session
761: sub find_existing_session {
762: my ($udom,$uname) = @_;
763: foreach my $try_server (@{ $spareid{'primary'} },
764: @{ $spareid{'default'} }) {
765: return $try_server if (&has_user_session($try_server, $udom, $uname));
766: }
767: return;
768: }
769:
770: # -------------------------------- ask if server already has a session for user
771: sub has_user_session {
772: my ($lonid,$udom,$uname) = @_;
773: my $result = &reply(join(':','userhassession',
774: map {&escape($_)} ($udom,$uname)),$lonid);
775: return 1 if ($result eq 'ok');
776:
777: return 0;
778: }
779:
1.202 matthew 780: # --------------------------------------------- Try to change a user's password
781:
782: sub changepass {
1.799 raeburn 783: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 784: $currentpass = &escape($currentpass);
785: $newpass = &escape($newpass);
1.1030 raeburn 786: my $lonhost = $perlvar{'lonHostID'};
787: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 788: $server);
789: if (! $answer) {
790: &logthis("No reply on password change request to $server ".
791: "by $uname in domain $udom.");
792: } elsif ($answer =~ "^ok") {
793: &logthis("$uname in $udom successfully changed their password ".
794: "on $server.");
795: } elsif ($answer =~ "^pwchange_failure") {
796: &logthis("$uname in $udom was unable to change their password ".
797: "on $server. The action was blocked by either lcpasswd ".
798: "or pwchange");
799: } elsif ($answer =~ "^non_authorized") {
800: &logthis("$uname in $udom did not get their password correct when ".
801: "attempting to change it on $server.");
802: } elsif ($answer =~ "^auth_mode_error") {
803: &logthis("$uname in $udom attempted to change their password despite ".
804: "not being locally or internally authenticated on $server.");
805: } elsif ($answer =~ "^unknown_user") {
806: &logthis("$uname in $udom attempted to change their password ".
807: "on $server but were unable to because $server is not ".
808: "their home server.");
809: } elsif ($answer =~ "^refused") {
810: &logthis("$server refused to change $uname in $udom password because ".
811: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 812: } elsif ($answer =~ "invalid_client") {
813: &logthis("$server refused to change $uname in $udom password because ".
814: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 815: }
816: return $answer;
1.1 albertel 817: }
818:
1.169 harris41 819: # ----------------------- Try to determine user's current authentication scheme
820:
821: sub queryauthenticate {
822: my ($uname,$udom)=@_;
1.456 albertel 823: my $uhome=&homeserver($uname,$udom);
824: if (!$uhome) {
825: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
826: return 'no_host';
827: }
828: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
829: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
830: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 831: }
1.456 albertel 832: return $answer;
1.169 harris41 833: }
834:
1.1 albertel 835: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 836:
1.1 albertel 837: sub authenticate {
1.952 raeburn 838: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 839: $upass=&escape($upass);
840: $uname= &LONCAPA::clean_username($uname);
1.836 www 841: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 842: my $newhome;
1.836 www 843: if ((!$uhome) || ($uhome eq 'no_host')) {
844: # Maybe the machine was offline and only re-appeared again recently?
845: &reconlonc();
846: # One more
1.952 raeburn 847: $uhome=&homeserver($uname,$udom,1);
848: if (($uhome eq 'no_host') && $checkdefauth) {
849: if (defined(&domain($udom,'primary'))) {
850: $newhome=&domain($udom,'primary');
851: }
852: if ($newhome ne '') {
853: $uhome = $newhome;
854: }
855: }
1.836 www 856: if ((!$uhome) || ($uhome eq 'no_host')) {
857: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 858: return 'no_host';
859: }
1.1 albertel 860: }
1.952 raeburn 861: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 862: if ($answer eq 'authorized') {
1.952 raeburn 863: if ($newhome) {
864: &logthis("User $uname at $udom authorized by $uhome, but needs account");
865: return 'no_account_on_host';
866: } else {
867: &logthis("User $uname at $udom authorized by $uhome");
868: return $uhome;
869: }
1.471 albertel 870: }
871: if ($answer eq 'non_authorized') {
872: &logthis("User $uname at $udom rejected by $uhome");
873: return 'no_host';
1.9 www 874: }
1.471 albertel 875: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 876: return 'no_host';
877: }
878:
879: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 880:
1.599 albertel 881: my %homecache;
1.1 albertel 882: sub homeserver {
1.230 stredwic 883: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 884: my $index="$uname:$udom";
1.426 albertel 885:
1.599 albertel 886: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 887:
888: my %servers = &get_servers($udom,'library');
889: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 890: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 891: exists($badServerCache{$tryserver}));
1.841 albertel 892:
893: my $answer=reply("home:$udom:$uname",$tryserver);
894: if ($answer eq 'found') {
895: delete($badServerCache{$tryserver});
896: return $homecache{$index}=$tryserver;
897: } elsif ($answer eq 'no_host') {
898: $badServerCache{$tryserver}=1;
899: }
1.1 albertel 900: }
901: return 'no_host';
1.70 www 902: }
903:
904: # ------------------------------------- Find the usernames behind a list of IDs
905:
906: sub idget {
907: my ($udom,@ids)=@_;
908: my %returnhash=();
909:
1.841 albertel 910: my %servers = &get_servers($udom,'library');
911: foreach my $tryserver (keys(%servers)) {
912: my $idlist=join('&',@ids);
913: $idlist=~tr/A-Z/a-z/;
914: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
915: my @answer=();
916: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
917: @answer=split(/\&/,$reply);
918: } ;
919: my $i;
920: for ($i=0;$i<=$#ids;$i++) {
921: if ($answer[$i]) {
922: $returnhash{$ids[$i]}=$answer[$i];
923: }
924: }
925: }
1.70 www 926: return %returnhash;
927: }
928:
929: # ------------------------------------- Find the IDs behind a list of usernames
930:
931: sub idrget {
932: my ($udom,@unames)=@_;
933: my %returnhash=();
1.800 albertel 934: foreach my $uname (@unames) {
935: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 936: }
1.70 www 937: return %returnhash;
938: }
939:
940: # ------------------------------- Store away a list of names and associated IDs
941:
942: sub idput {
943: my ($udom,%ids)=@_;
944: my %servers=();
1.800 albertel 945: foreach my $uname (keys(%ids)) {
946: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
947: my $uhom=&homeserver($uname,$udom);
1.70 www 948: if ($uhom ne 'no_host') {
1.800 albertel 949: my $id=&escape($ids{$uname});
1.70 www 950: $id=~tr/A-Z/a-z/;
1.800 albertel 951: my $esc_unam=&escape($uname);
1.70 www 952: if ($servers{$uhom}) {
1.800 albertel 953: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 954: } else {
1.800 albertel 955: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 956: }
957: }
1.191 harris41 958: }
1.800 albertel 959: foreach my $server (keys(%servers)) {
960: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 961: }
1.344 www 962: }
963:
1.1023 raeburn 964: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 965: sub dump_dom {
1.1023 raeburn 966: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 967: if (!$udom) {
968: $udom=$env{'user.domain'};
969: }
970: my %returnhash;
1.1023 raeburn 971: if ($udom) {
972: my $uname = &get_domainconfiguser($udom);
973: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 974: }
975: return %returnhash;
976: }
977:
1.1023 raeburn 978: # ------------------------------------------ get items from domain db files
1.806 raeburn 979:
980: sub get_dom {
1.860 raeburn 981: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 982: my $items='';
983: foreach my $item (@$storearr) {
984: $items.=&escape($item).'&';
985: }
986: $items=~s/\&$//;
1.860 raeburn 987: if (!$udom) {
988: $udom=$env{'user.domain'};
989: if (defined(&domain($udom,'primary'))) {
990: $uhome=&domain($udom,'primary');
991: } else {
1.874 albertel 992: undef($uhome);
1.860 raeburn 993: }
994: } else {
995: if (!$uhome) {
996: if (defined(&domain($udom,'primary'))) {
997: $uhome=&domain($udom,'primary');
998: }
999: }
1000: }
1001: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1002: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1003: my %returnhash;
1.875 albertel 1004: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1005: return %returnhash;
1006: }
1.806 raeburn 1007: my @pairs=split(/\&/,$rep);
1008: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1009: return @pairs;
1010: }
1011: my $i=0;
1012: foreach my $item (@$storearr) {
1013: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1014: $i++;
1015: }
1016: return %returnhash;
1017: } else {
1.880 banghart 1018: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1019: }
1020: }
1021:
1022: # -------------------------------------------- put items in domain db files
1023:
1024: sub put_dom {
1.860 raeburn 1025: my ($namespace,$storehash,$udom,$uhome)=@_;
1026: if (!$udom) {
1027: $udom=$env{'user.domain'};
1028: if (defined(&domain($udom,'primary'))) {
1029: $uhome=&domain($udom,'primary');
1030: } else {
1.874 albertel 1031: undef($uhome);
1.860 raeburn 1032: }
1033: } else {
1034: if (!$uhome) {
1035: if (defined(&domain($udom,'primary'))) {
1036: $uhome=&domain($udom,'primary');
1037: }
1038: }
1039: }
1040: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1041: my $items='';
1042: foreach my $item (keys(%$storehash)) {
1043: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1044: }
1045: $items=~s/\&$//;
1046: return &reply("putdom:$udom:$namespace:$items",$uhome);
1047: } else {
1.860 raeburn 1048: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1049: }
1050: }
1051:
1.1023 raeburn 1052: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1053: sub newput_dom {
1.1023 raeburn 1054: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1055: my $result;
1056: if (!$udom) {
1057: $udom=$env{'user.domain'};
1058: }
1.1023 raeburn 1059: if ($udom) {
1060: my $uname = &get_domainconfiguser($udom);
1061: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1062: }
1063: return $result;
1064: }
1065:
1.1023 raeburn 1066: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1067: sub del_dom {
1.1023 raeburn 1068: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1069: if (ref($storearr) eq 'ARRAY') {
1070: if (!$udom) {
1071: $udom=$env{'user.domain'};
1072: }
1.1023 raeburn 1073: if ($udom) {
1074: my $uname = &get_domainconfiguser($udom);
1075: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1076: }
1077: }
1078: }
1079:
1.1023 raeburn 1080: # ----------------------------------construct domainconfig user for a domain
1081: sub get_domainconfiguser {
1082: my ($udom) = @_;
1083: return $udom.'-domainconfig';
1084: }
1085:
1.837 raeburn 1086: sub retrieve_inst_usertypes {
1087: my ($udom) = @_;
1088: my (%returnhash,@order);
1.989 raeburn 1089: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1090: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1091: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1092: %returnhash = %{$domdefs{'inststatustypes'}};
1093: @order = @{$domdefs{'inststatusorder'}};
1094: } else {
1095: if (defined(&domain($udom,'primary'))) {
1096: my $uhome=&domain($udom,'primary');
1097: my $rep=&reply("inst_usertypes:$udom",$uhome);
1098: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1099: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1100: return (\%returnhash,\@order);
1101: }
1102: my ($hashitems,$orderitems) = split(/:/,$rep);
1103: my @pairs=split(/\&/,$hashitems);
1104: foreach my $item (@pairs) {
1105: my ($key,$value)=split(/=/,$item,2);
1106: $key = &unescape($key);
1107: next if ($key =~ /^error: 2 /);
1108: $returnhash{$key}=&thaw_unescape($value);
1109: }
1110: my @esc_order = split(/\&/,$orderitems);
1111: foreach my $item (@esc_order) {
1112: push(@order,&unescape($item));
1113: }
1114: } else {
1115: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1116: }
1117: }
1118: return (\%returnhash,\@order);
1119: }
1120:
1.868 raeburn 1121: sub is_domainimage {
1122: my ($url) = @_;
1123: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1124: if (&domain($1) ne '') {
1125: return '1';
1126: }
1127: }
1128: return;
1129: }
1130:
1.899 raeburn 1131: sub inst_directory_query {
1132: my ($srch) = @_;
1133: my $udom = $srch->{'srchdomain'};
1134: my %results;
1135: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1136: my $outcome;
1.899 raeburn 1137: if ($homeserver ne '') {
1.904 albertel 1138: my $queryid=&reply("querysend:instdirsearch:".
1139: &escape($srch->{'srchby'}).':'.
1140: &escape($srch->{'srchterm'}).':'.
1141: &escape($srch->{'srchtype'}),$homeserver);
1142: my $host=&hostname($homeserver);
1143: if ($queryid !~/^\Q$host\E\_/) {
1144: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1145: return;
1146: }
1147: my $response = &get_query_reply($queryid);
1148: my $maxtries = 5;
1149: my $tries = 1;
1150: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1151: $response = &get_query_reply($queryid);
1152: $tries ++;
1153: }
1154:
1155: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1156: if ($response eq 'unavailable') {
1157: $outcome = $response;
1158: } else {
1159: $outcome = 'ok';
1160: my @matches = split(/\n/,$response);
1161: foreach my $match (@matches) {
1162: my ($key,$value) = split(/=/,$match);
1163: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1164: }
1.899 raeburn 1165: }
1166: }
1167: }
1.909 raeburn 1168: return ($outcome,%results);
1.899 raeburn 1169: }
1170:
1171: sub usersearch {
1172: my ($srch) = @_;
1173: my $dom = $srch->{'srchdomain'};
1174: my %results;
1175: my %libserv = &all_library();
1176: my $query = 'usersearch';
1177: foreach my $tryserver (keys(%libserv)) {
1178: if (&host_domain($tryserver) eq $dom) {
1179: my $host=&hostname($tryserver);
1180: my $queryid=
1.911 raeburn 1181: &reply("querysend:".&escape($query).':'.
1182: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1183: &escape($srch->{'srchtype'}).':'.
1184: &escape($srch->{'srchterm'}),$tryserver);
1185: if ($queryid !~/^\Q$host\E\_/) {
1186: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1187: next;
1.899 raeburn 1188: }
1189: my $reply = &get_query_reply($queryid);
1190: my $maxtries = 1;
1191: my $tries = 1;
1192: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1193: $reply = &get_query_reply($queryid);
1194: $tries ++;
1195: }
1196: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1197: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1198: } else {
1.911 raeburn 1199: my @matches;
1200: if ($reply =~ /\n/) {
1201: @matches = split(/\n/,$reply);
1202: } else {
1203: @matches = split(/\&/,$reply);
1204: }
1.899 raeburn 1205: foreach my $match (@matches) {
1206: my ($uname,$udom,%userhash);
1.911 raeburn 1207: foreach my $entry (split(/:/,$match)) {
1208: my ($key,$value) =
1209: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1210: $userhash{$key} = $value;
1211: if ($key eq 'username') {
1212: $uname = $value;
1213: } elsif ($key eq 'domain') {
1214: $udom = $value;
1.911 raeburn 1215: }
1.899 raeburn 1216: }
1217: $results{$uname.':'.$udom} = \%userhash;
1218: }
1219: }
1220: }
1221: }
1222: return %results;
1223: }
1224:
1.912 raeburn 1225: sub get_instuser {
1226: my ($udom,$uname,$id) = @_;
1227: my $homeserver = &domain($udom,'primary');
1228: my ($outcome,%results);
1229: if ($homeserver ne '') {
1230: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1231: &escape($id).':'.&escape($udom),$homeserver);
1232: my $host=&hostname($homeserver);
1233: if ($queryid !~/^\Q$host\E\_/) {
1234: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1235: return;
1236: }
1237: my $response = &get_query_reply($queryid);
1238: my $maxtries = 5;
1239: my $tries = 1;
1240: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1241: $response = &get_query_reply($queryid);
1242: $tries ++;
1243: }
1244: if (!&error($response) && $response ne 'refused') {
1245: if ($response eq 'unavailable') {
1246: $outcome = $response;
1247: } else {
1248: $outcome = 'ok';
1249: my @matches = split(/\n/,$response);
1250: foreach my $match (@matches) {
1251: my ($key,$value) = split(/=/,$match);
1252: $results{&unescape($key)} = &thaw_unescape($value);
1253: }
1254: }
1255: }
1256: }
1257: my %userinfo;
1258: if (ref($results{$uname}) eq 'HASH') {
1259: %userinfo = %{$results{$uname}};
1260: }
1261: return ($outcome,%userinfo);
1262: }
1263:
1264: sub inst_rulecheck {
1.923 raeburn 1265: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1266: my %returnhash;
1267: if ($udom ne '') {
1268: if (ref($rules) eq 'ARRAY') {
1269: @{$rules} = map {&escape($_);} (@{$rules});
1270: my $rulestr = join(':',@{$rules});
1271: my $homeserver=&domain($udom,'primary');
1272: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1273: my $response;
1274: if ($item eq 'username') {
1275: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1276: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1277: $homeserver));
1.923 raeburn 1278: } elsif ($item eq 'id') {
1279: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1280: ':'.&escape($id).':'.$rulestr,
1281: $homeserver));
1.945 raeburn 1282: } elsif ($item eq 'selfcreate') {
1283: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1284: &escape($udom).':'.&escape($uname).
1285: ':'.$rulestr,$homeserver));
1.923 raeburn 1286: }
1.912 raeburn 1287: if ($response ne 'refused') {
1288: my @pairs=split(/\&/,$response);
1289: foreach my $item (@pairs) {
1290: my ($key,$value)=split(/=/,$item,2);
1291: $key = &unescape($key);
1292: next if ($key =~ /^error: 2 /);
1293: $returnhash{$key}=&thaw_unescape($value);
1294: }
1295: }
1296: }
1297: }
1298: }
1299: return %returnhash;
1300: }
1301:
1302: sub inst_userrules {
1.923 raeburn 1303: my ($udom,$check) = @_;
1.912 raeburn 1304: my (%ruleshash,@ruleorder);
1305: if ($udom ne '') {
1306: my $homeserver=&domain($udom,'primary');
1307: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1308: my $response;
1309: if ($check eq 'id') {
1310: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1311: $homeserver);
1.943 raeburn 1312: } elsif ($check eq 'email') {
1313: $response=&reply('instemailrules:'.&escape($udom),
1314: $homeserver);
1.923 raeburn 1315: } else {
1316: $response=&reply('instuserrules:'.&escape($udom),
1317: $homeserver);
1318: }
1.912 raeburn 1319: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1320: ($response ne 'unknown_cmd') &&
1.912 raeburn 1321: ($response ne 'no_such_host')) {
1322: my ($hashitems,$orderitems) = split(/:/,$response);
1323: my @pairs=split(/\&/,$hashitems);
1324: foreach my $item (@pairs) {
1325: my ($key,$value)=split(/=/,$item,2);
1326: $key = &unescape($key);
1327: next if ($key =~ /^error: 2 /);
1328: $ruleshash{$key}=&thaw_unescape($value);
1329: }
1330: my @esc_order = split(/\&/,$orderitems);
1331: foreach my $item (@esc_order) {
1332: push(@ruleorder,&unescape($item));
1333: }
1334: }
1335: }
1336: }
1337: return (\%ruleshash,\@ruleorder);
1338: }
1339:
1.976 raeburn 1340: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1341:
1342: sub get_domain_defaults {
1343: my ($domain) = @_;
1344: my $cachetime = 60*60*24;
1345: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1346: if (defined($cached)) {
1347: if (ref($result) eq 'HASH') {
1348: return %{$result};
1349: }
1350: }
1351: my %domdefaults;
1352: my %domconfig =
1.989 raeburn 1353: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1354: 'requestcourses','inststatus',
1355: 'coursedefaults'],$domain);
1.943 raeburn 1356: if (ref($domconfig{'defaults'}) eq 'HASH') {
1357: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1358: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1359: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1360: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1361: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1362: } else {
1363: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1364: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1365: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1366: }
1.976 raeburn 1367: if (ref($domconfig{'quotas'}) eq 'HASH') {
1368: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1369: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1370: } else {
1371: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1372: }
1373: my @usertools = ('aboutme','blog','portfolio');
1374: foreach my $item (@usertools) {
1375: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1376: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1377: }
1378: }
1379: }
1.985 raeburn 1380: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1381: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1382: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1383: }
1384: }
1.989 raeburn 1385: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1386: foreach my $item ('inststatustypes','inststatusorder') {
1387: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1388: }
1389: }
1.1047 raeburn 1390: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1391: foreach my $item ('canuse_pdfforms') {
1392: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1393: }
1394: }
1.943 raeburn 1395: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1396: $cachetime);
1397: return %domdefaults;
1398: }
1399:
1.344 www 1400: # --------------------------------------------------- Assign a key to a student
1401:
1402: sub assign_access_key {
1.364 www 1403: #
1404: # a valid key looks like uname:udom#comments
1405: # comments are being appended
1406: #
1.498 www 1407: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1408: $kdom=
1.620 albertel 1409: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1410: $knum=
1.620 albertel 1411: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1412: $cdom=
1.620 albertel 1413: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1414: $cnum=
1.620 albertel 1415: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1416: $udom=$env{'user.name'} unless (defined($udom));
1417: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1418: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1419: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1420: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1421: # assigned to this person
1422: # - this should not happen,
1.345 www 1423: # unless something went wrong
1424: # the first time around
1425: # ready to assign
1.364 www 1426: $logentry=$1.'; '.$logentry;
1.496 www 1427: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1428: $kdom,$knum) eq 'ok') {
1.345 www 1429: # key now belongs to user
1.346 www 1430: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1431: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1432: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1433: return 'ok';
1434: } else {
1435: return
1436: 'error: Count not permanently assign key, will need to be re-entered later.';
1437: }
1438: } else {
1439: return 'error: Could not assign key, try again later.';
1440: }
1.364 www 1441: } elsif (!$existing{$ckey}) {
1.345 www 1442: # the key does not exist
1443: return 'error: The key does not exist';
1444: } else {
1445: # the key is somebody else's
1446: return 'error: The key is already in use';
1447: }
1.344 www 1448: }
1449:
1.364 www 1450: # ------------------------------------------ put an additional comment on a key
1451:
1452: sub comment_access_key {
1453: #
1454: # a valid key looks like uname:udom#comments
1455: # comments are being appended
1456: #
1457: my ($ckey,$cdom,$cnum,$logentry)=@_;
1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1462: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1463: if ($existing{$ckey}) {
1464: $existing{$ckey}.='; '.$logentry;
1465: # ready to assign
1.367 www 1466: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1467: $cdom,$cnum) eq 'ok') {
1468: return 'ok';
1469: } else {
1470: return 'error: Count not store comment.';
1471: }
1472: } else {
1473: # the key does not exist
1474: return 'error: The key does not exist';
1475: }
1476: }
1477:
1.344 www 1478: # ------------------------------------------------------ Generate a set of keys
1479:
1480: sub generate_access_keys {
1.364 www 1481: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1482: $cdom=
1.620 albertel 1483: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1484: $cnum=
1.620 albertel 1485: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1486: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1487: unless (($cdom) && ($cnum)) { return 0; }
1488: if ($number>10000) { return 0; }
1489: sleep(2); # make sure don't get same seed twice
1490: srand(time()^($$+($$<<15))); # from "Programming Perl"
1491: my $total=0;
1492: for (my $i=1;$i<=$number;$i++) {
1493: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1494: sprintf("%lx",int(100000*rand)).'-'.
1495: sprintf("%lx",int(100000*rand));
1496: $newkey=~s/1/g/g; # folks mix up 1 and l
1497: $newkey=~s/0/h/g; # and also 0 and O
1498: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1499: if ($existing{$newkey}) {
1500: $i--;
1501: } else {
1.364 www 1502: if (&put('accesskeys',
1503: { $newkey => '# generated '.localtime().
1.620 albertel 1504: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1505: '; '.$logentry },
1506: $cdom,$cnum) eq 'ok') {
1.344 www 1507: $total++;
1508: }
1509: }
1510: }
1.620 albertel 1511: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1512: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1513: return $total;
1514: }
1515:
1516: # ------------------------------------------------------- Validate an accesskey
1517:
1518: sub validate_access_key {
1519: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1520: $cdom=
1.620 albertel 1521: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1522: $cnum=
1.620 albertel 1523: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1524: $udom=$env{'user.domain'} unless (defined($udom));
1525: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1526: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1527: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1528: }
1529:
1530: # ------------------------------------- Find the section of student in a course
1.652 albertel 1531: sub devalidate_getsection_cache {
1532: my ($udom,$unam,$courseid)=@_;
1533: my $hashid="$udom:$unam:$courseid";
1534: &devalidate_cache_new('getsection',$hashid);
1535: }
1.298 matthew 1536:
1.815 albertel 1537: sub courseid_to_courseurl {
1538: my ($courseid) = @_;
1539: #already url style courseid
1540: return $courseid if ($courseid =~ m{^/});
1541:
1542: if (exists($env{'course.'.$courseid.'.num'})) {
1543: my $cnum = $env{'course.'.$courseid.'.num'};
1544: my $cdom = $env{'course.'.$courseid.'.domain'};
1545: return "/$cdom/$cnum";
1546: }
1547:
1548: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1549: if (exists($courseinfo{'num'})) {
1550: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1551: }
1552:
1553: return undef;
1554: }
1555:
1.298 matthew 1556: sub getsection {
1557: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1558: my $cachetime=1800;
1.551 albertel 1559:
1560: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1561: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1562: if (defined($cached)) { return $result; }
1563:
1.298 matthew 1564: my %Pending;
1565: my %Expired;
1566: #
1567: # Each role can either have not started yet (pending), be active,
1568: # or have expired.
1569: #
1570: # If there is an active role, we are done.
1571: #
1572: # If there is more than one role which has not started yet,
1573: # choose the one which will start sooner
1574: # If there is one role which has not started yet, return it.
1575: #
1576: # If there is more than one expired role, choose the one which ended last.
1577: # If there is a role which has expired, return it.
1578: #
1.815 albertel 1579: $courseid = &courseid_to_courseurl($courseid);
1.1056.2.9 raeburn 1580: my $extra = &freeze_escape({'skipcheck' => 1});
1581: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1582: foreach my $key (keys(%roleshash)) {
1.479 albertel 1583: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1584: my $section=$1;
1585: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1586: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1587: my $now=time;
1.548 albertel 1588: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1589: $Expired{$end}=$section;
1590: next;
1591: }
1.548 albertel 1592: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1593: $Pending{$start}=$section;
1594: next;
1595: }
1.599 albertel 1596: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1597: }
1598: #
1599: # Presumedly there will be few matching roles from the above
1600: # loop and the sorting time will be negligible.
1601: if (scalar(keys(%Pending))) {
1602: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1603: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1604: }
1605: if (scalar(keys(%Expired))) {
1606: my @sorted = sort {$a <=> $b} keys(%Expired);
1607: my $time = pop(@sorted);
1.599 albertel 1608: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1609: }
1.599 albertel 1610: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1611: }
1.70 www 1612:
1.599 albertel 1613: sub save_cache {
1614: &purge_remembered();
1.722 albertel 1615: #&Apache::loncommon::validate_page();
1.620 albertel 1616: undef(%env);
1.780 albertel 1617: undef($env_loaded);
1.599 albertel 1618: }
1.452 albertel 1619:
1.599 albertel 1620: my $to_remember=-1;
1621: my %remembered;
1622: my %accessed;
1623: my $kicks=0;
1624: my $hits=0;
1.849 albertel 1625: sub make_key {
1626: my ($name,$id) = @_;
1.872 albertel 1627: if (length($id) > 65
1628: && length(&escape($id)) > 200) {
1629: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1630: }
1.849 albertel 1631: return &escape($name.':'.$id);
1632: }
1633:
1.599 albertel 1634: sub devalidate_cache_new {
1635: my ($name,$id,$debug) = @_;
1636: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1637: $id=&make_key($name,$id);
1.599 albertel 1638: $memcache->delete($id);
1639: delete($remembered{$id});
1640: delete($accessed{$id});
1641: }
1642:
1643: sub is_cached_new {
1644: my ($name,$id,$debug) = @_;
1.849 albertel 1645: $id=&make_key($name,$id);
1.599 albertel 1646: if (exists($remembered{$id})) {
1647: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1648: $accessed{$id}=[&gettimeofday()];
1649: $hits++;
1650: return ($remembered{$id},1);
1651: }
1652: my $value = $memcache->get($id);
1653: if (!(defined($value))) {
1654: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1655: return (undef,undef);
1.416 albertel 1656: }
1.599 albertel 1657: if ($value eq '__undef__') {
1658: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1659: $value=undef;
1660: }
1661: &make_room($id,$value,$debug);
1662: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1663: return ($value,1);
1664: }
1665:
1666: sub do_cache_new {
1667: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1668: $id=&make_key($name,$id);
1.599 albertel 1669: my $setvalue=$value;
1670: if (!defined($setvalue)) {
1671: $setvalue='__undef__';
1672: }
1.623 albertel 1673: if (!defined($time) ) {
1674: $time=600;
1675: }
1.599 albertel 1676: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1677: my $result = $memcache->set($id,$setvalue,$time);
1678: if (! $result) {
1.872 albertel 1679: &logthis("caching of id -> $id failed");
1.910 albertel 1680: $memcache->disconnect_all();
1.872 albertel 1681: }
1.600 albertel 1682: # need to make a copy of $value
1.919 albertel 1683: &make_room($id,$value,$debug);
1.599 albertel 1684: return $value;
1685: }
1686:
1687: sub make_room {
1688: my ($id,$value,$debug)=@_;
1.919 albertel 1689:
1690: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1691: : $value;
1.599 albertel 1692: if ($to_remember<0) { return; }
1693: $accessed{$id}=[&gettimeofday()];
1694: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1695: my $to_kick;
1696: my $max_time=0;
1697: foreach my $other (keys(%accessed)) {
1698: if (&tv_interval($accessed{$other}) > $max_time) {
1699: $to_kick=$other;
1700: $max_time=&tv_interval($accessed{$other});
1701: }
1702: }
1703: delete($remembered{$to_kick});
1704: delete($accessed{$to_kick});
1705: $kicks++;
1706: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1707: return;
1708: }
1709:
1.599 albertel 1710: sub purge_remembered {
1.604 albertel 1711: #&logthis("Tossing ".scalar(keys(%remembered)));
1712: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1713: undef(%remembered);
1714: undef(%accessed);
1.428 albertel 1715: }
1.70 www 1716: # ------------------------------------- Read an entry from a user's environment
1717:
1718: sub userenvironment {
1719: my ($udom,$unam,@what)=@_;
1.976 raeburn 1720: my $items;
1721: foreach my $item (@what) {
1722: $items.=&escape($item).'&';
1723: }
1724: $items=~s/\&$//;
1.70 www 1725: my %returnhash=();
1.1009 raeburn 1726: my $uhome = &homeserver($unam,$udom);
1727: unless ($uhome eq 'no_host') {
1728: my @answer=split(/\&/,
1729: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1730: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1731: return %returnhash;
1732: }
1.1009 raeburn 1733: my $i;
1734: for ($i=0;$i<=$#what;$i++) {
1735: $returnhash{$what[$i]}=&unescape($answer[$i]);
1736: }
1.70 www 1737: }
1738: return %returnhash;
1.1 albertel 1739: }
1740:
1.617 albertel 1741: # ---------------------------------------------------------- Get a studentphoto
1742: sub studentphoto {
1743: my ($udom,$unam,$ext) = @_;
1744: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1745: if (defined($env{'request.course.id'})) {
1.708 raeburn 1746: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1747: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1748: return(&retrievestudentphoto($udom,$unam,$ext));
1749: } else {
1750: my ($result,$perm_reqd)=
1.707 albertel 1751: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1752: if ($result eq 'ok') {
1753: if (!($perm_reqd eq 'yes')) {
1754: return(&retrievestudentphoto($udom,$unam,$ext));
1755: }
1756: }
1757: }
1758: }
1759: } else {
1760: my ($result,$perm_reqd) =
1.707 albertel 1761: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1762: if ($result eq 'ok') {
1763: if (!($perm_reqd eq 'yes')) {
1764: return(&retrievestudentphoto($udom,$unam,$ext));
1765: }
1766: }
1767: }
1768: return '/adm/lonKaputt/lonlogo_broken.gif';
1769: }
1770:
1771: sub retrievestudentphoto {
1772: my ($udom,$unam,$ext,$type) = @_;
1773: my $home=&Apache::lonnet::homeserver($unam,$udom);
1774: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1775: if ($ret eq 'ok') {
1776: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1777: if ($type eq 'thumbnail') {
1778: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1779: }
1780: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1781: return $tokenurl;
1782: } else {
1783: if ($type eq 'thumbnail') {
1784: return '/adm/lonKaputt/genericstudent_tn.gif';
1785: } else {
1786: return '/adm/lonKaputt/lonlogo_broken.gif';
1787: }
1.617 albertel 1788: }
1789: }
1790:
1.263 www 1791: # -------------------------------------------------------------------- New chat
1792:
1793: sub chatsend {
1.724 raeburn 1794: my ($newentry,$anon,$group)=@_;
1.620 albertel 1795: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1796: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1797: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1798: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1799: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1800: &escape($newentry)).':'.$group,$chome);
1.292 www 1801: }
1802:
1803: # ------------------------------------------ Find current version of a resource
1804:
1805: sub getversion {
1806: my $fname=&clutter(shift);
1807: unless ($fname=~/^\/res\//) { return -1; }
1808: return ¤tversion(&filelocation('',$fname));
1809: }
1810:
1811: sub currentversion {
1812: my $fname=shift;
1.599 albertel 1813: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1814: if (defined($cached)) { return $result; }
1.292 www 1815: my $author=$fname;
1816: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1817: my ($udom,$uname)=split(/\//,$author);
1818: my $home=homeserver($uname,$udom);
1819: if ($home eq 'no_host') {
1820: return -1;
1821: }
1822: my $answer=reply("currentversion:$fname",$home);
1823: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1824: return -1;
1825: }
1.599 albertel 1826: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1827: }
1828:
1.1 albertel 1829: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1830:
1.1 albertel 1831: sub subscribe {
1832: my $fname=shift;
1.761 raeburn 1833: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1834: $fname=~s/[\n\r]//g;
1.1 albertel 1835: my $author=$fname;
1836: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1837: my ($udom,$uname)=split(/\//,$author);
1838: my $home=homeserver($uname,$udom);
1.335 albertel 1839: if ($home eq 'no_host') {
1840: return 'not_found';
1.1 albertel 1841: }
1842: my $answer=reply("sub:$fname",$home);
1.64 www 1843: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1844: $answer.=' by '.$home;
1845: }
1.1 albertel 1846: return $answer;
1847: }
1848:
1.8 www 1849: # -------------------------------------------------------------- Replicate file
1850:
1851: sub repcopy {
1852: my $filename=shift;
1.23 www 1853: $filename=~s/\/+/\//g;
1.607 raeburn 1854: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1855: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1856: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1857: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1858: return &repcopy_userfile($filename);
1859: }
1.532 albertel 1860: $filename=~s/[\n\r]//g;
1.8 www 1861: my $transname="$filename.in.transfer";
1.828 www 1862: # FIXME: this should flock
1.607 raeburn 1863: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1864: my $remoteurl=subscribe($filename);
1.64 www 1865: if ($remoteurl =~ /^con_lost by/) {
1866: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1867: return 'unavailable';
1.8 www 1868: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1869: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1870: return 'not_found';
1.64 www 1871: } elsif ($remoteurl =~ /^rejected by/) {
1872: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1873: return 'forbidden';
1.20 www 1874: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1875: return 'ok';
1.8 www 1876: } else {
1.290 www 1877: my $author=$filename;
1878: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1879: my ($udom,$uname)=split(/\//,$author);
1880: my $home=homeserver($uname,$udom);
1881: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1882: my @parts=split(/\//,$filename);
1883: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1884: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1885: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1886: return 'bad_request';
1.8 www 1887: }
1888: my $count;
1889: for ($count=5;$count<$#parts;$count++) {
1890: $path.="/$parts[$count]";
1891: if ((-e $path)!=1) {
1892: mkdir($path,0777);
1893: }
1894: }
1895: my $ua=new LWP::UserAgent;
1896: my $request=new HTTP::Request('GET',"$remoteurl");
1897: my $response=$ua->request($request,$transname);
1898: if ($response->is_error()) {
1899: unlink($transname);
1900: my $message=$response->status_line;
1.672 albertel 1901: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1902: ." LWP get: $message: $filename</font>");
1.607 raeburn 1903: return 'unavailable';
1.8 www 1904: } else {
1.16 www 1905: if ($remoteurl!~/\.meta$/) {
1906: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1907: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1908: if ($mresponse->is_error()) {
1909: unlink($filename.'.meta');
1910: &logthis(
1.672 albertel 1911: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1912: }
1913: }
1.8 www 1914: rename($transname,$filename);
1.607 raeburn 1915: return 'ok';
1.8 www 1916: }
1.290 www 1917: }
1.8 www 1918: }
1.330 www 1919: }
1920:
1921: # ------------------------------------------------ Get server side include body
1922: sub ssi_body {
1.381 albertel 1923: my ($filelink,%form)=@_;
1.606 matthew 1924: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1925: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1926: }
1.953 www 1927: my $output='';
1928: my $response;
1.980 raeburn 1929: if ($filelink=~/^https?\:/) {
1.954 raeburn 1930: ($output,$response)=&externalssi($filelink);
1.953 www 1931: } else {
1.1004 droeschl 1932: $filelink .= $filelink=~/\?/ ? '&' : '?';
1933: $filelink .= 'inhibitmenu=yes';
1.953 www 1934: ($output,$response)=&ssi($filelink,%form);
1935: }
1.778 albertel 1936: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1937: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1938: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1939: if (wantarray) {
1940: return ($output, $response);
1941: } else {
1942: return $output;
1943: }
1.8 www 1944: }
1945:
1.15 www 1946: # --------------------------------------------------------- Server Side Include
1947:
1.782 albertel 1948: sub absolute_url {
1949: my ($host_name) = @_;
1950: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1951: if ($host_name eq '') {
1952: $host_name = $ENV{'SERVER_NAME'};
1953: }
1954: return $protocol.$host_name;
1955: }
1956:
1.942 foxr 1957: #
1958: # Server side include.
1959: # Parameters:
1960: # fn Possibly encrypted resource name/id.
1961: # form Hash that describes how the rendering should be done
1962: # and other things.
1.944 foxr 1963: # Returns:
1.950 raeburn 1964: # Scalar context: The content of the response.
1965: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1966: #
1.15 www 1967: sub ssi {
1968:
1.944 foxr 1969: my ($fn,%form)=@_;
1.15 www 1970: my $ua=new LWP::UserAgent;
1.23 www 1971: my $request;
1.711 albertel 1972:
1973: $form{'no_update_last_known'}=1;
1.895 albertel 1974: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1975: if (%form) {
1.782 albertel 1976: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1977: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1978: } else {
1.782 albertel 1979: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1980: }
1981:
1.15 www 1982: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1983: my $response=$ua->request($request);
1984:
1.944 foxr 1985: if (wantarray) {
1986: return ($response->content, $response);
1987: } else {
1988: return $response->content;
1.942 foxr 1989: }
1.324 www 1990: }
1991:
1992: sub externalssi {
1993: my ($url)=@_;
1994: my $ua=new LWP::UserAgent;
1995: my $request=new HTTP::Request('GET',$url);
1996: my $response=$ua->request($request);
1.954 raeburn 1997: if (wantarray) {
1998: return ($response->content, $response);
1999: } else {
2000: return $response->content;
2001: }
1.15 www 2002: }
1.254 www 2003:
1.492 albertel 2004: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2005:
2006: sub allowuploaded {
2007: my ($srcurl,$url)=@_;
2008: $url=&clutter(&declutter($url));
2009: my $dir=$url;
2010: $dir=~s/\/[^\/]+$//;
2011: my %httpref=();
2012: my $httpurl=&hreflocation('',$url);
2013: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2014: &Apache::lonnet::appenv(\%httpref);
1.254 www 2015: }
1.477 raeburn 2016:
1.478 albertel 2017: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2018: # input: action, courseID, current domain, intended
1.637 raeburn 2019: # path to file, source of file, instruction to parse file for objects,
2020: # ref to hash for embedded objects,
2021: # ref to hash for codebase of java objects.
2022: #
1.485 raeburn 2023: # output: url to file (if action was uploaddoc),
2024: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2025: #
1.478 albertel 2026: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2027: # course.
1.477 raeburn 2028: #
1.478 albertel 2029: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2030: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2031: # course's home server.
1.477 raeburn 2032: #
1.478 albertel 2033: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2034: # be copied from $source (current location) to
2035: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2036: # and will then be copied to
2037: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2038: # course's home server.
1.485 raeburn 2039: #
1.481 raeburn 2040: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2041: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2042: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2043: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2044: # in course's home server.
1.637 raeburn 2045: #
1.477 raeburn 2046:
2047: sub process_coursefile {
1.638 albertel 2048: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2049: my $fetchresult;
1.638 albertel 2050: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2051: if ($action eq 'propagate') {
1.638 albertel 2052: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2053: $home);
1.481 raeburn 2054: } else {
1.477 raeburn 2055: my $fpath = '';
2056: my $fname = $file;
1.478 albertel 2057: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2058: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2059: my $filepath = &build_filepath($fpath);
1.481 raeburn 2060: if ($action eq 'copy') {
2061: if ($source eq '') {
2062: $fetchresult = 'no source file';
2063: return $fetchresult;
2064: } else {
2065: my $destination = $filepath.'/'.$fname;
2066: rename($source,$destination);
2067: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2068: $home);
1.481 raeburn 2069: }
2070: } elsif ($action eq 'uploaddoc') {
2071: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2072: print $fh $env{'form.'.$source};
1.481 raeburn 2073: close($fh);
1.637 raeburn 2074: if ($parser eq 'parse') {
1.1024 raeburn 2075: my $mm = new File::MMagic;
2076: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2077: if ($mime_type eq 'text/html') {
2078: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2079: unless ($parse_result eq 'ok') {
2080: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2081: }
1.637 raeburn 2082: }
2083: }
1.477 raeburn 2084: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2085: $home);
1.481 raeburn 2086: if ($fetchresult eq 'ok') {
2087: return '/uploaded/'.$fpath.'/'.$fname;
2088: } else {
2089: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2090: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2091: return '/adm/notfound.html';
2092: }
1.477 raeburn 2093: }
2094: }
1.485 raeburn 2095: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2096: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2097: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2098: }
2099: return $fetchresult;
2100: }
2101:
1.637 raeburn 2102: sub build_filepath {
2103: my ($fpath) = @_;
2104: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2105: unless ($fpath eq '') {
2106: my @parts=split('/',$fpath);
2107: foreach my $part (@parts) {
2108: $filepath.= '/'.$part;
2109: if ((-e $filepath)!=1) {
2110: mkdir($filepath,0777);
2111: }
2112: }
2113: }
2114: return $filepath;
2115: }
2116:
2117: sub store_edited_file {
1.638 albertel 2118: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2119: my $file = $primary_url;
2120: $file =~ s#^/uploaded/$docudom/$docuname/##;
2121: my $fpath = '';
2122: my $fname = $file;
2123: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2124: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2125: my $filepath = &build_filepath($fpath);
2126: open(my $fh,'>'.$filepath.'/'.$fname);
2127: print $fh $content;
2128: close($fh);
1.638 albertel 2129: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2130: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2131: $home);
1.637 raeburn 2132: if ($$fetchresult eq 'ok') {
2133: return '/uploaded/'.$fpath.'/'.$fname;
2134: } else {
1.638 albertel 2135: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2136: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2137: return '/adm/notfound.html';
2138: }
2139: }
2140:
1.531 albertel 2141: sub clean_filename {
1.831 albertel 2142: my ($fname,$args)=@_;
1.315 www 2143: # Replace Windows backslashes by forward slashes
1.257 www 2144: $fname=~s/\\/\//g;
1.831 albertel 2145: if (!$args->{'keep_path'}) {
2146: # Get rid of everything but the actual filename
2147: $fname=~s/^.*\/([^\/]+)$/$1/;
2148: }
1.315 www 2149: # Replace spaces by underscores
2150: $fname=~s/\s+/\_/g;
2151: # Replace all other weird characters by nothing
1.831 albertel 2152: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2153: # Replace all .\d. sequences with _\d. so they no longer look like version
2154: # numbers
2155: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2156: return $fname;
2157: }
1.1051 raeburn 2158: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2159: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2160: # image with the same aspect ratio as the original, but with dimensions which do
2161: # not exceed $resizewidth and $resizeheight.
2162:
1.984 neumanie 2163: sub resizeImage {
1.1051 raeburn 2164: my ($img_path,$resizewidth,$resizeheight) = @_;
2165: my $ima = Image::Magick->new;
2166: my $resized;
2167: if (-e $img_path) {
2168: $ima->Read($img_path);
2169: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2170: my $width = $ima->Get('width');
2171: my $height = $ima->Get('height');
2172: if ($width > $resizewidth) {
2173: my $factor = $width/$resizewidth;
2174: my $newheight = $height/$factor;
2175: $ima->Scale(width=>$resizewidth,height=>$newheight);
2176: $resized = 1;
2177: }
2178: }
2179: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2180: my $width = $ima->Get('width');
2181: my $height = $ima->Get('height');
2182: if ($height > $resizeheight) {
2183: my $factor = $height/$resizeheight;
2184: my $newwidth = $width/$factor;
2185: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2186: $resized = 1;
2187: }
2188: }
2189: if ($resized) {
2190: $ima->Write($img_path);
2191: }
2192: }
2193: return;
1.977 amueller 2194: }
2195:
1.608 albertel 2196: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2197: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.2.10! raeburn 2198: # the desired filename is in $env{"form.$formname.filename"}
1.686 albertel 2199: # $coursedoc - if true up to the current course
2200: # if false
2201: # $subdir - directory in userfile to store the file into
1.858 raeburn 2202: # $parser - instruction to parse file for objects ($parser = parse)
2203: # $allfiles - reference to hash for embedded objects
2204: # $codebase - reference to hash for codebase of java objects
2205: # $desuname - username for permanent storage of uploaded file
2206: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2207: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2208: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2209: # $resizewidth - width (pixels) to which to resize uploaded image
2210: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2211: #
1.686 albertel 2212: # output: url of file in userspace, or error: <message>
2213: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2214:
1.531 albertel 2215: sub userfileupload {
1.860 raeburn 2216: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2217: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2218: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2219: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2220: $fname=&clean_filename($fname);
1.315 www 2221: # See if there is anything left
1.257 www 2222: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2223: chop($env{'form.'.$formname});
1.523 raeburn 2224: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2225: my $now = time;
2226: my $filepath = 'tmp/helprequests/'.$now;
2227: my @parts=split(/\//,$filepath);
2228: my $fullpath = $perlvar{'lonDaemons'};
2229: for (my $i=0;$i<@parts;$i++) {
2230: $fullpath .= '/'.$parts[$i];
2231: if ((-e $fullpath)!=1) {
2232: mkdir($fullpath,0777);
2233: }
2234: }
2235: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2236: print $fh $env{'form.'.$formname};
1.523 raeburn 2237: close($fh);
1.741 raeburn 2238: return $fullpath.'/'.$fname;
2239: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2240: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2241: '_'.$env{'user.domain'}.'/pending';
2242: my @parts=split(/\//,$filepath);
2243: my $fullpath = $perlvar{'lonDaemons'};
2244: for (my $i=0;$i<@parts;$i++) {
2245: $fullpath .= '/'.$parts[$i];
2246: if ((-e $fullpath)!=1) {
2247: mkdir($fullpath,0777);
2248: }
2249: }
2250: open(my $fh,'>'.$fullpath.'/'.$fname);
2251: print $fh $env{'form.'.$formname};
2252: close($fh);
2253: return $fullpath.'/'.$fname;
1.523 raeburn 2254: }
1.995 raeburn 2255: if ($subdir eq 'scantron') {
2256: $fname = 'scantron_orig_'.$fname;
1.1056.2.10! raeburn 2257: } else {
1.258 www 2258: # Create the directory if not present
1.995 raeburn 2259: $fname="$subdir/$fname";
2260: }
1.259 www 2261: if ($coursedoc) {
1.638 albertel 2262: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2263: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2264: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2265: return &finishuserfileupload($docuname,$docudom,
2266: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2267: $codebase,$thumbwidth,$thumbheight,
2268: $resizewidth,$resizeheight);
1.481 raeburn 2269: } else {
1.620 albertel 2270: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2271: return &process_coursefile('uploaddoc',$docuname,$docudom,
2272: $fname,$formname,$parser,
2273: $allfiles,$codebase);
1.481 raeburn 2274: }
1.719 banghart 2275: } elsif (defined($destuname)) {
2276: my $docuname=$destuname;
2277: my $docudom=$destudom;
1.860 raeburn 2278: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2279: $parser,$allfiles,$codebase,
1.1051 raeburn 2280: $thumbwidth,$thumbheight,
2281: $resizewidth,$resizeheight);
1.719 banghart 2282:
1.259 www 2283: } else {
1.638 albertel 2284: my $docuname=$env{'user.name'};
2285: my $docudom=$env{'user.domain'};
1.714 raeburn 2286: if (exists($env{'form.group'})) {
2287: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2288: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2289: }
1.860 raeburn 2290: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2291: $parser,$allfiles,$codebase,
1.1051 raeburn 2292: $thumbwidth,$thumbheight,
2293: $resizewidth,$resizeheight);
1.259 www 2294: }
1.271 www 2295: }
2296:
2297: sub finishuserfileupload {
1.860 raeburn 2298: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2299: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2300: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2301: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2302:
1.860 raeburn 2303: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2304: $file=$fname;
2305: if ($fname=~m|/|) {
2306: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2307: $path.=$fnamepath.'/';
2308: }
1.259 www 2309: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2310: my $count;
2311: for ($count=4;$count<=$#parts;$count++) {
2312: $filepath.="/$parts[$count]";
2313: if ((-e $filepath)!=1) {
2314: mkdir($filepath,0777);
2315: }
2316: }
1.984 neumanie 2317:
1.258 www 2318: # Save the file
2319: {
1.701 albertel 2320: if (!open(FH,'>'.$filepath.'/'.$file)) {
2321: &logthis('Failed to create '.$filepath.'/'.$file);
2322: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2323: return '/adm/notfound.html';
2324: }
2325: if (!print FH ($env{'form.'.$formname})) {
2326: &logthis('Failed to write to '.$filepath.'/'.$file);
2327: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2328: return '/adm/notfound.html';
2329: }
1.570 albertel 2330: close(FH);
1.1051 raeburn 2331: if ($resizewidth && $resizeheight) {
2332: my $mm = new File::MMagic;
2333: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2334: if ($mime_type =~ m{^image/}) {
2335: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2336: }
1.977 amueller 2337: }
1.258 www 2338: }
1.637 raeburn 2339: if ($parser eq 'parse') {
1.1024 raeburn 2340: my $mm = new File::MMagic;
2341: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2342: if ($mime_type eq 'text/html') {
2343: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2344: $allfiles,$codebase);
2345: unless ($parse_result eq 'ok') {
2346: &logthis('Failed to parse '.$filepath.$file.
2347: ' for embedded media: '.$parse_result);
2348: }
1.637 raeburn 2349: }
2350: }
1.860 raeburn 2351: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2352: my $input = $filepath.'/'.$file;
2353: my $output = $filepath.'/'.'tn-'.$file;
2354: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2355: system("convert -sample $thumbsize $input $output");
2356: if (-e $filepath.'/'.'tn-'.$file) {
2357: $fetchthumb = 1;
2358: }
2359: }
1.858 raeburn 2360:
1.259 www 2361: # Notify homeserver to grep it
2362: #
1.984 neumanie 2363: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2364: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2365: if ($fetchresult eq 'ok') {
1.860 raeburn 2366: if ($fetchthumb) {
2367: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2368: if ($thumbresult ne 'ok') {
2369: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2370: $docuhome.': '.$thumbresult);
2371: }
2372: }
1.259 www 2373: #
1.258 www 2374: # Return the URL to it
1.494 albertel 2375: return '/uploaded/'.$path.$file;
1.263 www 2376: } else {
1.494 albertel 2377: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2378: ': '.$fetchresult);
1.263 www 2379: return '/adm/notfound.html';
1.858 raeburn 2380: }
1.493 albertel 2381: }
2382:
1.637 raeburn 2383: sub extract_embedded_items {
1.961 raeburn 2384: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2385: my @state = ();
2386: my %javafiles = (
2387: codebase => '',
2388: code => '',
2389: archive => ''
2390: );
2391: my %mediafiles = (
2392: src => '',
2393: movie => '',
2394: );
1.648 raeburn 2395: my $p;
2396: if ($content) {
2397: $p = HTML::LCParser->new($content);
2398: } else {
1.961 raeburn 2399: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2400: }
1.641 albertel 2401: while (my $t=$p->get_token()) {
1.640 albertel 2402: if ($t->[0] eq 'S') {
2403: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2404: push(@state, $tagname);
1.648 raeburn 2405: if (lc($tagname) eq 'allow') {
2406: &add_filetype($allfiles,$attr->{'src'},'src');
2407: }
1.640 albertel 2408: if (lc($tagname) eq 'img') {
2409: &add_filetype($allfiles,$attr->{'src'},'src');
2410: }
1.886 albertel 2411: if (lc($tagname) eq 'a') {
2412: &add_filetype($allfiles,$attr->{'href'},'href');
2413: }
1.645 raeburn 2414: if (lc($tagname) eq 'script') {
2415: if ($attr->{'archive'} =~ /\.jar$/i) {
2416: &add_filetype($allfiles,$attr->{'archive'},'archive');
2417: } else {
2418: &add_filetype($allfiles,$attr->{'src'},'src');
2419: }
2420: }
2421: if (lc($tagname) eq 'link') {
2422: if (lc($attr->{'rel'}) eq 'stylesheet') {
2423: &add_filetype($allfiles,$attr->{'href'},'href');
2424: }
2425: }
1.640 albertel 2426: if (lc($tagname) eq 'object' ||
2427: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2428: foreach my $item (keys(%javafiles)) {
2429: $javafiles{$item} = '';
2430: }
2431: }
2432: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2433: my $name = lc($attr->{'name'});
2434: foreach my $item (keys(%javafiles)) {
2435: if ($name eq $item) {
2436: $javafiles{$item} = $attr->{'value'};
2437: last;
2438: }
2439: }
2440: foreach my $item (keys(%mediafiles)) {
2441: if ($name eq $item) {
2442: &add_filetype($allfiles, $attr->{'value'}, 'value');
2443: last;
2444: }
2445: }
2446: }
2447: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2448: foreach my $item (keys(%javafiles)) {
2449: if ($attr->{$item}) {
2450: $javafiles{$item} = $attr->{$item};
2451: last;
2452: }
2453: }
2454: foreach my $item (keys(%mediafiles)) {
2455: if ($attr->{$item}) {
2456: &add_filetype($allfiles,$attr->{$item},$item);
2457: last;
2458: }
2459: }
2460: }
2461: } elsif ($t->[0] eq 'E') {
2462: my ($tagname) = ($t->[1]);
2463: if ($javafiles{'codebase'} ne '') {
2464: $javafiles{'codebase'} .= '/';
2465: }
2466: if (lc($tagname) eq 'applet' ||
2467: lc($tagname) eq 'object' ||
2468: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2469: ) {
2470: foreach my $item (keys(%javafiles)) {
2471: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2472: my $file=$javafiles{'codebase'}.$javafiles{$item};
2473: &add_filetype($allfiles,$file,$item);
2474: }
2475: }
2476: }
2477: pop @state;
2478: }
2479: }
1.637 raeburn 2480: return 'ok';
2481: }
2482:
1.639 albertel 2483: sub add_filetype {
2484: my ($allfiles,$file,$type)=@_;
2485: if (exists($allfiles->{$file})) {
2486: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2487: push(@{$allfiles->{$file}}, &escape($type));
2488: }
2489: } else {
2490: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2491: }
2492: }
2493:
1.493 albertel 2494: sub removeuploadedurl {
1.984 neumanie 2495: my ($url)=@_;
2496: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2497: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2498: }
2499:
2500: sub removeuserfile {
2501: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2502: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2503: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2504: if ($result eq 'ok') {
1.798 raeburn 2505: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2506: my $metafile = $fname.'.meta';
2507: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2508: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2509: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2510: my $sqlresult =
1.823 albertel 2511: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2512: 'portfolio_metadata',$group,
2513: 'delete');
1.798 raeburn 2514: }
2515: }
2516: return $result;
1.257 www 2517: }
1.15 www 2518:
1.530 albertel 2519: sub mkdiruserfile {
2520: my ($docuname,$docudom,$dir)=@_;
2521: my $home=&homeserver($docuname,$docudom);
2522: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2523: }
2524:
1.531 albertel 2525: sub renameuserfile {
2526: my ($docuname,$docudom,$old,$new)=@_;
2527: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2528: my $result = &reply("renameuserfile:$docudom:$docuname:".
2529: &escape("$old").':'.&escape("$new"),$home);
2530: if ($result eq 'ok') {
2531: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2532: my $oldmeta = $old.'.meta';
2533: my $newmeta = $new.'.meta';
2534: my $metaresult =
2535: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2536: my $url = "/uploaded/$docudom/$docuname/$old";
2537: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2538: my $sqlresult =
1.823 albertel 2539: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2540: 'portfolio_metadata',$group,
2541: 'delete');
1.798 raeburn 2542: }
2543: }
2544: return $result;
1.531 albertel 2545: }
2546:
1.14 www 2547: # ------------------------------------------------------------------------- Log
2548:
2549: sub log {
2550: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2551: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2552: }
2553:
2554: # ------------------------------------------------------------------ Course Log
1.352 www 2555: #
2556: # This routine flushes several buffers of non-mission-critical nature
2557: #
1.157 www 2558:
2559: sub flushcourselogs {
1.352 www 2560: &logthis('Flushing log buffers');
2561: #
2562: # course logs
2563: # This is a log of all transactions in a course, which can be used
2564: # for data mining purposes
2565: #
2566: # It also collects the courseid database, which lists last transaction
2567: # times and course titles for all courseids
2568: #
2569: my %courseidbuffer=();
1.921 raeburn 2570: foreach my $crsid (keys(%courselogs)) {
1.352 www 2571: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2572: &escape($courselogs{$crsid}),
2573: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2574: delete $courselogs{$crsid};
2575: } else {
2576: &logthis('Failed to flush log buffer for '.$crsid);
2577: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2578: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2579: " exceeded maximum size, deleting.</font>");
2580: delete $courselogs{$crsid};
2581: }
1.352 www 2582: }
1.920 raeburn 2583: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2584: 'description' => $coursedescrbuf{$crsid},
2585: 'inst_code' => $courseinstcodebuf{$crsid},
2586: 'type' => $coursetypebuf{$crsid},
2587: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2588: };
1.191 harris41 2589: }
1.352 www 2590: #
2591: # Write course id database (reverse lookup) to homeserver of courses
2592: # Is used in pickcourse
2593: #
1.840 albertel 2594: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2595: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2596: $courseidbuffer{$crs_home},
2597: $crs_home,'timeonly');
1.352 www 2598: }
2599: #
2600: # File accesses
2601: # Writes to the dynamic metadata of resources to get hit counts, etc.
2602: #
1.449 matthew 2603: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2604: if ($entry =~ /___count$/) {
2605: my ($dom,$name);
1.807 albertel 2606: ($dom,$name,undef)=
1.811 albertel 2607: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2608: if (! defined($dom) || $dom eq '' ||
2609: ! defined($name) || $name eq '') {
1.620 albertel 2610: my $cid = $env{'request.course.id'};
2611: $dom = $env{'request.'.$cid.'.domain'};
2612: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2613: }
1.450 matthew 2614: my $value = $accesshash{$entry};
2615: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2616: my %temphash=($url => $value);
1.449 matthew 2617: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2618: if ($result eq 'ok') {
2619: delete $accesshash{$entry};
2620: } elsif ($result eq 'unknown_cmd') {
2621: # Target server has old code running on it.
1.450 matthew 2622: my %temphash=($entry => $value);
1.449 matthew 2623: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2624: delete $accesshash{$entry};
2625: }
2626: }
2627: } else {
1.811 albertel 2628: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2629: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2630: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2631: delete $accesshash{$entry};
2632: }
1.185 www 2633: }
1.191 harris41 2634: }
1.352 www 2635: #
2636: # Roles
2637: # Reverse lookup of user roles for course faculty/staff and co-authorship
2638: #
1.800 albertel 2639: foreach my $entry (keys(%userrolehash)) {
1.351 www 2640: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2641: split(/\:/,$entry);
2642: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2643: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2644: $rudom,$runame) eq 'ok') {
2645: delete $userrolehash{$entry};
2646: }
2647: }
1.662 raeburn 2648: #
2649: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2650: #
2651: my %domrolebuffer = ();
1.1000 raeburn 2652: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2653: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2654: if ($domrolebuffer{$rudom}) {
2655: $domrolebuffer{$rudom}.='&'.&escape($entry).
2656: '='.&escape($domainrolehash{$entry});
2657: } else {
2658: $domrolebuffer{$rudom}.=&escape($entry).
2659: '='.&escape($domainrolehash{$entry});
2660: }
2661: delete $domainrolehash{$entry};
2662: }
2663: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2664: my %servers = &get_servers($dom,'library');
2665: foreach my $tryserver (keys(%servers)) {
2666: unless (&reply('domroleput:'.$dom.':'.
2667: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2668: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2669: }
1.662 raeburn 2670: }
2671: }
1.186 www 2672: $dumpcount++;
1.157 www 2673: }
2674:
2675: sub courselog {
2676: my $what=shift;
1.158 www 2677: $what=time.':'.$what;
1.620 albertel 2678: unless ($env{'request.course.id'}) { return ''; }
2679: $coursedombuf{$env{'request.course.id'}}=
2680: $env{'course.'.$env{'request.course.id'}.'.domain'};
2681: $coursenumbuf{$env{'request.course.id'}}=
2682: $env{'course.'.$env{'request.course.id'}.'.num'};
2683: $coursehombuf{$env{'request.course.id'}}=
2684: $env{'course.'.$env{'request.course.id'}.'.home'};
2685: $coursedescrbuf{$env{'request.course.id'}}=
2686: $env{'course.'.$env{'request.course.id'}.'.description'};
2687: $courseinstcodebuf{$env{'request.course.id'}}=
2688: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2689: $courseownerbuf{$env{'request.course.id'}}=
2690: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2691: $coursetypebuf{$env{'request.course.id'}}=
2692: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2693: if (defined $courselogs{$env{'request.course.id'}}) {
2694: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2695: } else {
1.620 albertel 2696: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2697: }
1.620 albertel 2698: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2699: &flushcourselogs();
2700: }
1.158 www 2701: }
2702:
2703: sub courseacclog {
2704: my $fnsymb=shift;
1.620 albertel 2705: unless ($env{'request.course.id'}) { return ''; }
2706: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2707: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2708: $what.=':POST';
1.583 matthew 2709: # FIXME: Probably ought to escape things....
1.800 albertel 2710: foreach my $key (keys(%env)) {
2711: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2712: my $formitem = $1;
2713: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2714: $what.=':'.$formitem.'='.$env{$key};
2715: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2716: $what.=':'.$formitem.'='.$env{$key};
2717: }
1.158 www 2718: }
1.191 harris41 2719: }
1.583 matthew 2720: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2721: # FIXME: We should not be depending on a form parameter that someone
2722: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2723: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2724: $what.= ':POST';
2725: # FIXME: Probably ought to escape things....
2726: foreach my $element ('courseexp','crsfulltext','crsrelated',
2727: 'crsdiscuss') {
1.620 albertel 2728: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2729: }
2730: }
1.158 www 2731: }
2732: &courselog($what);
1.149 www 2733: }
2734:
1.185 www 2735: sub countacc {
2736: my $url=&declutter(shift);
1.458 matthew 2737: return if (! defined($url) || $url eq '');
1.620 albertel 2738: unless ($env{'request.course.id'}) { return ''; }
2739: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2740: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2741: $accesshash{$key}++;
1.185 www 2742: }
1.349 www 2743:
1.361 www 2744: sub linklog {
2745: my ($from,$to)=@_;
2746: $from=&declutter($from);
2747: $to=&declutter($to);
2748: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2749: $accesshash{$to.'___'.$from.'___goto'}=1;
2750: }
2751:
1.349 www 2752: sub userrolelog {
2753: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2754: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2755: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2756: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2757: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2758: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2759: $userrolehash
2760: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2761: =$tend.':'.$tstart;
1.662 raeburn 2762: }
1.898 albertel 2763: if (($env{'request.role'} =~ /dc\./) &&
2764: (($trole=~/^au/) || ($trole=~/^in/) ||
2765: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2766: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2767: ($trole=~/^co/))) {
1.898 albertel 2768: $userrolehash
2769: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2770: =$tend.':'.$tstart;
2771: }
1.662 raeburn 2772: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2773: ($trole=~/^li/) || ($trole=~/^li/) ||
2774: ($trole=~/^au/) || ($trole=~/^dg/) ||
2775: ($trole=~/^sc/)) {
2776: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2777: $domainrolehash
2778: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2779: = $tend.':'.$tstart;
2780: }
1.351 www 2781: }
2782:
1.957 raeburn 2783: sub courserolelog {
2784: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2785: if (($trole eq 'cc') || ($trole eq 'in') ||
2786: ($trole eq 'ep') || ($trole eq 'ad') ||
2787: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2788: ($trole=~/^cr/) || ($trole eq 'gr') ||
2789: ($trole eq 'co')) {
1.957 raeburn 2790: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2791: my $cdom = $1;
2792: my $cnum = $2;
2793: my $sec = $3;
2794: my $namespace = 'rolelog';
2795: my %storehash = (
2796: role => $trole,
2797: start => $tstart,
2798: end => $tend,
2799: selfenroll => $selfenroll,
2800: context => $context,
2801: );
2802: if ($trole eq 'gr') {
2803: $namespace = 'groupslog';
2804: $storehash{'group'} = $sec;
2805: } else {
2806: $storehash{'section'} = $sec;
2807: }
2808: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2809: if (($trole ne 'st') || ($sec ne '')) {
2810: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2811: }
1.957 raeburn 2812: }
2813: }
2814: return;
2815: }
2816:
1.351 www 2817: sub get_course_adv_roles {
1.948 raeburn 2818: my ($cid,$codes) = @_;
1.620 albertel 2819: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2820: my %coursehash=&coursedescription($cid);
1.988 raeburn 2821: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2822: my %nothide=();
1.800 albertel 2823: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2824: if ($user !~ /:/) {
2825: $nothide{join(':',split(/[\@]/,$user))}=1;
2826: } else {
2827: $nothide{$user}=1;
2828: }
1.470 www 2829: }
1.351 www 2830: my %returnhash=();
2831: my %dumphash=
2832: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2833: my $now=time;
1.997 raeburn 2834: my %privileged;
1.1000 raeburn 2835: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2836: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2837: if (($tstart) && ($tstart<0)) { next; }
2838: if (($tend) && ($tend<$now)) { next; }
2839: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2840: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2841: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2842: unless (ref($privileged{$domain}) eq 'HASH') {
2843: my %dompersonnel =
1.998 raeburn 2844: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2845: $privileged{$domain} = {};
2846: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2847: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2848: foreach my $user (keys(%{$dompersonnel{$server}})) {
2849: my ($trole,$uname,$udom) = split(/:/,$user);
2850: $privileged{$udom}{$uname} = 1;
2851: }
2852: }
2853: }
2854: }
2855: if ((exists($privileged{$domain}{$username})) &&
2856: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2857: if ($role eq 'cr') { next; }
1.948 raeburn 2858: if ($codes) {
2859: if ($section) { $role .= ':'.$section; }
2860: if ($returnhash{$role}) {
2861: $returnhash{$role}.=','.$username.':'.$domain;
2862: } else {
2863: $returnhash{$role}=$username.':'.$domain;
2864: }
1.351 www 2865: } else {
1.988 raeburn 2866: my $key=&plaintext($role,$crstype);
1.973 bisitz 2867: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2868: if ($returnhash{$key}) {
2869: $returnhash{$key}.=','.$username.':'.$domain;
2870: } else {
2871: $returnhash{$key}=$username.':'.$domain;
2872: }
1.351 www 2873: }
1.948 raeburn 2874: }
1.400 www 2875: return %returnhash;
2876: }
2877:
2878: sub get_my_roles {
1.937 raeburn 2879: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2880: unless (defined($uname)) { $uname=$env{'user.name'}; }
2881: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2882: my (%dumphash,%nothide);
1.1056.2.9 raeburn 2883: if ($context eq 'userroles') {
2884: my $extra = &freeze_escape({'skipcheck' => 1});
2885: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 2886: } else {
2887: %dumphash=
1.400 www 2888: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2889: if ($hidepriv) {
2890: my %coursehash=&coursedescription($udom.'_'.$uname);
2891: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2892: if ($user !~ /:/) {
2893: $nothide{join(':',split(/[\@]/,$user))} = 1;
2894: } else {
2895: $nothide{$user} = 1;
2896: }
2897: }
2898: }
1.858 raeburn 2899: }
1.400 www 2900: my %returnhash=();
2901: my $now=time;
1.999 raeburn 2902: my %privileged;
1.800 albertel 2903: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2904: my ($role,$tend,$tstart);
2905: if ($context eq 'userroles') {
2906: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2907: } else {
2908: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2909: }
1.400 www 2910: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2911: my $status = 'active';
1.939 raeburn 2912: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2913: $status = 'previous';
2914: }
2915: if (($tstart) && ($now<$tstart)) {
2916: $status = 'future';
2917: }
2918: if (ref($types) eq 'ARRAY') {
2919: if (!grep(/^\Q$status\E$/,@{$types})) {
2920: next;
2921: }
2922: } else {
2923: if ($status ne 'active') {
2924: next;
2925: }
2926: }
1.867 raeburn 2927: my ($rolecode,$username,$domain,$section,$area);
2928: if ($context eq 'userroles') {
2929: ($area,$rolecode) = split(/_/,$entry);
2930: (undef,$domain,$username,$section) = split(/\//,$area);
2931: } else {
2932: ($role,$username,$domain,$section) = split(/\:/,$entry);
2933: }
1.832 raeburn 2934: if (ref($roledoms) eq 'ARRAY') {
2935: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2936: next;
2937: }
2938: }
2939: if (ref($roles) eq 'ARRAY') {
2940: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2941: if ($role =~ /^cr\//) {
2942: if (!grep(/^cr$/,@{$roles})) {
2943: next;
2944: }
2945: } else {
2946: next;
2947: }
1.832 raeburn 2948: }
1.867 raeburn 2949: }
1.937 raeburn 2950: if ($hidepriv) {
1.999 raeburn 2951: if ($context eq 'userroles') {
2952: if ((&privileged($username,$domain)) &&
2953: (!$nothide{$username.':'.$domain})) {
2954: next;
2955: }
2956: } else {
2957: unless (ref($privileged{$domain}) eq 'HASH') {
2958: my %dompersonnel =
2959: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2960: $privileged{$domain} = {};
2961: if (keys(%dompersonnel)) {
2962: foreach my $server (keys(%dompersonnel)) {
2963: if (ref($dompersonnel{$server}) eq 'HASH') {
2964: foreach my $user (keys(%{$dompersonnel{$server}})) {
2965: my ($trole,$uname,$udom) = split(/:/,$user);
2966: $privileged{$udom}{$uname} = $trole;
2967: }
2968: }
2969: }
2970: }
2971: }
2972: if (exists($privileged{$domain}{$username})) {
2973: if (!$nothide{$username.':'.$domain}) {
2974: next;
2975: }
2976: }
1.937 raeburn 2977: }
2978: }
1.933 raeburn 2979: if ($withsec) {
2980: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2981: $tstart.':'.$tend;
2982: } else {
2983: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2984: }
1.832 raeburn 2985: }
1.373 www 2986: return %returnhash;
1.399 www 2987: }
2988:
2989: # ----------------------------------------------------- Frontpage Announcements
2990: #
2991: #
2992:
2993: sub postannounce {
2994: my ($server,$text)=@_;
1.844 albertel 2995: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2996: unless ($text=~/\w/) { $text=''; }
2997: return &reply('setannounce:'.&escape($text),$server);
2998: }
2999:
3000: sub getannounce {
1.448 albertel 3001:
3002: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3003: my $announcement='';
1.800 albertel 3004: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3005: close($fh);
1.399 www 3006: if ($announcement=~/\w/) {
3007: return
3008: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3009: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3010: } else {
3011: return '';
3012: }
3013: } else {
3014: return '';
3015: }
1.351 www 3016: }
1.353 www 3017:
3018: # ---------------------------------------------------------- Course ID routines
3019: # Deal with domain's nohist_courseid.db files
3020: #
3021:
3022: sub courseidput {
1.921 raeburn 3023: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3024: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3025: my $outcome;
3026: if ($caller eq 'timeonly') {
3027: my $cids = '';
3028: foreach my $item (keys(%$storehash)) {
3029: $cids.=&escape($item).'&';
3030: }
3031: $cids=~s/\&$//;
3032: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3033: $coursehome);
3034: } else {
3035: my $items = '';
3036: foreach my $item (keys(%$storehash)) {
3037: $items.= &escape($item).'='.
3038: &freeze_escape($$storehash{$item}).'&';
3039: }
3040: $items=~s/\&$//;
3041: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3042: $coursehome);
1.918 raeburn 3043: }
3044: if ($outcome eq 'unknown_cmd') {
3045: my $what;
3046: foreach my $cid (keys(%$storehash)) {
3047: $what .= &escape($cid).'=';
1.921 raeburn 3048: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3049: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3050: }
3051: $what =~ s/\:$/&/;
3052: }
3053: $what =~ s/\&$//;
3054: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3055: } else {
3056: return $outcome;
3057: }
1.353 www 3058: }
3059:
3060: sub courseiddump {
1.921 raeburn 3061: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3062: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3063: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.2.5 raeburn 3064: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3065: my $as_hash = 1;
3066: my %returnhash;
3067: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3068: my %libserv = &all_library();
3069: foreach my $tryserver (keys(%libserv)) {
3070: if ( ( $hostidflag == 1
3071: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3072: || (!defined($hostidflag)) ) {
3073:
1.918 raeburn 3074: if (($domfilter eq '') ||
3075: (&host_domain($tryserver) eq $domfilter)) {
3076: my $rep =
3077: &reply('courseiddump:'.&host_domain($tryserver).':'.
3078: $sincefilter.':'.&escape($descfilter).':'.
3079: &escape($instcodefilter).':'.&escape($ownerfilter).
3080: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3081: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3082: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3083: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3084: &escape($cc_clone).':'.$cloneonly.':'.
3085: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.2.5 raeburn 3086: &escape($creationcontext).':'.$domcloner,
3087: $tryserver);
1.918 raeburn 3088: my @pairs=split(/\&/,$rep);
3089: foreach my $item (@pairs) {
3090: my ($key,$value)=split(/\=/,$item,2);
3091: $key = &unescape($key);
3092: next if ($key =~ /^error: 2 /);
3093: my $result = &thaw_unescape($value);
3094: if (ref($result) eq 'HASH') {
3095: $returnhash{$key}=$result;
3096: } else {
1.921 raeburn 3097: my @responses = split(/:/,$value);
3098: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3099: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3100: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3101: }
1.1008 raeburn 3102: }
1.353 www 3103: }
3104: }
3105: }
3106: }
3107: return %returnhash;
3108: }
3109:
1.1055 raeburn 3110: sub courselastaccess {
3111: my ($cdom,$cnum,$hostidref) = @_;
3112: my %returnhash;
3113: if ($cdom && $cnum) {
3114: my $chome = &homeserver($cnum,$cdom);
3115: if ($chome ne 'no_host') {
3116: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3117: &extract_lastaccess(\%returnhash,$rep);
3118: }
3119: } else {
3120: if (!$cdom) { $cdom=''; }
3121: my %libserv = &all_library();
3122: foreach my $tryserver (keys(%libserv)) {
3123: if (ref($hostidref) eq 'ARRAY') {
3124: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3125: }
3126: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3127: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3128: &extract_lastaccess(\%returnhash,$rep);
3129: }
3130: }
3131: }
3132: return %returnhash;
3133: }
3134:
3135: sub extract_lastaccess {
3136: my ($returnhash,$rep) = @_;
3137: if (ref($returnhash) eq 'HASH') {
3138: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3139: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3140: $rep eq '') {
3141: my @pairs=split(/\&/,$rep);
3142: foreach my $item (@pairs) {
3143: my ($key,$value)=split(/\=/,$item,2);
3144: $key = &unescape($key);
3145: next if ($key =~ /^error: 2 /);
3146: $returnhash->{$key} = &thaw_unescape($value);
3147: }
3148: }
3149: }
3150: return;
3151: }
3152:
1.658 raeburn 3153: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3154:
3155: sub dcmailput {
1.685 raeburn 3156: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3157: my $status = &Apache::lonnet::critical(
1.740 www 3158: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3159: &escape($message),$server);
1.662 raeburn 3160: return $status;
3161: }
3162:
1.658 raeburn 3163: sub dcmaildump {
3164: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3165: my %returnhash=();
1.846 albertel 3166:
3167: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3168: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3169: &escape($enddate).':';
3170: my @esc_senders=map { &escape($_)} @$senders;
3171: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3172: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3173: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3174: if (($key) && ($value)) {
3175: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3176: }
3177: }
3178: }
3179: return %returnhash;
3180: }
1.662 raeburn 3181: # ---------------------------------------------------------- Domain roles
3182:
3183: sub get_domain_roles {
3184: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3185: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3186: $startdate = '.';
3187: }
1.1018 raeburn 3188: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3189: $enddate = '.';
3190: }
1.922 raeburn 3191: my $rolelist;
3192: if (ref($roles) eq 'ARRAY') {
3193: $rolelist = join(':',@{$roles});
3194: }
1.662 raeburn 3195: my %personnel = ();
1.841 albertel 3196:
3197: my %servers = &get_servers($dom,'library');
3198: foreach my $tryserver (keys(%servers)) {
3199: %{$personnel{$tryserver}}=();
3200: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3201: &escape($startdate).':'.
3202: &escape($enddate).':'.
3203: &escape($rolelist), $tryserver))) {
3204: my ($key,$value) = split(/\=/,$line,2);
3205: if (($key) && ($value)) {
3206: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3207: }
3208: }
1.662 raeburn 3209: }
3210: return %personnel;
3211: }
1.658 raeburn 3212:
1.149 www 3213: # ----------------------------------------------------------- Check out an item
3214:
1.504 albertel 3215: sub get_first_access {
3216: my ($type,$argsymb)=@_;
1.790 albertel 3217: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3218: if ($argsymb) { $symb=$argsymb; }
3219: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3220: if ($type eq 'course') {
3221: $res='course';
3222: } elsif ($type eq 'map') {
1.588 albertel 3223: $res=&symbread($map);
3224: } else {
3225: $res=$symb;
3226: }
3227: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3228: return $times{"$courseid\0$res"};
1.504 albertel 3229: }
3230:
3231: sub set_first_access {
3232: my ($type)=@_;
1.790 albertel 3233: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3234: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3235: if ($type eq 'course') {
3236: $res='course';
3237: } elsif ($type eq 'map') {
1.588 albertel 3238: $res=&symbread($map);
3239: } else {
3240: $res=$symb;
3241: }
3242: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3243: if (!$firstaccess) {
1.588 albertel 3244: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3245: }
3246: return 'already_set';
1.504 albertel 3247: }
3248:
1.149 www 3249: sub checkout {
3250: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3251: my $now=time;
3252: my $lonhost=$perlvar{'lonHostID'};
3253: my $infostr=&escape(
1.234 www 3254: 'CHECKOUTTOKEN&'.
1.149 www 3255: $tuname.'&'.
3256: $tudom.'&'.
3257: $tcrsid.'&'.
3258: $symb.'&'.
3259: $now.'&'.$ENV{'REMOTE_ADDR'});
3260: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3261: if ($token=~/^error\:/) {
1.672 albertel 3262: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3263: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3264: "</font>");
3265: return '';
3266: }
3267:
1.149 www 3268: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3269: $token=~tr/a-z/A-Z/;
3270:
1.153 www 3271: my %infohash=('resource.0.outtoken' => $token,
3272: 'resource.0.checkouttime' => $now,
3273: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3274:
3275: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3276: return '';
1.151 www 3277: } else {
1.672 albertel 3278: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3279: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3280: "</font>");
1.149 www 3281: }
3282:
3283: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3284: &escape('Checkout '.$infostr.' - '.
3285: $token)) ne 'ok') {
3286: return '';
1.151 www 3287: } else {
1.672 albertel 3288: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3289: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3290: "</font>");
1.149 www 3291: }
1.151 www 3292: return $token;
1.149 www 3293: }
3294:
3295: # ------------------------------------------------------------ Check in an item
3296:
3297: sub checkin {
3298: my $token=shift;
1.150 www 3299: my $now=time;
3300: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3301: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3302: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3303: $dtoken=~s/\W/\_/g;
1.234 www 3304: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3305: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3306:
1.154 www 3307: unless (($tuname) && ($tudom)) {
3308: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3309: return '';
3310: }
3311:
3312: unless (&allowed('mgr',$tcrsid)) {
3313: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3314: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3315: return '';
3316: }
3317:
1.153 www 3318: my %infohash=('resource.0.intoken' => $token,
3319: 'resource.0.checkintime' => $now,
3320: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3321:
3322: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3323: return '';
3324: }
3325:
3326: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3327: &escape('Checkin - '.$token)) ne 'ok') {
3328: return '';
3329: }
3330:
3331: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3332: }
3333:
3334: # --------------------------------------------- Set Expire Date for Spreadsheet
3335:
3336: sub expirespread {
3337: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3338: my $cid=$env{'request.course.id'};
1.110 www 3339: if ($cid) {
3340: my $now=time;
3341: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3342: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3343: $env{'course.'.$cid.'.num'}.
1.110 www 3344: ':nohist_expirationdates:'.
3345: &escape($key).'='.$now,
1.620 albertel 3346: $env{'course.'.$cid.'.home'})
1.110 www 3347: }
3348: return 'ok';
1.14 www 3349: }
3350:
1.109 www 3351: # ----------------------------------------------------- Devalidate Spreadsheets
3352:
3353: sub devalidate {
1.325 www 3354: my ($symb,$uname,$udom)=@_;
1.620 albertel 3355: my $cid=$env{'request.course.id'};
1.109 www 3356: if ($cid) {
1.391 matthew 3357: # delete the stored spreadsheets for
3358: # - the student level sheet of this user in course's homespace
3359: # - the assessment level sheet for this resource
3360: # for this user in user's homespace
1.553 albertel 3361: # - current conditional state info
1.325 www 3362: my $key=$uname.':'.$udom.':';
1.109 www 3363: my $status=
1.299 matthew 3364: &del('nohist_calculatedsheets',
1.391 matthew 3365: [$key.'studentcalc:'],
1.620 albertel 3366: $env{'course.'.$cid.'.domain'},
3367: $env{'course.'.$cid.'.num'})
1.133 albertel 3368: .' '.
3369: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3370: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3371: unless ($status eq 'ok ok') {
3372: &logthis('Could not devalidate spreadsheet '.
1.325 www 3373: $uname.' at '.$udom.' for '.
1.109 www 3374: $symb.': '.$status);
1.133 albertel 3375: }
1.553 albertel 3376: &delenv('user.state.'.$cid);
1.109 www 3377: }
3378: }
3379:
1.265 albertel 3380: sub get_scalar {
3381: my ($string,$end) = @_;
3382: my $value;
3383: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3384: $value = $1;
3385: } elsif ($$string =~ s/^([^&]*?)&//) {
3386: $value = $1;
3387: }
3388: return &unescape($value);
3389: }
3390:
3391: sub array2str {
3392: my (@array) = @_;
3393: my $result=&arrayref2str(\@array);
3394: $result=~s/^__ARRAY_REF__//;
3395: $result=~s/__END_ARRAY_REF__$//;
3396: return $result;
3397: }
3398:
1.204 albertel 3399: sub arrayref2str {
3400: my ($arrayref) = @_;
1.265 albertel 3401: my $result='__ARRAY_REF__';
1.204 albertel 3402: foreach my $elem (@$arrayref) {
1.265 albertel 3403: if(ref($elem) eq 'ARRAY') {
3404: $result.=&arrayref2str($elem).'&';
3405: } elsif(ref($elem) eq 'HASH') {
3406: $result.=&hashref2str($elem).'&';
3407: } elsif(ref($elem)) {
3408: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3409: } else {
3410: $result.=&escape($elem).'&';
3411: }
3412: }
3413: $result=~s/\&$//;
1.265 albertel 3414: $result .= '__END_ARRAY_REF__';
1.204 albertel 3415: return $result;
3416: }
3417:
1.168 albertel 3418: sub hash2str {
1.204 albertel 3419: my (%hash) = @_;
3420: my $result=&hashref2str(\%hash);
1.265 albertel 3421: $result=~s/^__HASH_REF__//;
3422: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3423: return $result;
3424: }
3425:
3426: sub hashref2str {
3427: my ($hashref)=@_;
1.265 albertel 3428: my $result='__HASH_REF__';
1.800 albertel 3429: foreach my $key (sort(keys(%$hashref))) {
3430: if (ref($key) eq 'ARRAY') {
3431: $result.=&arrayref2str($key).'=';
3432: } elsif (ref($key) eq 'HASH') {
3433: $result.=&hashref2str($key).'=';
3434: } elsif (ref($key)) {
1.265 albertel 3435: $result.='=';
1.800 albertel 3436: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3437: } else {
1.800 albertel 3438: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3439: }
3440:
1.800 albertel 3441: if(ref($hashref->{$key}) eq 'ARRAY') {
3442: $result.=&arrayref2str($hashref->{$key}).'&';
3443: } elsif(ref($hashref->{$key}) eq 'HASH') {
3444: $result.=&hashref2str($hashref->{$key}).'&';
3445: } elsif(ref($hashref->{$key})) {
1.265 albertel 3446: $result.='&';
1.800 albertel 3447: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3448: } else {
1.800 albertel 3449: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3450: }
3451: }
1.168 albertel 3452: $result=~s/\&$//;
1.265 albertel 3453: $result .= '__END_HASH_REF__';
1.168 albertel 3454: return $result;
3455: }
3456:
3457: sub str2hash {
1.265 albertel 3458: my ($string)=@_;
3459: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3460: return %$hash;
3461: }
3462:
3463: sub str2hashref {
1.168 albertel 3464: my ($string) = @_;
1.265 albertel 3465:
3466: my %hash;
3467:
3468: if($string !~ /^__HASH_REF__/) {
3469: if (! ($string eq '' || !defined($string))) {
3470: $hash{'error'}='Not hash reference';
3471: }
3472: return (\%hash, $string);
3473: }
3474:
3475: $string =~ s/^__HASH_REF__//;
3476:
3477: while($string !~ /^__END_HASH_REF__/) {
3478: #key
3479: my $key='';
3480: if($string =~ /^__HASH_REF__/) {
3481: ($key, $string)=&str2hashref($string);
3482: if(defined($key->{'error'})) {
3483: $hash{'error'}='Bad data';
3484: return (\%hash, $string);
3485: }
3486: } elsif($string =~ /^__ARRAY_REF__/) {
3487: ($key, $string)=&str2arrayref($string);
3488: if($key->[0] eq 'Array reference error') {
3489: $hash{'error'}='Bad data';
3490: return (\%hash, $string);
3491: }
3492: } else {
3493: $string =~ s/^(.*?)=//;
1.267 albertel 3494: $key=&unescape($1);
1.265 albertel 3495: }
3496: $string =~ s/^=//;
3497:
3498: #value
3499: my $value='';
3500: if($string =~ /^__HASH_REF__/) {
3501: ($value, $string)=&str2hashref($string);
3502: if(defined($value->{'error'})) {
3503: $hash{'error'}='Bad data';
3504: return (\%hash, $string);
3505: }
3506: } elsif($string =~ /^__ARRAY_REF__/) {
3507: ($value, $string)=&str2arrayref($string);
3508: if($value->[0] eq 'Array reference error') {
3509: $hash{'error'}='Bad data';
3510: return (\%hash, $string);
3511: }
3512: } else {
3513: $value=&get_scalar(\$string,'__END_HASH_REF__');
3514: }
3515: $string =~ s/^&//;
3516:
3517: $hash{$key}=$value;
1.204 albertel 3518: }
1.265 albertel 3519:
3520: $string =~ s/^__END_HASH_REF__//;
3521:
3522: return (\%hash, $string);
1.204 albertel 3523: }
3524:
3525: sub str2array {
1.265 albertel 3526: my ($string)=@_;
3527: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3528: return @$array;
3529: }
3530:
3531: sub str2arrayref {
1.204 albertel 3532: my ($string) = @_;
1.265 albertel 3533: my @array;
3534:
3535: if($string !~ /^__ARRAY_REF__/) {
3536: if (! ($string eq '' || !defined($string))) {
3537: $array[0]='Array reference error';
3538: }
3539: return (\@array, $string);
3540: }
3541:
3542: $string =~ s/^__ARRAY_REF__//;
3543:
3544: while($string !~ /^__END_ARRAY_REF__/) {
3545: my $value='';
3546: if($string =~ /^__HASH_REF__/) {
3547: ($value, $string)=&str2hashref($string);
3548: if(defined($value->{'error'})) {
3549: $array[0] ='Array reference error';
3550: return (\@array, $string);
3551: }
3552: } elsif($string =~ /^__ARRAY_REF__/) {
3553: ($value, $string)=&str2arrayref($string);
3554: if($value->[0] eq 'Array reference error') {
3555: $array[0] ='Array reference error';
3556: return (\@array, $string);
3557: }
3558: } else {
3559: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3560: }
3561: $string =~ s/^&//;
3562:
3563: push(@array, $value);
1.191 harris41 3564: }
1.265 albertel 3565:
3566: $string =~ s/^__END_ARRAY_REF__//;
3567:
3568: return (\@array, $string);
1.168 albertel 3569: }
3570:
1.167 albertel 3571: # -------------------------------------------------------------------Temp Store
3572:
1.168 albertel 3573: sub tmpreset {
3574: my ($symb,$namespace,$domain,$stuname) = @_;
3575: if (!$symb) {
3576: $symb=&symbread();
1.620 albertel 3577: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3578: }
3579: $symb=escape($symb);
3580:
1.620 albertel 3581: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3582: $namespace=~s/\//\_/g;
3583: $namespace=~s/\W//g;
3584:
1.620 albertel 3585: if (!$domain) { $domain=$env{'user.domain'}; }
3586: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3587: if ($domain eq 'public' && $stuname eq 'public') {
3588: $stuname=$ENV{'REMOTE_ADDR'};
3589: }
1.168 albertel 3590: my $path=$perlvar{'lonDaemons'}.'/tmp';
3591: my %hash;
3592: if (tie(%hash,'GDBM_File',
3593: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3594: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3595: foreach my $key (keys(%hash)) {
1.180 albertel 3596: if ($key=~ /:$symb/) {
1.168 albertel 3597: delete($hash{$key});
3598: }
3599: }
3600: }
3601: }
3602:
1.167 albertel 3603: sub tmpstore {
1.168 albertel 3604: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3605:
3606: if (!$symb) {
3607: $symb=&symbread();
1.620 albertel 3608: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3609: }
3610: $symb=escape($symb);
3611:
3612: if (!$namespace) {
3613: # I don't think we would ever want to store this for a course.
3614: # it seems this will only be used if we don't have a course.
1.620 albertel 3615: #$namespace=$env{'request.course.id'};
1.168 albertel 3616: #if (!$namespace) {
1.620 albertel 3617: $namespace=$env{'request.state'};
1.168 albertel 3618: #}
3619: }
3620: $namespace=~s/\//\_/g;
3621: $namespace=~s/\W//g;
1.620 albertel 3622: if (!$domain) { $domain=$env{'user.domain'}; }
3623: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3624: if ($domain eq 'public' && $stuname eq 'public') {
3625: $stuname=$ENV{'REMOTE_ADDR'};
3626: }
1.168 albertel 3627: my $now=time;
3628: my %hash;
3629: my $path=$perlvar{'lonDaemons'}.'/tmp';
3630: if (tie(%hash,'GDBM_File',
3631: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3632: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3633: $hash{"version:$symb"}++;
3634: my $version=$hash{"version:$symb"};
3635: my $allkeys='';
3636: foreach my $key (keys(%$storehash)) {
3637: $allkeys.=$key.':';
1.591 albertel 3638: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3639: }
3640: $hash{"$version:$symb:timestamp"}=$now;
3641: $allkeys.='timestamp';
3642: $hash{"$version:keys:$symb"}=$allkeys;
3643: if (untie(%hash)) {
3644: return 'ok';
3645: } else {
3646: return "error:$!";
3647: }
3648: } else {
3649: return "error:$!";
3650: }
3651: }
1.167 albertel 3652:
1.168 albertel 3653: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3654:
1.168 albertel 3655: sub tmprestore {
3656: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3657:
1.168 albertel 3658: if (!$symb) {
3659: $symb=&symbread();
1.620 albertel 3660: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3661: }
3662: $symb=escape($symb);
3663:
1.620 albertel 3664: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3665:
1.620 albertel 3666: if (!$domain) { $domain=$env{'user.domain'}; }
3667: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3668: if ($domain eq 'public' && $stuname eq 'public') {
3669: $stuname=$ENV{'REMOTE_ADDR'};
3670: }
1.168 albertel 3671: my %returnhash;
3672: $namespace=~s/\//\_/g;
3673: $namespace=~s/\W//g;
3674: my %hash;
3675: my $path=$perlvar{'lonDaemons'}.'/tmp';
3676: if (tie(%hash,'GDBM_File',
3677: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3678: &GDBM_READER(),0640)) {
1.168 albertel 3679: my $version=$hash{"version:$symb"};
3680: $returnhash{'version'}=$version;
3681: my $scope;
3682: for ($scope=1;$scope<=$version;$scope++) {
3683: my $vkeys=$hash{"$scope:keys:$symb"};
3684: my @keys=split(/:/,$vkeys);
3685: my $key;
3686: $returnhash{"$scope:keys"}=$vkeys;
3687: foreach $key (@keys) {
1.591 albertel 3688: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3689: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3690: }
3691: }
1.168 albertel 3692: if (!(untie(%hash))) {
3693: return "error:$!";
3694: }
3695: } else {
3696: return "error:$!";
3697: }
3698: return %returnhash;
1.167 albertel 3699: }
3700:
1.9 www 3701: # ----------------------------------------------------------------------- Store
3702:
3703: sub store {
1.124 www 3704: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3705: my $home='';
3706:
1.168 albertel 3707: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3708:
1.213 www 3709: $symb=&symbclean($symb);
1.122 albertel 3710: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3711:
1.620 albertel 3712: if (!$domain) { $domain=$env{'user.domain'}; }
3713: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3714:
3715: &devalidate($symb,$stuname,$domain);
1.109 www 3716:
3717: $symb=escape($symb);
1.187 www 3718: if (!$namespace) {
1.620 albertel 3719: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3720: return '';
3721: }
3722: }
1.620 albertel 3723: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3724:
3725: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3726: $$storehash{'host'}=$perlvar{'lonHostID'};
3727:
1.12 www 3728: my $namevalue='';
1.800 albertel 3729: foreach my $key (keys(%$storehash)) {
3730: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3731: }
1.12 www 3732: $namevalue=~s/\&$//;
1.187 www 3733: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3734: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3735: }
3736:
1.47 www 3737: # -------------------------------------------------------------- Critical Store
3738:
3739: sub cstore {
1.124 www 3740: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3741: my $home='';
3742:
1.168 albertel 3743: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3744:
1.213 www 3745: $symb=&symbclean($symb);
1.122 albertel 3746: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3747:
1.620 albertel 3748: if (!$domain) { $domain=$env{'user.domain'}; }
3749: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3750:
3751: &devalidate($symb,$stuname,$domain);
1.109 www 3752:
3753: $symb=escape($symb);
1.187 www 3754: if (!$namespace) {
1.620 albertel 3755: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3756: return '';
3757: }
3758: }
1.620 albertel 3759: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3760:
3761: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3762: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3763:
1.47 www 3764: my $namevalue='';
1.800 albertel 3765: foreach my $key (keys(%$storehash)) {
3766: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3767: }
1.47 www 3768: $namevalue=~s/\&$//;
1.187 www 3769: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3770: return critical
3771: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3772: }
3773:
1.9 www 3774: # --------------------------------------------------------------------- Restore
3775:
3776: sub restore {
1.124 www 3777: my ($symb,$namespace,$domain,$stuname) = @_;
3778: my $home='';
3779:
1.168 albertel 3780: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3781:
1.122 albertel 3782: if (!$symb) {
3783: unless ($symb=escape(&symbread())) { return ''; }
3784: } else {
1.213 www 3785: $symb=&escape(&symbclean($symb));
1.122 albertel 3786: }
1.188 www 3787: if (!$namespace) {
1.620 albertel 3788: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3789: return '';
3790: }
3791: }
1.620 albertel 3792: if (!$domain) { $domain=$env{'user.domain'}; }
3793: if (!$stuname) { $stuname=$env{'user.name'}; }
3794: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3795: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3796:
1.12 www 3797: my %returnhash=();
1.800 albertel 3798: foreach my $line (split(/\&/,$answer)) {
3799: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3800: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3801: }
1.75 www 3802: my $version;
3803: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3804: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3805: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3806: }
1.75 www 3807: }
1.13 www 3808: return %returnhash;
1.34 www 3809: }
3810:
3811: # ---------------------------------------------------------- Course Description
3812:
3813: sub coursedescription {
1.731 albertel 3814: my ($courseid,$args)=@_;
1.34 www 3815: $courseid=~s/^\///;
1.49 www 3816: $courseid=~s/\_/\//g;
1.34 www 3817: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3818: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3819: my $normalid=$cdomain.'_'.$cnum;
3820: # need to always cache even if we get errors otherwise we keep
3821: # trying and trying and trying to get the course description.
3822: my %envhash=();
3823: my %returnhash=();
1.731 albertel 3824:
3825: my $expiretime=600;
3826: if ($env{'request.course.id'} eq $normalid) {
3827: $expiretime=120;
3828: }
3829:
3830: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3831: if (!$args->{'freshen_cache'}
3832: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3833: foreach my $key (keys(%env)) {
3834: next if ($key !~ /^\Q$prefix\E(.*)/);
3835: my ($setting) = $1;
3836: $returnhash{$setting} = $env{$key};
3837: }
3838: return %returnhash;
3839: }
3840:
3841: # get the data agin
3842: if (!$args->{'one_time'}) {
3843: $envhash{'course.'.$normalid.'.last_cache'}=time;
3844: }
1.811 albertel 3845:
1.34 www 3846: if ($chome ne 'no_host') {
1.302 albertel 3847: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3848: if (!exists($returnhash{'con_lost'})) {
3849: $returnhash{'home'}= $chome;
3850: $returnhash{'domain'} = $cdomain;
3851: $returnhash{'num'} = $cnum;
1.741 raeburn 3852: if (!defined($returnhash{'type'})) {
3853: $returnhash{'type'} = 'Course';
3854: }
1.130 albertel 3855: while (my ($name,$value) = each %returnhash) {
1.53 www 3856: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3857: }
1.270 www 3858: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3859: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3860: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3861: $envhash{'course.'.$normalid.'.home'}=$chome;
3862: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3863: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3864: }
3865: }
1.731 albertel 3866: if (!$args->{'one_time'}) {
1.949 raeburn 3867: &appenv(\%envhash);
1.731 albertel 3868: }
1.302 albertel 3869: return %returnhash;
1.461 www 3870: }
3871:
3872: # -------------------------------------------------See if a user is privileged
3873:
3874: sub privileged {
3875: my ($username,$domain)=@_;
3876: my $rolesdump=&reply("dump:$domain:$username:roles",
3877: &homeserver($username,$domain));
1.1033 raeburn 3878: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3879: ($rolesdump =~ /^error:/)) {
3880: return 0;
3881: }
1.461 www 3882: my $now=time;
3883: if ($rolesdump ne '') {
1.800 albertel 3884: foreach my $entry (split(/&/,$rolesdump)) {
3885: if ($entry!~/^rolesdef_/) {
3886: my ($area,$role)=split(/=/,$entry);
1.461 www 3887: $area=~s/\_\w\w$//;
3888: my ($trole,$tend,$tstart)=split(/_/,$role);
3889: if (($trole eq 'dc') || ($trole eq 'su')) {
3890: my $active=1;
3891: if ($tend) {
3892: if ($tend<$now) { $active=0; }
3893: }
3894: if ($tstart) {
3895: if ($tstart>$now) { $active=0; }
3896: }
3897: if ($active) { return 1; }
3898: }
3899: }
3900: }
3901: }
3902: return 0;
1.9 www 3903: }
1.1 albertel 3904:
1.103 harris41 3905: # -------------------------------------------------------- Get user privileges
1.11 www 3906:
3907: sub rolesinit {
3908: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3909: my $now=time;
3910: my %userroles = ('user.login.time' => $now);
1.11 www 3911: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3912: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3913: ($rolesdump =~ /^error:/)) {
3914: return \%userroles;
3915: }
1.11 www 3916: my %allroles=();
1.678 raeburn 3917: my %allgroups=();
3918: my $group_privs;
1.11 www 3919:
3920: if ($rolesdump ne '') {
1.800 albertel 3921: foreach my $entry (split(/&/,$rolesdump)) {
3922: if ($entry!~/^rolesdef_/) {
3923: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3924: $area=~s/\_\w\w$//;
1.678 raeburn 3925: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3926: if ($role=~/^cr/) {
1.807 albertel 3927: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3928: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3929: ($tend,$tstart)=split('_',$trest);
3930: } else {
3931: $trole=$role;
3932: }
1.678 raeburn 3933: } elsif ($role =~ m|^gr/|) {
3934: ($trole,$tend,$tstart) = split(/_/,$role);
3935: ($trole,$group_privs) = split(/\//,$trole);
3936: $group_privs = &unescape($group_privs);
1.587 albertel 3937: } else {
3938: ($trole,$tend,$tstart)=split(/_/,$role);
3939: }
1.743 albertel 3940: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3941: $username);
3942: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3943: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3944: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3945: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3946: my $spec=$trole.'.'.$area;
3947: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3948: if ($trole =~ /^cr\//) {
1.567 raeburn 3949: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3950: } elsif ($trole eq 'gr') {
3951: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3952: } else {
1.567 raeburn 3953: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3954: }
1.12 www 3955: }
1.662 raeburn 3956: }
1.191 harris41 3957: }
1.743 albertel 3958: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3959: $userroles{'user.adv'} = $adv;
3960: $userroles{'user.author'} = $author;
1.620 albertel 3961: $env{'user.adv'}=$adv;
1.11 www 3962: }
1.743 albertel 3963: return \%userroles;
1.11 www 3964: }
3965:
1.567 raeburn 3966: sub set_arearole {
3967: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3968: # log the associated role with the area
3969: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3970: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3971: }
3972:
3973: sub custom_roleprivs {
3974: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3975: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3976: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3977: if (&hostname($homsvr) ne '') {
1.567 raeburn 3978: my ($rdummy,$roledef)=
3979: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3980: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3981: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3982: if (defined($syspriv)) {
1.1043 raeburn 3983: if ($trest =~ /^$match_community$/) {
3984: $syspriv =~ s/bre\&S//;
3985: }
1.567 raeburn 3986: $$allroles{'cm./'}.=':'.$syspriv;
3987: $$allroles{$spec.'./'}.=':'.$syspriv;
3988: }
3989: if ($tdomain ne '') {
3990: if (defined($dompriv)) {
3991: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3992: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3993: }
3994: if (($trest ne '') && (defined($coursepriv))) {
3995: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3996: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3997: }
3998: }
3999: }
4000: }
4001: }
4002:
1.678 raeburn 4003: sub group_roleprivs {
4004: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4005: my $access = 1;
4006: my $now = time;
4007: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4008: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4009: if ($access) {
1.811 albertel 4010: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4011: $$allgroups{$course}{$group} .=':'.$group_privs;
4012: }
4013: }
1.567 raeburn 4014:
4015: sub standard_roleprivs {
4016: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4017: if (defined($pr{$trole.':s'})) {
4018: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4019: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4020: }
4021: if ($tdomain ne '') {
4022: if (defined($pr{$trole.':d'})) {
4023: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4024: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4025: }
4026: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4027: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4028: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4029: }
4030: }
4031: }
4032:
4033: sub set_userprivs {
1.1056.2.3 raeburn 4034: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4035: my $author=0;
4036: my $adv=0;
1.678 raeburn 4037: my %grouproles = ();
4038: if (keys(%{$allgroups}) > 0) {
1.1056.2.3 raeburn 4039: my @groupkeys;
1.1000 raeburn 4040: foreach my $role (keys(%{$allroles})) {
1.1056.2.3 raeburn 4041: push(@groupkeys,$role);
4042: }
4043: if (ref($groups_roles) eq 'HASH') {
4044: foreach my $key (keys(%{$groups_roles})) {
4045: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4046: push(@groupkeys,$key);
4047: }
4048: }
4049: }
4050: if (@groupkeys > 0) {
4051: foreach my $role (@groupkeys) {
4052: my ($trole,$area,$sec,$extendedarea);
4053: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4054: $trole = $1;
4055: $area = $2;
4056: $sec = $3;
4057: $extendedarea = $area.$sec;
4058: if (exists($$allgroups{$area})) {
4059: foreach my $group (keys(%{$$allgroups{$area}})) {
4060: my $spec = $trole.'.'.$extendedarea;
4061: $grouproles{$spec.'.'.$area.'/'.$group} =
4062: $$allgroups{$area}{$group};
4063: }
1.678 raeburn 4064: }
4065: }
4066: }
4067: }
4068: }
1.800 albertel 4069: foreach my $group (keys(%grouproles)) {
4070: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4071: }
1.800 albertel 4072: foreach my $role (keys(%{$allroles})) {
4073: my %thesepriv;
1.941 raeburn 4074: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4075: foreach my $item (split(/:/,$$allroles{$role})) {
4076: if ($item ne '') {
4077: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4078: if ($restrictions eq '') {
4079: $thesepriv{$privilege}='F';
4080: } elsif ($thesepriv{$privilege} ne 'F') {
4081: $thesepriv{$privilege}.=$restrictions;
4082: }
4083: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4084: }
4085: }
4086: my $thesestr='';
1.800 albertel 4087: foreach my $priv (keys(%thesepriv)) {
4088: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4089: }
4090: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4091: }
4092: return ($author,$adv);
4093: }
4094:
1.994 raeburn 4095: sub role_status {
1.1002 raeburn 4096: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4097: my @pwhere = ();
4098: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4099: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4100: unless (!defined($$role) || $$role eq '') {
4101: $$where=join('.',@pwhere);
4102: $$trolecode=$$role.'.'.$$where;
4103: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4104: $$tstatus='is';
4105: if ($$tstart && $$tstart>$then) {
4106: $$tstatus='future';
1.1034 raeburn 4107: if ($$tstart<$now) {
4108: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4109: if (($$where ne '') && ($$role ne '')) {
1.1056.2.3 raeburn 4110: my (%allroles,%allgroups,$group_privs,
4111: %groups_roles,@rolecodes);
1.1002 raeburn 4112: my %userroles = (
4113: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4114: );
1.1056.2.3 raeburn 4115: @rolecodes = ('cm');
1.1002 raeburn 4116: my $spec=$$role.'.'.$$where;
4117: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4118: if ($$role =~ /^cr\//) {
4119: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.2.3 raeburn 4120: push(@rolecodes,'cr');
1.1002 raeburn 4121: } elsif ($$role eq 'gr') {
1.1056.2.3 raeburn 4122: push(@rolecodes,$$role);
1.1002 raeburn 4123: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4124: $env{'user.name'});
1.1056.2.3 raeburn 4125: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4126: (undef,my $group_privs) = split(/\//,$trole);
4127: $group_privs = &unescape($group_privs);
4128: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.2.3 raeburn 4129: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4130: if (keys(%course_roles) > 0) {
4131: my ($tnum) = ($trest =~ /^($match_courseid)/);
4132: if ($tdomain ne '' && $tnum ne '') {
4133: foreach my $key (keys(%course_roles)) {
4134: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4135: my $crsrole = $1;
4136: my $crssec = $2;
4137: if ($crsrole =~ /^cr/) {
4138: unless (grep(/^cr$/,@rolecodes)) {
4139: push(@rolecodes,'cr');
4140: }
4141: } else {
4142: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4143: push(@rolecodes,$crsrole);
4144: }
4145: }
4146: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4147: if ($crssec ne '') {
4148: $rolekey .= '/'.$crssec;
4149: }
4150: $rolekey .= './';
4151: $groups_roles{$rolekey} = \@rolecodes;
4152: }
4153: }
4154: }
4155: }
1.1002 raeburn 4156: } else {
1.1056.2.3 raeburn 4157: push(@rolecodes,$$role);
1.1002 raeburn 4158: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4159: }
1.1056.2.3 raeburn 4160: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4161: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4162: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4163: }
4164: }
1.1034 raeburn 4165: $$tstatus = 'is';
1.1002 raeburn 4166: }
1.994 raeburn 4167: }
4168: if ($$tend) {
4169: if ($$tend<$then) {
4170: $$tstatus='expired';
4171: } elsif ($$tend<$now) {
4172: $$tstatus='will_not';
4173: }
4174: }
4175: }
4176: }
4177: }
4178:
4179: sub check_adhoc_privs {
1.1056.2.8 raeburn 4180: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4181: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4182: if ($env{$cckey}) {
4183: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4184: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4185: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.2.8 raeburn 4186: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4187: }
4188: } else {
1.1056.2.8 raeburn 4189: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4190: }
4191: }
4192:
4193: sub set_adhoc_privileges {
4194: # role can be cc or ca
1.1056.2.8 raeburn 4195: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4196: my $area = '/'.$dcdom.'/'.$pickedcourse;
4197: my $spec = $role.'.'.$area;
4198: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4199: $env{'user.name'});
4200: my %ccrole = ();
4201: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4202: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4203: &appenv(\%userroles,[$role,'cm']);
4204: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.2.8 raeburn 4205: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4206: &appenv( {'request.role' => $spec,
4207: 'request.role.domain' => $dcdom,
4208: 'request.course.sec' => ''
4209: }
4210: );
4211: my $tadv=0;
4212: if (&allowed('adv') eq 'F') { $tadv=1; }
4213: &appenv({'request.role.adv' => $tadv});
4214: }
1.994 raeburn 4215: }
4216:
1.12 www 4217: # --------------------------------------------------------------- get interface
4218:
4219: sub get {
1.131 albertel 4220: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4221: my $items='';
1.800 albertel 4222: foreach my $item (@$storearr) {
4223: $items.=&escape($item).'&';
1.191 harris41 4224: }
1.12 www 4225: $items=~s/\&$//;
1.620 albertel 4226: if (!$udomain) { $udomain=$env{'user.domain'}; }
4227: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4228: my $uhome=&homeserver($uname,$udomain);
4229:
1.133 albertel 4230: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4231: my @pairs=split(/\&/,$rep);
1.273 albertel 4232: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4233: return @pairs;
4234: }
1.15 www 4235: my %returnhash=();
1.42 www 4236: my $i=0;
1.800 albertel 4237: foreach my $item (@$storearr) {
4238: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4239: $i++;
1.191 harris41 4240: }
1.15 www 4241: return %returnhash;
1.27 www 4242: }
4243:
4244: # --------------------------------------------------------------- del interface
4245:
4246: sub del {
1.133 albertel 4247: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4248: my $items='';
1.800 albertel 4249: foreach my $item (@$storearr) {
4250: $items.=&escape($item).'&';
1.191 harris41 4251: }
1.984 neumanie 4252:
1.27 www 4253: $items=~s/\&$//;
1.620 albertel 4254: if (!$udomain) { $udomain=$env{'user.domain'}; }
4255: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4256: my $uhome=&homeserver($uname,$udomain);
4257: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4258: }
4259:
4260: # -------------------------------------------------------------- dump interface
4261:
4262: sub dump {
1.1056.2.9 raeburn 4263: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4264: if (!$udomain) { $udomain=$env{'user.domain'}; }
4265: if (!$uname) { $uname=$env{'user.name'}; }
4266: my $uhome=&homeserver($uname,$udomain);
4267: if ($regexp) {
4268: $regexp=&escape($regexp);
4269: } else {
4270: $regexp='.';
4271: }
1.1056.2.9 raeburn 4272: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4273: my @pairs=split(/\&/,$rep);
4274: my %returnhash=();
4275: foreach my $item (@pairs) {
4276: my ($key,$value)=split(/=/,$item,2);
4277: $key = &unescape($key);
4278: next if ($key =~ /^error: 2 /);
4279: $returnhash{$key}=&thaw_unescape($value);
4280: }
4281: return %returnhash;
1.407 www 4282: }
4283:
1.717 albertel 4284: # --------------------------------------------------------- dumpstore interface
4285:
4286: sub dumpstore {
4287: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4288: if (!$udomain) { $udomain=$env{'user.domain'}; }
4289: if (!$uname) { $uname=$env{'user.name'}; }
4290: my $uhome=&homeserver($uname,$udomain);
4291: if ($regexp) {
4292: $regexp=&escape($regexp);
4293: } else {
4294: $regexp='.';
4295: }
4296: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4297: my @pairs=split(/\&/,$rep);
4298: my %returnhash=();
4299: foreach my $item (@pairs) {
4300: my ($key,$value)=split(/=/,$item,2);
4301: next if ($key =~ /^error: 2 /);
4302: $returnhash{$key}=&thaw_unescape($value);
4303: }
4304: return %returnhash;
1.717 albertel 4305: }
4306:
1.407 www 4307: # -------------------------------------------------------------- keys interface
4308:
4309: sub getkeys {
4310: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4311: if (!$udomain) { $udomain=$env{'user.domain'}; }
4312: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4313: my $uhome=&homeserver($uname,$udomain);
4314: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4315: my @keyarray=();
1.800 albertel 4316: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4317: next if ($key =~ /^error: 2 /);
1.800 albertel 4318: push(@keyarray,&unescape($key));
1.407 www 4319: }
4320: return @keyarray;
1.318 matthew 4321: }
4322:
1.319 matthew 4323: # --------------------------------------------------------------- currentdump
4324: sub currentdump {
1.328 matthew 4325: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4326: $courseid = $env{'request.course.id'} if (! defined($courseid));
4327: $sdom = $env{'user.domain'} if (! defined($sdom));
4328: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4329: my $uhome = &homeserver($sname,$sdom);
4330: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4331: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4332: #
1.318 matthew 4333: my %returnhash=();
1.319 matthew 4334: #
4335: if ($rep eq "unknown_cmd") {
4336: # an old lond will not know currentdump
4337: # Do a dump and make it look like a currentdump
1.822 albertel 4338: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4339: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4340: my %hash = @tmp;
4341: @tmp=();
1.424 matthew 4342: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4343: } else {
4344: my @pairs=split(/\&/,$rep);
1.800 albertel 4345: foreach my $pair (@pairs) {
4346: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4347: my ($symb,$param) = split(/:/,$key);
4348: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4349: &thaw_unescape($value);
1.319 matthew 4350: }
1.191 harris41 4351: }
1.12 www 4352: return %returnhash;
1.424 matthew 4353: }
4354:
4355: sub convert_dump_to_currentdump{
4356: my %hash = %{shift()};
4357: my %returnhash;
4358: # Code ripped from lond, essentially. The only difference
4359: # here is the unescaping done by lonnet::dump(). Conceivably
4360: # we might run in to problems with parameter names =~ /^v\./
4361: while (my ($key,$value) = each(%hash)) {
4362: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4363: $symb = &unescape($symb);
4364: $param = &unescape($param);
1.424 matthew 4365: next if ($v eq 'version' || $symb eq 'keys');
4366: next if (exists($returnhash{$symb}) &&
4367: exists($returnhash{$symb}->{$param}) &&
4368: $returnhash{$symb}->{'v.'.$param} > $v);
4369: $returnhash{$symb}->{$param}=$value;
4370: $returnhash{$symb}->{'v.'.$param}=$v;
4371: }
4372: #
4373: # Remove all of the keys in the hashes which keep track of
4374: # the version of the parameter.
4375: while (my ($symb,$param_hash) = each(%returnhash)) {
4376: # use a foreach because we are going to delete from the hash.
4377: foreach my $key (keys(%$param_hash)) {
4378: delete($param_hash->{$key}) if ($key =~ /^v\./);
4379: }
4380: }
4381: return \%returnhash;
1.12 www 4382: }
4383:
1.627 albertel 4384: # ------------------------------------------------------ critical inc interface
4385:
4386: sub cinc {
4387: return &inc(@_,'critical');
4388: }
4389:
1.449 matthew 4390: # --------------------------------------------------------------- inc interface
4391:
4392: sub inc {
1.627 albertel 4393: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4394: if (!$udomain) { $udomain=$env{'user.domain'}; }
4395: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4396: my $uhome=&homeserver($uname,$udomain);
4397: my $items='';
4398: if (! ref($store)) {
4399: # got a single value, so use that instead
4400: $items = &escape($store).'=&';
4401: } elsif (ref($store) eq 'SCALAR') {
4402: $items = &escape($$store).'=&';
4403: } elsif (ref($store) eq 'ARRAY') {
4404: $items = join('=&',map {&escape($_);} @{$store});
4405: } elsif (ref($store) eq 'HASH') {
4406: while (my($key,$value) = each(%{$store})) {
4407: $items.= &escape($key).'='.&escape($value).'&';
4408: }
4409: }
4410: $items=~s/\&$//;
1.627 albertel 4411: if ($critical) {
4412: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4413: } else {
4414: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4415: }
1.449 matthew 4416: }
4417:
1.12 www 4418: # --------------------------------------------------------------- put interface
4419:
4420: sub put {
1.134 albertel 4421: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4422: if (!$udomain) { $udomain=$env{'user.domain'}; }
4423: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4424: my $uhome=&homeserver($uname,$udomain);
1.12 www 4425: my $items='';
1.800 albertel 4426: foreach my $item (keys(%$storehash)) {
4427: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4428: }
1.12 www 4429: $items=~s/\&$//;
1.134 albertel 4430: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4431: }
4432:
1.631 albertel 4433: # ------------------------------------------------------------ newput interface
4434:
4435: sub newput {
4436: my ($namespace,$storehash,$udomain,$uname)=@_;
4437: if (!$udomain) { $udomain=$env{'user.domain'}; }
4438: if (!$uname) { $uname=$env{'user.name'}; }
4439: my $uhome=&homeserver($uname,$udomain);
4440: my $items='';
4441: foreach my $key (keys(%$storehash)) {
4442: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4443: }
4444: $items=~s/\&$//;
4445: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4446: }
4447:
4448: # --------------------------------------------------------- putstore interface
4449:
1.524 raeburn 4450: sub putstore {
1.715 albertel 4451: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4452: if (!$udomain) { $udomain=$env{'user.domain'}; }
4453: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4454: my $uhome=&homeserver($uname,$udomain);
4455: my $items='';
1.715 albertel 4456: foreach my $key (keys(%$storehash)) {
4457: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4458: }
1.715 albertel 4459: $items=~s/\&$//;
1.716 albertel 4460: my $esc_symb=&escape($symb);
4461: my $esc_v=&escape($version);
1.715 albertel 4462: my $reply =
1.716 albertel 4463: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4464: $uhome);
4465: if ($reply eq 'unknown_cmd') {
1.716 albertel 4466: # gfall back to way things use to be done
1.715 albertel 4467: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4468: $uname);
1.524 raeburn 4469: }
1.715 albertel 4470: return $reply;
4471: }
4472:
4473: sub old_putstore {
1.716 albertel 4474: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4475: if (!$udomain) { $udomain=$env{'user.domain'}; }
4476: if (!$uname) { $uname=$env{'user.name'}; }
4477: my $uhome=&homeserver($uname,$udomain);
4478: my %newstorehash;
1.800 albertel 4479: foreach my $item (keys(%$storehash)) {
4480: my $key = $version.':'.&escape($symb).':'.$item;
4481: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4482: }
4483: my $items='';
4484: my %allitems = ();
1.800 albertel 4485: foreach my $item (keys(%newstorehash)) {
4486: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4487: my $key = $1.':keys:'.$2;
4488: $allitems{$key} .= $3.':';
4489: }
1.800 albertel 4490: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4491: }
1.800 albertel 4492: foreach my $item (keys(%allitems)) {
4493: $allitems{$item} =~ s/\:$//;
4494: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4495: }
4496: $items=~s/\&$//;
4497: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4498: }
4499:
1.47 www 4500: # ------------------------------------------------------ critical put interface
4501:
4502: sub cput {
1.134 albertel 4503: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4504: if (!$udomain) { $udomain=$env{'user.domain'}; }
4505: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4506: my $uhome=&homeserver($uname,$udomain);
1.47 www 4507: my $items='';
1.800 albertel 4508: foreach my $item (keys(%$storehash)) {
4509: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4510: }
1.47 www 4511: $items=~s/\&$//;
1.134 albertel 4512: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4513: }
4514:
4515: # -------------------------------------------------------------- eget interface
4516:
4517: sub eget {
1.133 albertel 4518: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4519: my $items='';
1.800 albertel 4520: foreach my $item (@$storearr) {
4521: $items.=&escape($item).'&';
1.191 harris41 4522: }
1.12 www 4523: $items=~s/\&$//;
1.620 albertel 4524: if (!$udomain) { $udomain=$env{'user.domain'}; }
4525: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4526: my $uhome=&homeserver($uname,$udomain);
4527: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4528: my @pairs=split(/\&/,$rep);
4529: my %returnhash=();
1.42 www 4530: my $i=0;
1.800 albertel 4531: foreach my $item (@$storearr) {
4532: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4533: $i++;
1.191 harris41 4534: }
1.12 www 4535: return %returnhash;
4536: }
4537:
1.667 albertel 4538: # ------------------------------------------------------------ tmpput interface
4539: sub tmpput {
1.802 raeburn 4540: my ($storehash,$server,$context)=@_;
1.667 albertel 4541: my $items='';
1.800 albertel 4542: foreach my $item (keys(%$storehash)) {
4543: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4544: }
4545: $items=~s/\&$//;
1.802 raeburn 4546: if (defined($context)) {
4547: $items .= ':'.&escape($context);
4548: }
1.667 albertel 4549: return &reply("tmpput:$items",$server);
4550: }
4551:
4552: # ------------------------------------------------------------ tmpget interface
4553: sub tmpget {
1.688 albertel 4554: my ($token,$server)=@_;
4555: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4556: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4557: my %returnhash;
4558: foreach my $item (split(/\&/,$rep)) {
4559: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4560: next if ($key =~ /^error: 2 /);
1.667 albertel 4561: $returnhash{&unescape($key)}=&thaw_unescape($value);
4562: }
4563: return %returnhash;
4564: }
4565:
1.688 albertel 4566: # ------------------------------------------------------------ tmpget interface
4567: sub tmpdel {
4568: my ($token,$server)=@_;
4569: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4570: return &reply("tmpdel:$token",$server);
4571: }
4572:
1.765 albertel 4573: # -------------------------------------------------- portfolio access checking
4574:
4575: sub portfolio_access {
1.766 albertel 4576: my ($requrl) = @_;
1.765 albertel 4577: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4578: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4579: if ($result) {
4580: my %setters;
4581: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4582: my ($startblock,$endblock) =
4583: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4584: if ($startblock && $endblock) {
4585: return 'B';
4586: }
4587: } else {
4588: my ($startblock,$endblock) =
4589: &Apache::loncommon::blockcheck(\%setters,'port');
4590: if ($startblock && $endblock) {
4591: return 'B';
4592: }
4593: }
4594: }
1.765 albertel 4595: if ($result eq 'ok') {
1.766 albertel 4596: return 'F';
1.765 albertel 4597: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4598: return 'A';
1.765 albertel 4599: }
1.766 albertel 4600: return '';
1.765 albertel 4601: }
4602:
4603: sub get_portfolio_access {
1.767 albertel 4604: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4605:
4606: if (!ref($access_hash)) {
4607: my $current_perms = &get_portfile_permissions($udom,$unum);
4608: my %access_controls = &get_access_controls($current_perms,$group,
4609: $file_name);
4610: $access_hash = $access_controls{$file_name};
4611: }
4612:
1.765 albertel 4613: my ($public,$guest,@domains,@users,@courses,@groups);
4614: my $now = time;
4615: if (ref($access_hash) eq 'HASH') {
4616: foreach my $key (keys(%{$access_hash})) {
4617: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4618: if ($start > $now) {
4619: next;
4620: }
4621: if ($end && $end<$now) {
4622: next;
4623: }
4624: if ($scope eq 'public') {
4625: $public = $key;
4626: last;
4627: } elsif ($scope eq 'guest') {
4628: $guest = $key;
4629: } elsif ($scope eq 'domains') {
4630: push(@domains,$key);
4631: } elsif ($scope eq 'users') {
4632: push(@users,$key);
4633: } elsif ($scope eq 'course') {
4634: push(@courses,$key);
4635: } elsif ($scope eq 'group') {
4636: push(@groups,$key);
4637: }
4638: }
4639: if ($public) {
4640: return 'ok';
4641: }
4642: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4643: if ($guest) {
4644: return $guest;
4645: }
4646: } else {
4647: if (@domains > 0) {
4648: foreach my $domkey (@domains) {
4649: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4650: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4651: return 'ok';
4652: }
4653: }
4654: }
4655: }
4656: if (@users > 0) {
4657: foreach my $userkey (@users) {
1.865 raeburn 4658: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4659: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4660: if (ref($item) eq 'HASH') {
4661: if (($item->{'uname'} eq $env{'user.name'}) &&
4662: ($item->{'udom'} eq $env{'user.domain'})) {
4663: return 'ok';
4664: }
4665: }
4666: }
4667: }
1.765 albertel 4668: }
4669: }
4670: my %roleshash;
4671: my @courses_and_groups = @courses;
4672: push(@courses_and_groups,@groups);
4673: if (@courses_and_groups > 0) {
4674: my (%allgroups,%allroles);
4675: my ($start,$end,$role,$sec,$group);
4676: foreach my $envkey (%env) {
1.1056.2.2 raeburn 4677: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4678: my $cid = $2.'_'.$3;
4679: if ($1 eq 'gr') {
4680: $group = $4;
4681: $allgroups{$cid}{$group} = $env{$envkey};
4682: } else {
4683: if ($4 eq '') {
4684: $sec = 'none';
4685: } else {
4686: $sec = $4;
4687: }
4688: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4689: }
1.811 albertel 4690: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4691: my $cid = $2.'_'.$3;
4692: if ($4 eq '') {
4693: $sec = 'none';
4694: } else {
4695: $sec = $4;
4696: }
4697: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4698: }
4699: }
4700: if (keys(%allroles) == 0) {
4701: return;
4702: }
4703: foreach my $key (@courses_and_groups) {
4704: my %content = %{$$access_hash{$key}};
4705: my $cnum = $content{'number'};
4706: my $cdom = $content{'domain'};
4707: my $cid = $cdom.'_'.$cnum;
4708: if (!exists($allroles{$cid})) {
4709: next;
4710: }
4711: foreach my $role_id (keys(%{$content{'roles'}})) {
4712: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4713: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4714: my @status = @{$content{'roles'}{$role_id}{'access'}};
4715: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4716: foreach my $role (keys(%{$allroles{$cid}})) {
4717: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4718: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4719: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4720: if (grep/^all$/,@sections) {
4721: return 'ok';
4722: } else {
4723: if (grep/^$sec$/,@sections) {
4724: return 'ok';
4725: }
4726: }
4727: }
4728: }
4729: if (keys(%{$allgroups{$cid}}) == 0) {
4730: if (grep/^none$/,@groups) {
4731: return 'ok';
4732: }
4733: } else {
4734: if (grep/^all$/,@groups) {
4735: return 'ok';
4736: }
4737: foreach my $group (keys(%{$allgroups{$cid}})) {
4738: if (grep/^$group$/,@groups) {
4739: return 'ok';
4740: }
4741: }
4742: }
4743: }
4744: }
4745: }
4746: }
4747: }
4748: if ($guest) {
4749: return $guest;
4750: }
4751: }
4752: }
4753: return;
4754: }
4755:
4756: sub course_group_datechecker {
4757: my ($dates,$now,$status) = @_;
4758: my ($start,$end) = split(/\./,$dates);
4759: if (!$start && !$end) {
4760: return 'ok';
4761: }
4762: if (grep/^active$/,@{$status}) {
4763: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4764: return 'ok';
4765: }
4766: }
4767: if (grep/^previous$/,@{$status}) {
4768: if ($end > $now ) {
4769: return 'ok';
4770: }
4771: }
4772: if (grep/^future$/,@{$status}) {
4773: if ($start > $now) {
4774: return 'ok';
4775: }
4776: }
4777: return;
4778: }
4779:
4780: sub parse_portfolio_url {
4781: my ($url) = @_;
4782:
4783: my ($type,$udom,$unum,$group,$file_name);
4784:
1.823 albertel 4785: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4786: $type = 1;
4787: $udom = $1;
4788: $unum = $2;
4789: $file_name = $3;
1.823 albertel 4790: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4791: $type = 2;
4792: $udom = $1;
4793: $unum = $2;
4794: $group = $3;
4795: $file_name = $3.'/'.$4;
4796: }
4797: if (wantarray) {
4798: return ($type,$udom,$unum,$file_name,$group);
4799: }
4800: return $type;
4801: }
4802:
4803: sub is_portfolio_url {
4804: my ($url) = @_;
4805: return scalar(&parse_portfolio_url($url));
4806: }
4807:
1.798 raeburn 4808: sub is_portfolio_file {
4809: my ($file) = @_;
1.820 raeburn 4810: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4811: return 1;
4812: }
4813: return;
4814: }
4815:
1.976 raeburn 4816: sub usertools_access {
1.985 raeburn 4817: my ($uname,$udom,$tool,$action,$context) = @_;
4818: my ($access,%tools);
4819: if ($context eq '') {
4820: $context = 'tools';
4821: }
4822: if ($context eq 'requestcourses') {
4823: %tools = (
4824: official => 1,
4825: unofficial => 1,
1.1006 raeburn 4826: community => 1,
1.985 raeburn 4827: );
4828: } else {
4829: %tools = (
4830: aboutme => 1,
4831: blog => 1,
4832: portfolio => 1,
4833: );
4834: }
1.976 raeburn 4835: return if (!defined($tools{$tool}));
4836:
4837: if ((!defined($udom)) || (!defined($uname))) {
4838: $udom = $env{'user.domain'};
4839: $uname = $env{'user.name'};
4840: }
4841:
1.978 raeburn 4842: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4843: if ($action ne 'reload') {
1.985 raeburn 4844: if ($context eq 'requestcourses') {
4845: return $env{'environment.canrequest.'.$tool};
4846: } else {
4847: return $env{'environment.availabletools.'.$tool};
4848: }
4849: }
1.976 raeburn 4850: }
4851:
4852: my ($toolstatus,$inststatus);
4853:
1.985 raeburn 4854: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4855: ($action ne 'reload')) {
4856: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4857: $inststatus = $env{'environment.inststatus'};
4858: } else {
1.1025 raeburn 4859: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4860: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4861: $inststatus = $userenv{'inststatus'};
4862: }
4863:
4864: if ($toolstatus ne '') {
4865: if ($toolstatus) {
4866: $access = 1;
4867: } else {
4868: $access = 0;
4869: }
4870: return $access;
4871: }
4872:
4873: my $is_adv = &is_advanced_user($udom,$uname);
4874: my %domdef = &get_domain_defaults($udom);
4875: if (ref($domdef{$tool}) eq 'HASH') {
4876: if ($is_adv) {
4877: if ($domdef{$tool}{'_LC_adv'} ne '') {
4878: if ($domdef{$tool}{'_LC_adv'}) {
4879: $access = 1;
4880: } else {
4881: $access = 0;
4882: }
4883: return $access;
4884: }
4885: }
4886: if ($inststatus ne '') {
4887: my ($hasaccess,$hasnoaccess);
4888: foreach my $affiliation (split(/:/,$inststatus)) {
4889: if ($domdef{$tool}{$affiliation} ne '') {
4890: if ($domdef{$tool}{$affiliation}) {
4891: $hasaccess = 1;
4892: } else {
4893: $hasnoaccess = 1;
4894: }
4895: }
4896: }
4897: if ($hasaccess || $hasnoaccess) {
4898: if ($hasaccess) {
4899: $access = 1;
4900: } elsif ($hasnoaccess) {
4901: $access = 0;
4902: }
4903: return $access;
4904: }
4905: } else {
4906: if ($domdef{$tool}{'default'} ne '') {
4907: if ($domdef{$tool}{'default'}) {
4908: $access = 1;
4909: } elsif ($domdef{$tool}{'default'} == 0) {
4910: $access = 0;
4911: }
4912: return $access;
4913: }
4914: }
4915: } else {
1.985 raeburn 4916: if ($context eq 'tools') {
4917: $access = 1;
4918: } else {
4919: $access = 0;
4920: }
1.976 raeburn 4921: return $access;
4922: }
4923: }
4924:
1.1050 raeburn 4925: sub is_course_owner {
4926: my ($cdom,$cnum,$udom,$uname) = @_;
4927: if (($udom eq '') || ($uname eq '')) {
4928: $udom = $env{'user.domain'};
4929: $uname = $env{'user.name'};
4930: }
4931: unless (($udom eq '') || ($uname eq '')) {
4932: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4933: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4934: return 1;
4935: } else {
4936: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4937: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4938: return 1;
4939: }
4940: }
4941: }
4942: }
4943: return;
4944: }
4945:
1.976 raeburn 4946: sub is_advanced_user {
4947: my ($udom,$uname) = @_;
1.1056.2.9 raeburn 4948: if ($udom ne '' && $uname ne '') {
4949: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4950: return $env{'user.adv'};
4951: }
4952: }
1.976 raeburn 4953: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4954: my %allroles;
4955: my $is_adv;
4956: foreach my $role (keys(%roleshash)) {
4957: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4958: my $area = '/'.$tdomain.'/'.$trest;
4959: if ($sec ne '') {
4960: $area .= '/'.$sec;
4961: }
4962: if (($area ne '') && ($trole ne '')) {
4963: my $spec=$trole.'.'.$area;
4964: if ($trole =~ /^cr\//) {
4965: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4966: } elsif ($trole ne 'gr') {
4967: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4968: }
4969: }
4970: }
4971: foreach my $role (keys(%allroles)) {
4972: last if ($is_adv);
4973: foreach my $item (split(/:/,$allroles{$role})) {
4974: if ($item ne '') {
4975: my ($privilege,$restrictions)=split(/&/,$item);
4976: if ($privilege eq 'adv') {
4977: $is_adv = 1;
4978: last;
4979: }
4980: }
4981: }
4982: }
4983: return $is_adv;
4984: }
1.798 raeburn 4985:
1.1035 raeburn 4986: sub check_can_request {
1.1036 raeburn 4987: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 4988: my $canreq = 0;
4989: my ($types,$typename) = &Apache::loncommon::course_types();
4990: my @options = ('approval','validate','autolimit');
4991: my $optregex = join('|',@options);
4992: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4993: foreach my $type (@{$types}) {
4994: if (&usertools_access($env{'user.name'},
4995: $env{'user.domain'},
4996: $type,undef,'requestcourses')) {
4997: $canreq ++;
1.1036 raeburn 4998: if (ref($request_domains) eq 'HASH') {
4999: push(@{$request_domains->{$type}},$env{'user.domain'});
5000: }
1.1035 raeburn 5001: if ($dom eq $env{'user.domain'}) {
5002: $can_request->{$type} = 1;
5003: }
5004: }
5005: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5006: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5007: if (@curr > 0) {
1.1036 raeburn 5008: foreach my $item (@curr) {
5009: if (ref($request_domains) eq 'HASH') {
5010: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5011: if ($otherdom ne '') {
5012: if (ref($request_domains->{$type}) eq 'ARRAY') {
5013: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5014: push(@{$request_domains->{$type}},$otherdom);
5015: }
5016: } else {
5017: push(@{$request_domains->{$type}},$otherdom);
5018: }
5019: }
5020: }
5021: }
5022: unless($dom eq $env{'user.domain'}) {
5023: $canreq ++;
1.1035 raeburn 5024: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5025: $can_request->{$type} = 1;
5026: }
5027: }
5028: }
5029: }
5030: }
5031: }
5032: return $canreq;
5033: }
5034:
1.341 www 5035: # ---------------------------------------------- Custom access rule evaluation
5036:
5037: sub customaccess {
5038: my ($priv,$uri)=@_;
1.807 albertel 5039: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5040: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5041: $udom = &LONCAPA::clean_domain($udom);
5042: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5043: my $access=0;
1.800 albertel 5044: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5045: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5046: if ($type eq 'user') {
5047: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5048: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5049: if ($tdom) {
5050: if ($tdom ne $env{'user.domain'}) { next; }
5051: }
1.896 albertel 5052: if ($tuname) {
5053: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5054: }
5055: $access=($effect eq 'allow');
5056: last;
5057: }
5058: } else {
5059: if ($role) {
5060: if ($role ne $urole) { next; }
5061: }
5062: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5063: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5064: if ($tdom) {
5065: if ($tdom ne $udom) { next; }
5066: }
5067: if ($tcrs) {
5068: if ($tcrs ne $ucrs) { next; }
5069: }
5070: if ($tsec) {
5071: if ($tsec ne $usec) { next; }
5072: }
5073: $access=($effect eq 'allow');
5074: last;
5075: }
5076: if ($realm eq '' && $role eq '') {
5077: $access=($effect eq 'allow');
5078: }
1.402 bowersj2 5079: }
1.341 www 5080: }
5081: return $access;
5082: }
5083:
1.103 harris41 5084: # ------------------------------------------------- Check for a user privilege
1.12 www 5085:
5086: sub allowed {
1.810 raeburn 5087: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5088: my $ver_orguri=$uri;
1.439 www 5089: $uri=&deversion($uri);
1.152 www 5090: my $orguri=$uri;
1.52 www 5091: $uri=&declutter($uri);
1.809 raeburn 5092:
1.810 raeburn 5093: if ($priv eq 'evb') {
5094: # Evade communication block restrictions for specified role in a course
5095: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5096: return $1;
5097: } else {
5098: return;
5099: }
5100: }
5101:
1.620 albertel 5102: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5103: # Free bre access to adm and meta resources
1.775 albertel 5104: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5105: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5106: && ($priv eq 'bre')) {
1.14 www 5107: return 'F';
1.159 www 5108: }
5109:
1.545 banghart 5110: # Free bre access to user's own portfolio contents
1.714 raeburn 5111: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5112: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5113: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5114: my %setters;
5115: my ($startblock,$endblock) =
5116: &Apache::loncommon::blockcheck(\%setters,'port');
5117: if ($startblock && $endblock) {
5118: return 'B';
5119: } else {
5120: return 'F';
5121: }
1.545 banghart 5122: }
5123:
1.762 raeburn 5124: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5125: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5126: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5127: if (exists($env{'request.course.id'})) {
5128: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5129: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5130: if (($domain eq $cdom) && ($name eq $cnum)) {
5131: my $courseprivid=$env{'request.course.id'};
5132: $courseprivid=~s/\_/\//;
5133: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5134: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5135: return $1;
1.762 raeburn 5136: } else {
5137: if ($env{'request.course.sec'}) {
5138: $courseprivid.='/'.$env{'request.course.sec'};
5139: }
5140: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5141: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5142: return $2;
5143: }
1.714 raeburn 5144: }
5145: }
5146: }
5147: }
5148:
1.159 www 5149: # Free bre to public access
5150:
5151: if ($priv eq 'bre') {
1.238 www 5152: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5153: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5154: return 'F';
5155: }
1.238 www 5156: if ($copyright eq 'priv') {
5157: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5158: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5159: return '';
5160: }
5161: }
5162: if ($copyright eq 'domain') {
5163: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5164: unless (($env{'user.domain'} eq $1) ||
5165: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5166: return '';
5167: }
1.262 matthew 5168: }
1.620 albertel 5169: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5170: # Library role, so allow browsing of resources in this domain.
5171: return 'F';
1.238 www 5172: }
1.341 www 5173: if ($copyright eq 'custom') {
5174: unless (&customaccess($priv,$uri)) { return ''; }
5175: }
1.14 www 5176: }
1.264 matthew 5177: # Domain coordinator is trying to create a course
1.620 albertel 5178: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5179: # uri is the requested domain in this case.
5180: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5181: # a role of dc for the domain in question.
1.620 albertel 5182: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5183: }
1.29 www 5184:
1.52 www 5185: my $thisallowed='';
5186: my $statecond=0;
5187: my $courseprivid='';
5188:
1.1039 raeburn 5189: my $ownaccess;
1.1043 raeburn 5190: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5191: if (($priv eq 'bro') && ($env{'user.author'})) {
5192: if ($uri eq '') {
5193: $ownaccess = 1;
5194: } else {
5195: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5196: my $udom = $env{'user.domain'};
5197: my $uname = $env{'user.name'};
5198: if ($uri =~ m{^\Q$udom\E/?$}) {
5199: $ownaccess = 1;
1.1040 raeburn 5200: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5201: unless ($uri =~ m{\.\./}) {
5202: $ownaccess = 1;
5203: }
5204: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5205: my $now = time;
5206: if ($uri =~ m{^([^/]+)/?$}) {
5207: my $adom = $1;
5208: foreach my $key (keys(%env)) {
1.1042 raeburn 5209: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5210: my ($start,$end) = split('.',$env{$key});
5211: if (($now >= $start) && (!$end || $end < $now)) {
5212: $ownaccess = 1;
5213: last;
5214: }
5215: }
5216: }
5217: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5218: my $adom = $1;
5219: my $aname = $2;
1.1042 raeburn 5220: foreach my $role ('ca','aa') {
5221: if ($env{"user.role.$role./$adom/$aname"}) {
5222: my ($start,$end) =
5223: split('.',$env{"user.role.$role./$adom/$aname"});
5224: if (($now >= $start) && (!$end || $end < $now)) {
5225: $ownaccess = 1;
5226: last;
5227: }
1.1039 raeburn 5228: }
5229: }
5230: }
5231: }
5232: }
5233: }
5234: }
5235:
1.52 www 5236: # Course
5237:
1.620 albertel 5238: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5239: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5240: $thisallowed.=$1;
5241: }
1.52 www 5242: }
1.29 www 5243:
1.52 www 5244: # Domain
5245:
1.620 albertel 5246: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5247: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5248: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5249: $thisallowed.=$1;
5250: }
1.12 www 5251: }
1.52 www 5252:
5253: # Course: uri itself is a course
1.66 www 5254: my $courseuri=$uri;
5255: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5256: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5257:
1.620 albertel 5258: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5259: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5260: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5261: $thisallowed.=$1;
5262: }
1.12 www 5263: }
1.29 www 5264:
1.665 albertel 5265: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5266: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5267: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5268: $thisallowed='';
1.671 raeburn 5269: my ($match)=&is_on_map($uri);
5270: if ($match) {
5271: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5272: =~/\Q$priv\E\&([^\:]*)/) {
5273: $thisallowed.=$1;
5274: }
5275: } else {
1.705 albertel 5276: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5277: if ($refuri) {
5278: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5279: $thisallowed='F';
1.671 raeburn 5280: } else {
5281: $refuri=&declutter($refuri);
5282: my ($match) = &is_on_map($refuri);
5283: if ($match) {
5284: $thisallowed='F';
5285: }
1.669 raeburn 5286: }
1.671 raeburn 5287: }
5288: }
1.314 www 5289: }
1.492 albertel 5290:
1.766 albertel 5291: if ($priv eq 'bre'
5292: && $thisallowed ne 'F'
5293: && $thisallowed ne '2'
5294: && &is_portfolio_url($uri)) {
5295: $thisallowed = &portfolio_access($uri);
5296: }
5297:
1.52 www 5298: # Full access at system, domain or course-wide level? Exit.
1.29 www 5299: if ($thisallowed=~/F/) {
5300: return 'F';
5301: }
5302:
1.52 www 5303: # If this is generating or modifying users, exit with special codes
1.29 www 5304:
1.643 www 5305: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5306: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5307: my ($audom,$auname)=split('/',$uri);
1.643 www 5308: # no author name given, so this just checks on the general right to make a co-author in this domain
5309: unless ($auname) { return $thisallowed; }
5310: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5311: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5312: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5313: ($audom ne $env{'request.role.domain'}))) { return ''; }
5314: }
1.52 www 5315: return $thisallowed;
5316: }
5317: #
1.103 harris41 5318: # Gathered so far: system, domain and course wide privileges
1.52 www 5319: #
5320: # Course: See if uri or referer is an individual resource that is part of
5321: # the course
5322:
1.620 albertel 5323: if ($env{'request.course.id'}) {
1.232 www 5324:
1.620 albertel 5325: $courseprivid=$env{'request.course.id'};
5326: if ($env{'request.course.sec'}) {
5327: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5328: }
5329: $courseprivid=~s/\_/\//;
5330: my $checkreferer=1;
1.232 www 5331: my ($match,$cond)=&is_on_map($uri);
5332: if ($match) {
5333: $statecond=$cond;
1.620 albertel 5334: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5335: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5336: $thisallowed.=$1;
5337: $checkreferer=0;
5338: }
1.29 www 5339: }
1.83 www 5340:
1.148 www 5341: if ($checkreferer) {
1.620 albertel 5342: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5343: unless ($refuri) {
1.800 albertel 5344: foreach my $key (keys(%env)) {
5345: if ($key=~/^httpref\..*\*/) {
5346: my $pattern=$key;
1.156 www 5347: $pattern=~s/^httpref\.\/res\///;
1.148 www 5348: $pattern=~s/\*/\[\^\/\]\+/g;
5349: $pattern=~s/\//\\\//g;
1.152 www 5350: if ($orguri=~/$pattern/) {
1.800 albertel 5351: $refuri=$env{$key};
1.148 www 5352: }
5353: }
1.191 harris41 5354: }
1.148 www 5355: }
1.232 www 5356:
1.148 www 5357: if ($refuri) {
1.152 www 5358: $refuri=&declutter($refuri);
1.232 www 5359: my ($match,$cond)=&is_on_map($refuri);
5360: if ($match) {
5361: my $refstatecond=$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;
1.53 www 5365: $uri=$refuri;
5366: $statecond=$refstatecond;
1.52 www 5367: }
5368: }
1.148 www 5369: }
1.29 www 5370: }
1.52 www 5371: }
1.29 www 5372:
1.52 www 5373: #
1.103 harris41 5374: # Gathered now: all privileges that could apply, and condition number
1.52 www 5375: #
5376: #
5377: # Full or no access?
5378: #
1.29 www 5379:
1.52 www 5380: if ($thisallowed=~/F/) {
5381: return 'F';
5382: }
1.29 www 5383:
1.52 www 5384: unless ($thisallowed) {
5385: return '';
5386: }
1.29 www 5387:
1.52 www 5388: # Restrictions exist, deal with them
5389: #
5390: # C:according to course preferences
5391: # R:according to resource settings
5392: # L:unless locked
5393: # X:according to user session state
5394: #
5395:
5396: # Possibly locked functionality, check all courses
1.54 www 5397: # Locks might take effect only after 10 minutes cache expiration for other
5398: # courses, and 2 minutes for current course
1.52 www 5399:
5400: my $envkey;
5401: if ($thisallowed=~/L/) {
1.1000 raeburn 5402: foreach $envkey (keys(%env)) {
1.54 www 5403: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5404: my $courseid=$2;
5405: my $roleid=$1.'.'.$2;
1.92 www 5406: $courseid=~s/^\///;
1.54 www 5407: my $expiretime=600;
1.620 albertel 5408: if ($env{'request.role'} eq $roleid) {
1.54 www 5409: $expiretime=120;
5410: }
5411: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5412: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5413: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5414: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5415: }
1.620 albertel 5416: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5417: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5418: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5419: &log($env{'user.domain'},$env{'user.name'},
5420: $env{'user.home'},
1.57 www 5421: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5422: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5423: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5424: return '';
5425: }
5426: }
1.620 albertel 5427: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5428: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5429: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5430: &log($env{'user.domain'},$env{'user.name'},
5431: $env{'user.home'},
1.57 www 5432: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5433: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5434: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5435: return '';
5436: }
5437: }
5438: }
1.29 www 5439: }
1.52 www 5440: }
5441:
5442: #
5443: # Rest of the restrictions depend on selected course
5444: #
5445:
1.620 albertel 5446: unless ($env{'request.course.id'}) {
1.766 albertel 5447: if ($thisallowed eq 'A') {
5448: return 'A';
1.814 raeburn 5449: } elsif ($thisallowed eq 'B') {
5450: return 'B';
1.766 albertel 5451: } else {
5452: return '1';
5453: }
1.52 www 5454: }
1.29 www 5455:
1.52 www 5456: #
5457: # Now user is definitely in a course
5458: #
1.53 www 5459:
5460:
5461: # Course preferences
5462:
5463: if ($thisallowed=~/C/) {
1.620 albertel 5464: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5465: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5466: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5467: =~/\Q$rolecode\E/) {
1.689 albertel 5468: if ($priv ne 'pch') {
5469: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5470: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5471: $env{'request.course.id'});
5472: }
1.237 www 5473: return '';
5474: }
5475:
1.620 albertel 5476: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5477: =~/\Q$unamedom\E/) {
1.689 albertel 5478: if ($priv ne 'pch') {
5479: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5480: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5481: $env{'request.course.id'});
5482: }
1.54 www 5483: return '';
5484: }
1.53 www 5485: }
5486:
5487: # Resource preferences
5488:
5489: if ($thisallowed=~/R/) {
1.620 albertel 5490: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5491: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5492: if ($priv ne 'pch') {
5493: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5494: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5495: }
5496: return '';
1.54 www 5497: }
1.53 www 5498: }
1.30 www 5499:
1.246 www 5500: # Restricted by state or randomout?
1.30 www 5501:
1.52 www 5502: if ($thisallowed=~/X/) {
1.620 albertel 5503: if ($env{'acc.randomout'}) {
1.579 albertel 5504: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5505: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5506: return '';
5507: }
1.247 www 5508: }
5509: if (&condval($statecond)) {
1.52 www 5510: return '2';
5511: } else {
5512: return '';
5513: }
5514: }
1.30 www 5515:
1.766 albertel 5516: if ($thisallowed eq 'A') {
5517: return 'A';
1.814 raeburn 5518: } elsif ($thisallowed eq 'B') {
5519: return 'B';
1.766 albertel 5520: }
1.52 www 5521: return 'F';
1.232 www 5522: }
5523:
1.710 albertel 5524: sub split_uri_for_cond {
5525: my $uri=&deversion(&declutter(shift));
5526: my @uriparts=split(/\//,$uri);
5527: my $filename=pop(@uriparts);
5528: my $pathname=join('/',@uriparts);
5529: return ($pathname,$filename);
5530: }
1.232 www 5531: # --------------------------------------------------- Is a resource on the map?
5532:
5533: sub is_on_map {
1.710 albertel 5534: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5535: #Trying to find the conditional for the file
1.620 albertel 5536: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5537: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5538: if ($match) {
1.289 bowersj2 5539: return (1,$1);
5540: } else {
1.434 www 5541: return (0,0);
1.289 bowersj2 5542: }
1.12 www 5543: }
5544:
1.427 www 5545: # --------------------------------------------------------- Get symb from alias
5546:
5547: sub get_symb_from_alias {
5548: my $symb=shift;
5549: my ($map,$resid,$url)=&decode_symb($symb);
5550: # Already is a symb
5551: if ($url) { return $symb; }
5552: # Must be an alias
5553: my $aliassymb='';
5554: my %bighash;
1.620 albertel 5555: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5556: &GDBM_READER(),0640)) {
5557: my $rid=$bighash{'mapalias_'.$symb};
5558: if ($rid) {
5559: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5560: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5561: $resid,$bighash{'src_'.$rid});
1.427 www 5562: }
5563: untie %bighash;
5564: }
5565: return $aliassymb;
5566: }
5567:
1.12 www 5568: # ----------------------------------------------------------------- Define Role
5569:
5570: sub definerole {
5571: if (allowed('mcr','/')) {
5572: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5573: foreach my $role (split(':',$sysrole)) {
5574: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5575: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5576: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5577: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5578: return "refused:s:$crole&$cqual";
5579: }
5580: }
1.191 harris41 5581: }
1.800 albertel 5582: foreach my $role (split(':',$domrole)) {
5583: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5584: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5585: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5586: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5587: return "refused:d:$crole&$cqual";
5588: }
5589: }
1.191 harris41 5590: }
1.800 albertel 5591: foreach my $role (split(':',$courole)) {
5592: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5593: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5594: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5595: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5596: return "refused:c:$crole&$cqual";
5597: }
5598: }
1.191 harris41 5599: }
1.620 albertel 5600: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5601: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5602: "rolesdef_$rolename=".
5603: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5604: return reply($command,$env{'user.home'});
1.12 www 5605: } else {
5606: return 'refused';
5607: }
1.105 harris41 5608: }
5609:
5610: # ---------------- Make a metadata query against the network of library servers
5611:
5612: sub metadata_query {
1.244 matthew 5613: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5614: my %rhash;
1.845 albertel 5615: my %libserv = &all_library();
1.244 matthew 5616: my @server_list = (defined($server_array) ? @$server_array
5617: : keys(%libserv) );
5618: for my $server (@server_list) {
1.118 harris41 5619: unless ($custom or $customshow) {
5620: my $reply=&reply("querysend:".&escape($query),$server);
5621: $rhash{$server}=$reply;
5622: }
5623: else {
5624: my $reply=&reply("querysend:".&escape($query).':'.
5625: &escape($custom).':'.&escape($customshow),
5626: $server);
5627: $rhash{$server}=$reply;
5628: }
1.112 harris41 5629: }
1.118 harris41 5630: return \%rhash;
1.240 www 5631: }
5632:
5633: # ----------------------------------------- Send log queries and wait for reply
5634:
5635: sub log_query {
5636: my ($uname,$udom,$query,%filters)=@_;
5637: my $uhome=&homeserver($uname,$udom);
5638: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5639: my $uhost=&hostname($uhome);
1.800 albertel 5640: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5641: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5642: $uhome);
1.479 albertel 5643: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5644: return get_query_reply($queryid);
5645: }
5646:
1.818 raeburn 5647: # -------------------------- Update MySQL table for portfolio file
5648:
5649: sub update_portfolio_table {
1.821 raeburn 5650: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5651: if ($group ne '') {
5652: $file_name =~s /^\Q$group\E//;
5653: }
1.818 raeburn 5654: my $homeserver = &homeserver($uname,$udom);
5655: my $queryid=
1.821 raeburn 5656: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5657: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5658: my $reply = &get_query_reply($queryid);
5659: return $reply;
5660: }
5661:
1.899 raeburn 5662: # -------------------------- Update MySQL allusers table
5663:
5664: sub update_allusers_table {
5665: my ($uname,$udom,$names) = @_;
5666: my $homeserver = &homeserver($uname,$udom);
5667: my $queryid=
5668: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5669: 'lastname='.&escape($names->{'lastname'}).'%%'.
5670: 'firstname='.&escape($names->{'firstname'}).'%%'.
5671: 'middlename='.&escape($names->{'middlename'}).'%%'.
5672: 'generation='.&escape($names->{'generation'}).'%%'.
5673: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5674: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.2.6 raeburn 5675: return;
1.899 raeburn 5676: }
5677:
1.508 raeburn 5678: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5679:
5680: sub fetch_enrollment_query {
1.511 raeburn 5681: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5682: my $homeserver;
1.547 raeburn 5683: my $maxtries = 1;
1.508 raeburn 5684: if ($context eq 'automated') {
5685: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5686: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5687: } else {
5688: $homeserver = &homeserver($cnum,$dom);
5689: }
1.838 albertel 5690: my $host=&hostname($homeserver);
1.506 raeburn 5691: my $cmd = '';
1.1000 raeburn 5692: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5693: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5694: }
5695: $cmd =~ s/%%$//;
5696: $cmd = &escape($cmd);
5697: my $query = 'fetchenrollment';
1.620 albertel 5698: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5699: unless ($queryid=~/^\Q$host\E\_/) {
5700: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5701: return 'error: '.$queryid;
5702: }
1.506 raeburn 5703: my $reply = &get_query_reply($queryid);
1.547 raeburn 5704: my $tries = 1;
5705: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5706: $reply = &get_query_reply($queryid);
5707: $tries ++;
5708: }
1.526 raeburn 5709: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5710: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5711: } else {
1.901 albertel 5712: my @responses = split(/:/,$reply);
1.515 raeburn 5713: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5714: foreach my $line (@responses) {
5715: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5716: $$replyref{$key} = $value;
5717: }
5718: } else {
1.506 raeburn 5719: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5720: foreach my $line (@responses) {
5721: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5722: $$replyref{$key} = $value;
5723: if ($value > 0) {
1.800 albertel 5724: foreach my $item (@{$$affiliatesref{$key}}) {
5725: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5726: my $destname = $pathname.'/'.$filename;
5727: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5728: if ($xml_classlist =~ /^error/) {
5729: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5730: } else {
1.506 raeburn 5731: if ( open(FILE,">$destname") ) {
5732: print FILE &unescape($xml_classlist);
5733: close(FILE);
1.526 raeburn 5734: } else {
5735: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5736: }
5737: }
5738: }
5739: }
5740: }
5741: }
5742: return 'ok';
5743: }
5744: return 'error';
5745: }
5746:
1.242 www 5747: sub get_query_reply {
5748: my $queryid=shift;
1.240 www 5749: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5750: my $reply='';
5751: for (1..100) {
5752: sleep 2;
5753: if (-e $replyfile.'.end') {
1.448 albertel 5754: if (open(my $fh,$replyfile)) {
1.904 albertel 5755: $reply = join('',<$fh>);
5756: close($fh);
1.240 www 5757: } else { return 'error: reply_file_error'; }
1.242 www 5758: return &unescape($reply);
5759: }
1.240 www 5760: }
1.242 www 5761: return 'timeout:'.$queryid;
1.240 www 5762: }
5763:
5764: sub courselog_query {
1.241 www 5765: #
5766: # possible filters:
5767: # url: url or symb
5768: # username
5769: # domain
5770: # action: view, submit, grade
5771: # start: timestamp
5772: # end: timestamp
5773: #
1.240 www 5774: my (%filters)=@_;
1.620 albertel 5775: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5776: if ($filters{'url'}) {
5777: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5778: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5779: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5780: }
1.620 albertel 5781: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5782: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5783: return &log_query($cname,$cdom,'courselog',%filters);
5784: }
5785:
5786: sub userlog_query {
1.858 raeburn 5787: #
5788: # possible filters:
5789: # action: log check role
5790: # start: timestamp
5791: # end: timestamp
5792: #
1.240 www 5793: my ($uname,$udom,%filters)=@_;
5794: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5795: }
5796:
1.506 raeburn 5797: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5798:
5799: sub auto_run {
1.508 raeburn 5800: my ($cnum,$cdom) = @_;
1.876 raeburn 5801: my $response = 0;
5802: my $settings;
5803: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5804: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5805: $settings = $domconfig{'autoenroll'};
5806: if ($settings->{'run'} eq '1') {
5807: $response = 1;
5808: }
5809: } else {
1.934 raeburn 5810: my $homeserver;
5811: if (&is_course($cdom,$cnum)) {
5812: $homeserver = &homeserver($cnum,$cdom);
5813: } else {
5814: $homeserver = &domain($cdom,'primary');
5815: }
5816: if ($homeserver ne 'no_host') {
5817: $response = &reply('autorun:'.$cdom,$homeserver);
5818: }
1.876 raeburn 5819: }
1.506 raeburn 5820: return $response;
5821: }
1.776 albertel 5822:
1.506 raeburn 5823: sub auto_get_sections {
1.508 raeburn 5824: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5825: my $homeserver;
5826: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5827: $homeserver = &homeserver($cnum,$cdom);
5828: }
5829: if (!defined($homeserver)) {
5830: if ($cdom =~ /^$match_domain$/) {
5831: $homeserver = &domain($cdom,'primary');
5832: }
5833: }
5834: my @secs;
5835: if (defined($homeserver)) {
5836: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5837: unless ($response eq 'refused') {
5838: @secs = split(/:/,$response);
5839: }
1.506 raeburn 5840: }
5841: return @secs;
5842: }
1.776 albertel 5843:
1.506 raeburn 5844: sub auto_new_course {
1.508 raeburn 5845: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5846: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5847: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5848: return $response;
5849: }
1.776 albertel 5850:
1.506 raeburn 5851: sub auto_validate_courseID {
1.508 raeburn 5852: my ($cnum,$cdom,$inst_course_id) = @_;
5853: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5854: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5855: return $response;
5856: }
1.776 albertel 5857:
1.1007 raeburn 5858: sub auto_validate_instcode {
1.1020 raeburn 5859: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5860: my ($homeserver,$response);
5861: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5862: $homeserver = &homeserver($cnum,$cdom);
5863: }
5864: if (!defined($homeserver)) {
5865: if ($cdom =~ /^$match_domain$/) {
5866: $homeserver = &domain($cdom,'primary');
5867: }
5868: }
1.1056.2.4 raeburn 5869: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5870: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5871: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5872: return ($outcome,$description);
1.1007 raeburn 5873: }
5874:
1.506 raeburn 5875: sub auto_create_password {
1.873 raeburn 5876: my ($cnum,$cdom,$authparam,$udom) = @_;
5877: my ($homeserver,$response);
1.506 raeburn 5878: my $create_passwd = 0;
5879: my $authchk = '';
1.873 raeburn 5880: if ($udom =~ /^$match_domain$/) {
5881: $homeserver = &domain($udom,'primary');
5882: }
5883: if ($homeserver eq '') {
5884: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5885: $homeserver = &homeserver($cnum,$cdom);
5886: }
5887: }
5888: if ($homeserver eq '') {
5889: $authchk = 'nodomain';
1.506 raeburn 5890: } else {
1.873 raeburn 5891: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5892: if ($response eq 'refused') {
5893: $authchk = 'refused';
5894: } else {
1.901 albertel 5895: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5896: }
1.506 raeburn 5897: }
5898: return ($authparam,$create_passwd,$authchk);
5899: }
5900:
1.706 raeburn 5901: sub auto_photo_permission {
5902: my ($cnum,$cdom,$students) = @_;
5903: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5904: my ($outcome,$perm_reqd,$conditions) =
5905: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5906: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5907: return (undef,undef);
5908: }
1.706 raeburn 5909: return ($outcome,$perm_reqd,$conditions);
5910: }
5911:
5912: sub auto_checkphotos {
5913: my ($uname,$udom,$pid) = @_;
5914: my $homeserver = &homeserver($uname,$udom);
5915: my ($result,$resulttype);
5916: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5917: &escape($uname).':'.&escape($pid),
5918: $homeserver));
1.709 albertel 5919: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5920: return (undef,undef);
5921: }
1.706 raeburn 5922: if ($outcome) {
5923: ($result,$resulttype) = split(/:/,$outcome);
5924: }
5925: return ($result,$resulttype);
5926: }
5927:
5928: sub auto_photochoice {
5929: my ($cnum,$cdom) = @_;
5930: my $homeserver = &homeserver($cnum,$cdom);
5931: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5932: &escape($cdom),
5933: $homeserver)));
1.709 albertel 5934: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5935: return (undef,undef);
5936: }
1.706 raeburn 5937: return ($update,$comment);
5938: }
5939:
5940: sub auto_photoupdate {
5941: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5942: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5943: my $host=&hostname($homeserver);
1.706 raeburn 5944: my $cmd = '';
5945: my $maxtries = 1;
1.800 albertel 5946: foreach my $affiliate (keys(%{$affiliatesref})) {
5947: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5948: }
5949: $cmd =~ s/%%$//;
5950: $cmd = &escape($cmd);
5951: my $query = 'institutionalphotos';
5952: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5953: unless ($queryid=~/^\Q$host\E\_/) {
5954: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5955: return 'error: '.$queryid;
5956: }
5957: my $reply = &get_query_reply($queryid);
5958: my $tries = 1;
5959: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5960: $reply = &get_query_reply($queryid);
5961: $tries ++;
5962: }
5963: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5964: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5965: } else {
5966: my @responses = split(/:/,$reply);
5967: my $outcome = shift(@responses);
5968: foreach my $item (@responses) {
5969: my ($key,$value) = split(/=/,$item);
5970: $$photo{$key} = $value;
5971: }
5972: return $outcome;
5973: }
5974: return 'error';
5975: }
5976:
1.521 raeburn 5977: sub auto_instcode_format {
1.793 albertel 5978: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5979: $cat_order) = @_;
1.521 raeburn 5980: my $courses = '';
1.772 raeburn 5981: my @homeservers;
1.521 raeburn 5982: if ($caller eq 'global') {
1.841 albertel 5983: my %servers = &get_servers($codedom,'library');
5984: foreach my $tryserver (keys(%servers)) {
5985: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5986: push(@homeservers,$tryserver);
5987: }
1.584 raeburn 5988: }
1.1022 raeburn 5989: } elsif ($caller eq 'requests') {
5990: if ($codedom =~ /^$match_domain$/) {
5991: my $chome = &domain($codedom,'primary');
5992: unless ($chome eq 'no_host') {
5993: push(@homeservers,$chome);
5994: }
5995: }
1.521 raeburn 5996: } else {
1.772 raeburn 5997: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5998: }
1.793 albertel 5999: foreach my $code (keys(%{$instcodes})) {
6000: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6001: }
6002: chop($courses);
1.772 raeburn 6003: my $ok_response = 0;
6004: my $response;
6005: while (@homeservers > 0 && $ok_response == 0) {
6006: my $server = shift(@homeservers);
6007: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6008: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6009: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6010: split(/:/,$response);
1.772 raeburn 6011: %{$codes} = (%{$codes},&str2hash($codes_str));
6012: push(@{$codetitles},&str2array($codetitles_str));
6013: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6014: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6015: $ok_response = 1;
6016: }
6017: }
6018: if ($ok_response) {
1.521 raeburn 6019: return 'ok';
1.772 raeburn 6020: } else {
6021: return $response;
1.521 raeburn 6022: }
6023: }
6024:
1.792 raeburn 6025: sub auto_instcode_defaults {
6026: my ($domain,$returnhash,$code_order) = @_;
6027: my @homeservers;
1.841 albertel 6028:
6029: my %servers = &get_servers($domain,'library');
6030: foreach my $tryserver (keys(%servers)) {
6031: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6032: push(@homeservers,$tryserver);
6033: }
1.792 raeburn 6034: }
1.841 albertel 6035:
1.792 raeburn 6036: my $response;
1.841 albertel 6037: foreach my $server (@homeservers) {
1.792 raeburn 6038: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6039: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6040:
6041: foreach my $pair (split(/\&/,$response)) {
6042: my ($name,$value)=split(/\=/,$pair);
6043: if ($name eq 'code_order') {
6044: @{$code_order} = split(/\&/,&unescape($value));
6045: } else {
6046: $returnhash->{&unescape($name)}=&unescape($value);
6047: }
6048: }
6049: return 'ok';
1.792 raeburn 6050: }
1.841 albertel 6051:
6052: return $response;
1.1003 raeburn 6053: }
6054:
6055: sub auto_possible_instcodes {
1.1007 raeburn 6056: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6057: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6058: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6059: return;
6060: }
1.1003 raeburn 6061: my (@homeservers,$uhome);
6062: if (defined(&domain($domain,'primary'))) {
6063: $uhome=&domain($domain,'primary');
6064: push(@homeservers,&domain($domain,'primary'));
6065: } else {
6066: my %servers = &get_servers($domain,'library');
6067: foreach my $tryserver (keys(%servers)) {
6068: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6069: push(@homeservers,$tryserver);
6070: }
6071: }
6072: }
6073: my $response;
6074: foreach my $server (@homeservers) {
6075: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6076: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6077: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6078: split(':',$response);
6079: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6080: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6081: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6082: my ($name,$value)=split('=',$item);
6083: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6084: }
6085: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6086: my ($name,$value)=split('=',$item);
6087: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6088: }
6089: return 'ok';
6090: }
6091: return $response;
6092: }
1.792 raeburn 6093:
1.1010 raeburn 6094: sub auto_courserequest_checks {
6095: my ($dom) = @_;
1.1020 raeburn 6096: my ($homeserver,%validations);
6097: if ($dom =~ /^$match_domain$/) {
6098: $homeserver = &domain($dom,'primary');
6099: }
6100: unless ($homeserver eq 'no_host') {
6101: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6102: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6103: my @items = split(/&/,$response);
6104: foreach my $item (@items) {
6105: my ($key,$value) = split('=',$item);
6106: $validations{&unescape($key)} = &thaw_unescape($value);
6107: }
6108: }
6109: }
1.1010 raeburn 6110: return %validations;
6111: }
6112:
1.1020 raeburn 6113: sub auto_courserequest_validation {
6114: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6115: my ($homeserver,$response);
6116: if ($dom =~ /^$match_domain$/) {
6117: $homeserver = &domain($dom,'primary');
6118: }
6119: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6120:
1.1020 raeburn 6121: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6122: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6123: ':'.&escape($instcode).':'.&escape($instseclist),
6124: $homeserver));
6125: }
6126: return $response;
6127: }
6128:
1.777 albertel 6129: sub auto_validate_class_sec {
1.918 raeburn 6130: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6131: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6132: my $ownerlist;
6133: if (ref($owners) eq 'ARRAY') {
6134: $ownerlist = join(',',@{$owners});
6135: } else {
6136: $ownerlist = $owners;
6137: }
1.773 raeburn 6138: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6139: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6140: return $response;
6141: }
6142:
1.679 raeburn 6143: # ------------------------------------------------------- Course Group routines
6144:
6145: sub get_coursegroups {
1.809 raeburn 6146: my ($cdom,$cnum,$group,$namespace) = @_;
6147: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6148: }
6149:
1.679 raeburn 6150: sub modify_coursegroup {
6151: my ($cdom,$cnum,$groupsettings) = @_;
6152: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6153: }
6154:
1.809 raeburn 6155: sub toggle_coursegroup_status {
6156: my ($cdom,$cnum,$group,$action) = @_;
6157: my ($from_namespace,$to_namespace);
6158: if ($action eq 'delete') {
6159: $from_namespace = 'coursegroups';
6160: $to_namespace = 'deleted_groups';
6161: } else {
6162: $from_namespace = 'deleted_groups';
6163: $to_namespace = 'coursegroups';
6164: }
6165: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6166: if (my $tmp = &error(%curr_group)) {
6167: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6168: return ('read error',$tmp);
6169: } else {
6170: my %savedsettings = %curr_group;
1.809 raeburn 6171: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6172: my $deloutcome;
6173: if ($result eq 'ok') {
1.809 raeburn 6174: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6175: } else {
6176: return ('write error',$result);
6177: }
6178: if ($deloutcome eq 'ok') {
6179: return 'ok';
6180: } else {
6181: return ('delete error',$deloutcome);
6182: }
6183: }
6184: }
6185:
1.679 raeburn 6186: sub modify_group_roles {
1.957 raeburn 6187: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6188: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6189: my $role = 'gr/'.&escape($userprivs);
6190: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6191: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6192: if ($result eq 'ok') {
6193: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6194: }
1.679 raeburn 6195: return $result;
6196: }
6197:
6198: sub modify_coursegroup_membership {
6199: my ($cdom,$cnum,$membership) = @_;
6200: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6201: return $result;
6202: }
6203:
1.682 raeburn 6204: sub get_active_groups {
6205: my ($udom,$uname,$cdom,$cnum) = @_;
6206: my $now = time;
6207: my %groups = ();
6208: foreach my $key (keys(%env)) {
1.811 albertel 6209: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6210: my ($start,$end) = split(/\./,$env{$key});
6211: if (($end!=0) && ($end<$now)) { next; }
6212: if (($start!=0) && ($start>$now)) { next; }
6213: if ($1 eq $cdom && $2 eq $cnum) {
6214: $groups{$3} = $env{$key} ;
6215: }
6216: }
6217: }
6218: return %groups;
6219: }
6220:
1.683 raeburn 6221: sub get_group_membership {
6222: my ($cdom,$cnum,$group) = @_;
6223: return(&dump('groupmembership',$cdom,$cnum,$group));
6224: }
6225:
6226: sub get_users_groups {
6227: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6228: my @usersgroups;
1.683 raeburn 6229: my $cachetime=1800;
6230:
6231: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6232: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6233: if (defined($cached)) {
1.734 albertel 6234: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6235: } else {
6236: $grouplist = '';
1.816 raeburn 6237: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.2.9 raeburn 6238: my $extra = &freeze_escape({'skipcheck' => 1});
6239: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6240: my $access_end = $env{'course.'.$courseid.
6241: '.default_enrollment_end_date'};
6242: my $now = time;
6243: foreach my $key (keys(%roleshash)) {
6244: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6245: my $group = $1;
6246: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6247: my $start = $2;
6248: my $end = $1;
6249: if ($start == -1) { next; } # deleted from group
6250: if (($start!=0) && ($start>$now)) { next; }
6251: if (($end!=0) && ($end<$now)) {
6252: if ($access_end && $access_end < $now) {
6253: if ($access_end - $end < 86400) {
6254: push(@usersgroups,$group);
1.733 raeburn 6255: }
6256: }
1.817 raeburn 6257: next;
1.733 raeburn 6258: }
1.817 raeburn 6259: push(@usersgroups,$group);
1.683 raeburn 6260: }
6261: }
6262: }
1.817 raeburn 6263: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6264: $grouplist = join(':',@usersgroups);
6265: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6266: }
1.733 raeburn 6267: return @usersgroups;
1.683 raeburn 6268: }
6269:
6270: sub devalidate_getgroups_cache {
6271: my ($udom,$uname,$cdom,$cnum)=@_;
6272: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6273:
1.683 raeburn 6274: my $hashid="$udom:$uname:$courseid";
6275: &devalidate_cache_new('getgroups',$hashid);
6276: }
6277:
1.12 www 6278: # ------------------------------------------------------------------ Plain Text
6279:
6280: sub plaintext {
1.988 raeburn 6281: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6282: if ($short =~ m{^cr/}) {
1.758 albertel 6283: return (split('/',$short))[-1];
6284: }
1.742 raeburn 6285: if (!defined($cid)) {
6286: $cid = $env{'request.course.id'};
6287: }
6288: my %rolenames = (
1.1008 raeburn 6289: Course => 'std',
6290: Community => 'alt1',
1.742 raeburn 6291: );
1.1037 raeburn 6292: if ($cid ne '') {
6293: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6294: unless ($forcedefault) {
6295: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6296: &Apache::lonlocal::mt_escape(\$roletext);
6297: return &Apache::lonlocal::mt($roletext);
6298: }
6299: }
6300: }
6301: if ((defined($type)) && (defined($rolenames{$type})) &&
6302: (defined($rolenames{$type})) &&
6303: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6304: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6305: } elsif ($cid ne '') {
6306: my $crstype = $env{'course.'.$cid.'.type'};
6307: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6308: (defined($prp{$short}{$rolenames{$crstype}}))) {
6309: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6310: }
1.742 raeburn 6311: }
1.1037 raeburn 6312: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6313: }
6314:
6315: # ----------------------------------------------------------------- Assign Role
6316:
6317: sub assignrole {
1.957 raeburn 6318: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6319: $context)=@_;
1.21 www 6320: my $mrole;
6321: if ($role =~ /^cr\//) {
1.393 www 6322: my $cwosec=$url;
1.811 albertel 6323: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6324: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6325: my $refused = 1;
6326: if ($context eq 'requestcourses') {
6327: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6328: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6329: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6330: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6331: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6332: if ($crsenv{'internal.courseowner'} eq
6333: $env{'user.name'}.':'.$env{'user.domain'}) {
6334: $refused = '';
6335: }
6336: }
6337: }
6338: }
6339: }
6340: if ($refused) {
6341: &logthis('Refused custom assignrole: '.
6342: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6343: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6344: return 'refused';
6345: }
1.104 www 6346: }
1.21 www 6347: $mrole='cr';
1.678 raeburn 6348: } elsif ($role =~ /^gr\//) {
6349: my $cwogrp=$url;
1.811 albertel 6350: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6351: unless (&allowed('mdg',$cwogrp)) {
6352: &logthis('Refused group assignrole: '.
6353: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6354: $env{'user.name'}.' at '.$env{'user.domain'});
6355: return 'refused';
6356: }
6357: $mrole='gr';
1.21 www 6358: } else {
1.82 www 6359: my $cwosec=$url;
1.811 albertel 6360: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6361: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6362: my $refused;
6363: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6364: if (!(&allowed('c'.$role,$url))) {
6365: $refused = 1;
6366: }
6367: } else {
6368: $refused = 1;
6369: }
1.947 raeburn 6370: if ($refused) {
1.1045 raeburn 6371: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6372: if (!$selfenroll && $context eq 'course') {
6373: my %crsenv;
6374: if ($role eq 'cc' || $role eq 'co') {
6375: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6376: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6377: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6378: if ($crsenv{'internal.courseowner'} eq
6379: $env{'user.name'}.':'.$env{'user.domain'}) {
6380: $refused = '';
6381: }
6382: }
6383: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6384: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6385: if ($crsenv{'internal.courseowner'} eq
6386: $env{'user.name'}.':'.$env{'user.domain'}) {
6387: $refused = '';
6388: }
6389: }
6390: }
6391: }
6392: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6393: $refused = '';
1.1017 raeburn 6394: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6395: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6396: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6397: my $wrongcc;
6398: if ($cnum =~ /^$match_community$/) {
6399: $wrongcc = 1 if ($role eq 'cc');
6400: } else {
6401: $wrongcc = 1 if ($role eq 'co');
6402: }
6403: unless ($wrongcc) {
6404: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6405: if ($crsenv{'internal.courseowner'} eq
6406: $env{'user.name'}.':'.$env{'user.domain'}) {
6407: $refused = '';
6408: }
1.1017 raeburn 6409: }
6410: }
6411: }
6412: if ($refused) {
1.947 raeburn 6413: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6414: ' '.$role.' '.$end.' '.$start.' by '.
6415: $env{'user.name'}.' at '.$env{'user.domain'});
6416: return 'refused';
6417: }
1.932 raeburn 6418: }
1.104 www 6419: }
1.21 www 6420: $mrole=$role;
6421: }
1.620 albertel 6422: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6423: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6424: if ($end) { $command.='_'.$end; }
1.21 www 6425: if ($start) {
6426: if ($end) {
1.81 www 6427: $command.='_'.$start;
1.21 www 6428: } else {
1.81 www 6429: $command.='_0_'.$start;
1.21 www 6430: }
6431: }
1.739 raeburn 6432: my $origstart = $start;
6433: my $origend = $end;
1.957 raeburn 6434: my $delflag;
1.357 www 6435: # actually delete
6436: if ($deleteflag) {
1.373 www 6437: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6438: # modify command to delete the role
1.620 albertel 6439: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6440: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6441: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6442: # set start and finish to negative values for userrolelog
6443: $start=-1;
6444: $end=-1;
1.957 raeburn 6445: $delflag = 1;
1.357 www 6446: }
6447: }
6448: # send command
1.349 www 6449: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6450: # log new user role if status is ok
1.349 www 6451: if ($answer eq 'ok') {
1.663 raeburn 6452: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6453: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6454: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6455: unless ($role =~ /^gr/) {
6456: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6457: $origstart,$selfenroll,$context);
1.739 raeburn 6458: }
1.1053 raeburn 6459: if ($role eq 'cc') {
6460: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6461: }
1.349 www 6462: }
6463: return $answer;
1.169 harris41 6464: }
6465:
1.1053 raeburn 6466: sub autoupdate_coowners {
6467: my ($url,$end,$start,$uname,$udom) = @_;
6468: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6469: if (($cdom ne '') && ($cnum ne '')) {
6470: my $now = time;
6471: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6472: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6473: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6474: my $instcode = $coursehash{'internal.coursecode'};
6475: if ($instcode ne '') {
1.1056 raeburn 6476: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6477: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6478: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6479: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6480: if ($result eq 'valid') {
6481: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6482: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6483: push(@newcoowners,$coowner);
6484: }
6485: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6486: push(@newcoowners,$uname.':'.$udom);
6487: }
6488: @newcoowners = sort(@newcoowners);
6489: } else {
6490: push(@newcoowners,$uname.':'.$udom);
6491: }
6492: } else {
6493: if ($coursehash{'internal.co-owners'}) {
6494: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6495: unless ($coowner eq $uname.':'.$udom) {
6496: push(@newcoowners,$coowner);
6497: }
6498: }
6499: unless (@newcoowners > 0) {
6500: $delcoowners = 1;
6501: $coowners = '';
6502: }
6503: }
6504: }
6505: if (@newcoowners || $delcoowners) {
6506: &store_coowners($cdom,$cnum,$coursehash{'home'},
6507: $delcoowners,@newcoowners);
6508: }
6509: }
6510: }
6511: }
6512: }
6513: }
6514: }
6515:
6516: sub store_coowners {
6517: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6518: my $cid = $cdom.'_'.$cnum;
6519: my ($coowners,$delresult,$putresult);
6520: if (@newcoowners) {
6521: $coowners = join(',',@newcoowners);
6522: my %coownershash = (
6523: 'internal.co-owners' => $coowners,
6524: );
6525: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6526: if ($putresult eq 'ok') {
6527: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6528: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6529: }
6530: }
6531: }
6532: if ($delcoowners) {
6533: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6534: if ($delresult eq 'ok') {
6535: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6536: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6537: }
6538: }
6539: }
6540: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6541: my %crsinfo =
6542: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6543: if (ref($crsinfo{$cid}) eq 'HASH') {
6544: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6545: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6546: }
6547: }
6548: }
6549:
1.169 harris41 6550: # -------------------------------------------------- Modify user authentication
1.197 www 6551: # Overrides without validation
6552:
1.169 harris41 6553: sub modifyuserauth {
6554: my ($udom,$uname,$umode,$upass)=@_;
6555: my $uhome=&homeserver($uname,$udom);
1.197 www 6556: unless (&allowed('mau',$udom)) { return 'refused'; }
6557: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6558: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6559: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6560: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6561: &escape($upass),$uhome);
1.620 albertel 6562: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6563: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6564: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6565: &log($udom,,$uname,$uhome,
1.620 albertel 6566: 'Authentication changed by '.$env{'user.domain'}.', '.
6567: $env{'user.name'}.', '.$umode.
1.197 www 6568: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6569: unless ($reply eq 'ok') {
1.197 www 6570: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6571: return 'error: '.$reply;
6572: }
1.170 harris41 6573: return 'ok';
1.80 www 6574: }
6575:
1.81 www 6576: # --------------------------------------------------------------- Modify a user
1.80 www 6577:
1.81 www 6578: sub modifyuser {
1.206 matthew 6579: my ($udom, $uname, $uid,
6580: $umode, $upass, $first,
6581: $middle, $last, $gene,
1.1056.2.1 raeburn 6582: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6583: $udom= &LONCAPA::clean_domain($udom);
6584: $uname=&LONCAPA::clean_username($uname);
1.1056.2.1 raeburn 6585: my $showcandelete = 'none';
6586: if (ref($candelete) eq 'ARRAY') {
6587: if (@{$candelete} > 0) {
6588: $showcandelete = join(', ',@{$candelete});
6589: }
6590: }
1.81 www 6591: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6592: $umode.', '.$first.', '.$middle.', '.
1.1056.2.1 raeburn 6593: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6594: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6595: ' desiredhome not specified').
1.620 albertel 6596: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6597: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6598: my $uhome=&homeserver($uname,$udom,'true');
1.1056.2.6 raeburn 6599: my $newuser;
6600: if ($uhome eq 'no_host') {
6601: $newuser = 1;
6602: }
1.80 www 6603: # ----------------------------------------------------------------- Create User
1.406 albertel 6604: if (($uhome eq 'no_host') &&
6605: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6606: my $unhome='';
1.844 albertel 6607: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6608: $unhome = $desiredhome;
1.620 albertel 6609: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6610: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6611: } else { # load balancing routine for determining $unhome
1.81 www 6612: my $loadm=10000000;
1.841 albertel 6613: my %servers = &get_servers($udom,'library');
6614: foreach my $tryserver (keys(%servers)) {
6615: my $answer=reply('load',$tryserver);
6616: if (($answer=~/\d+/) && ($answer<$loadm)) {
6617: $loadm=$answer;
6618: $unhome=$tryserver;
6619: }
1.80 www 6620: }
6621: }
6622: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6623: return 'error: unable to find a home server for '.$uname.
6624: ' in domain '.$udom;
1.80 www 6625: }
6626: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6627: &escape($upass),$unhome);
6628: unless ($reply eq 'ok') {
6629: return 'error: '.$reply;
6630: }
1.230 stredwic 6631: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6632: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6633: return 'error: unable verify users home machine.';
1.80 www 6634: }
1.209 matthew 6635: } # End of creation of new user
1.80 www 6636: # ---------------------------------------------------------------------- Add ID
6637: if ($uid) {
6638: $uid=~tr/A-Z/a-z/;
6639: my %uidhash=&idrget($udom,$uname);
1.196 www 6640: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6641: && (!$forceid)) {
1.80 www 6642: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6643: return 'error: user id "'.$uid.'" does not match '.
6644: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6645: }
6646: } else {
6647: &idput($udom,($uname => $uid));
6648: }
6649: }
6650: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6651: my @tmp=&get('environment',
1.899 raeburn 6652: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6653: 'permanentemail','inststatus'],
1.134 albertel 6654: $udom,$uname);
1.1056.2.6 raeburn 6655: my (%names,%oldnames);
1.313 matthew 6656: if ($tmp[0] =~ m/^error:.*/) {
6657: %names=();
6658: } else {
6659: %names = @tmp;
1.1056.2.6 raeburn 6660: %oldnames = %names;
1.313 matthew 6661: }
1.388 www 6662: #
1.1056.2.1 raeburn 6663: # If name, email and/or uid are blank (e.g., because an uploaded file
6664: # of users did not contain them), do not overwrite existing values
6665: # unless field is in $candelete array ref.
6666: #
6667: my @fields = ('firstname','middlename','lastname','generation',
6668: 'permanentemail','id');
6669: my %newvalues;
6670: if (ref($candelete) eq 'ARRAY') {
6671: foreach my $field (@fields) {
6672: if (grep(/^\Q$field\E$/,@{$candelete})) {
6673: if ($field eq 'firstname') {
6674: $names{$field} = $first;
6675: } elsif ($field eq 'middlename') {
6676: $names{$field} = $middle;
6677: } elsif ($field eq 'lastname') {
6678: $names{$field} = $last;
6679: } elsif ($field eq 'generation') {
6680: $names{$field} = $gene;
6681: } elsif ($field eq 'permanentemail') {
6682: $names{$field} = $email;
6683: } elsif ($field eq 'id') {
6684: $names{$field} = $uid;
6685: }
6686: }
6687: }
6688: }
6689:
1.388 www 6690: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6691: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6692: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6693: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6694: if ($email) {
6695: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6696: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6697: }
1.899 raeburn 6698: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6699: if (defined($inststatus)) {
6700: $names{'inststatus'} = '';
6701: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6702: if (ref($usertypes) eq 'HASH') {
6703: my @okstatuses;
6704: foreach my $item (split(/:/,$inststatus)) {
6705: if (defined($usertypes->{$item})) {
6706: push(@okstatuses,$item);
6707: }
6708: }
6709: if (@okstatuses) {
6710: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6711: }
6712: }
6713: }
1.1056.2.6 raeburn 6714: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6715: $umode.', '.$first.', '.$middle.', '.
6716: $last.', '.$gene.', '.$email.', '.$inststatus;
6717: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6718: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6719: } else {
6720: $logmsg .= ' during self creation';
6721: }
1.1056.2.6 raeburn 6722: my $changed;
6723: if ($newuser) {
6724: $changed = 1;
6725: } else {
6726: foreach my $field (@fields) {
6727: if ($names{$field} ne $oldnames{$field}) {
6728: $changed = 1;
6729: last;
6730: }
6731: }
6732: }
6733: unless ($changed) {
6734: $logmsg = 'No changes in user information needed for: '.$logmsg;
6735: &logthis($logmsg);
6736: return 'ok';
6737: }
6738: my $reply = &put('environment', \%names, $udom,$uname);
6739: if ($reply ne 'ok') {
6740: return 'error: '.$reply;
6741: }
1.1056.2.7 raeburn 6742: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
6743: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
6744: }
1.1056.2.6 raeburn 6745: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6746: &devalidate_cache_new('namescache',$uname.':'.$udom);
6747: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6748: &logthis($logmsg);
1.134 albertel 6749: return 'ok';
1.80 www 6750: }
6751:
1.81 www 6752: # -------------------------------------------------------------- Modify student
1.80 www 6753:
1.81 www 6754: sub modifystudent {
6755: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6756: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6757: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6758: if (!$cid) {
1.620 albertel 6759: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6760: return 'not_in_class';
6761: }
1.80 www 6762: }
6763: # --------------------------------------------------------------- Make the user
1.81 www 6764: my $reply=&modifyuser
1.209 matthew 6765: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6766: $desiredhome,$email,$inststatus);
1.80 www 6767: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6768: # This will cause &modify_student_enrollment to get the uid from the
6769: # students environment
6770: $uid = undef if (!$forceid);
1.455 albertel 6771: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6772: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6773: return $reply;
6774: }
6775:
6776: sub modify_student_enrollment {
1.957 raeburn 6777: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6778: my ($cdom,$cnum,$chome);
6779: if (!$cid) {
1.620 albertel 6780: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6781: return 'not_in_class';
6782: }
1.620 albertel 6783: $cdom=$env{'course.'.$cid.'.domain'};
6784: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6785: } else {
6786: ($cdom,$cnum)=split(/_/,$cid);
6787: }
1.620 albertel 6788: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6789: if (!$chome) {
1.457 raeburn 6790: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6791: }
1.455 albertel 6792: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6793: # Make sure the user exists
1.81 www 6794: my $uhome=&homeserver($uname,$udom);
6795: if (($uhome eq '') || ($uhome eq 'no_host')) {
6796: return 'error: no such user';
6797: }
1.297 matthew 6798: # Get student data if we were not given enough information
6799: if (!defined($first) || $first eq '' ||
6800: !defined($last) || $last eq '' ||
6801: !defined($uid) || $uid eq '' ||
6802: !defined($middle) || $middle eq '' ||
6803: !defined($gene) || $gene eq '') {
1.294 matthew 6804: # They did not supply us with enough data to enroll the student, so
6805: # we need to pick up more information.
1.297 matthew 6806: my %tmp = &get('environment',
1.294 matthew 6807: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6808: ,$udom,$uname);
6809:
1.800 albertel 6810: #foreach my $key (keys(%tmp)) {
6811: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6812: #}
1.294 matthew 6813: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6814: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6815: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6816: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6817: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6818: }
1.556 albertel 6819: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6820: my $reply=cput('classlist',
6821: {"$uname:$udom" =>
1.515 raeburn 6822: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6823: $cdom,$cnum);
1.81 www 6824: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6825: return 'error: '.$reply;
1.652 albertel 6826: } else {
6827: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6828: }
1.297 matthew 6829: # Add student role to user
1.83 www 6830: my $uurl='/'.$cid;
1.81 www 6831: $uurl=~s/\_/\//g;
6832: if ($usec) {
6833: $uurl.='/'.$usec;
6834: }
1.957 raeburn 6835: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6836: }
6837:
1.556 albertel 6838: sub format_name {
6839: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6840: my $name;
6841: if ($first ne 'lastname') {
6842: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6843: } else {
6844: if ($lastname=~/\S/) {
6845: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6846: $name=~s/\s+,/,/;
6847: } else {
6848: $name.= $firstname.' '.$middlename.' '.$generation;
6849: }
6850: }
6851: $name=~s/^\s+//;
6852: $name=~s/\s+$//;
6853: $name=~s/\s+/ /g;
6854: return $name;
6855: }
6856:
1.84 www 6857: # ------------------------------------------------- Write to course preferences
6858:
6859: sub writecoursepref {
6860: my ($courseid,%prefs)=@_;
6861: $courseid=~s/^\///;
6862: $courseid=~s/\_/\//g;
6863: my ($cdomain,$cnum)=split(/\//,$courseid);
6864: my $chome=homeserver($cnum,$cdomain);
6865: if (($chome eq '') || ($chome eq 'no_host')) {
6866: return 'error: no such course';
6867: }
6868: my $cstring='';
1.800 albertel 6869: foreach my $pref (keys(%prefs)) {
6870: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6871: }
1.84 www 6872: $cstring=~s/\&$//;
6873: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6874: }
6875:
6876: # ---------------------------------------------------------- Make/modify course
6877:
6878: sub createcourse {
1.741 raeburn 6879: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6880: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6881: $url=&declutter($url);
6882: my $cid='';
1.1028 raeburn 6883: if ($context eq 'requestcourses') {
6884: my $can_create = 0;
6885: my ($ownername,$ownerdom) = split(':',$course_owner);
6886: if ($udom eq $ownerdom) {
6887: if (&usertools_access($ownername,$ownerdom,$category,undef,
6888: $context)) {
6889: $can_create = 1;
6890: }
6891: } else {
6892: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6893: $category);
6894: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6895: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6896: if (@curr > 0) {
6897: my @options = qw(approval validate autolimit);
6898: my $optregex = join('|',@options);
6899: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6900: $can_create = 1;
6901: }
6902: }
6903: }
6904: }
6905: if ($can_create) {
6906: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6907: unless (&allowed('ccc',$udom)) {
6908: return 'refused';
6909: }
1.1017 raeburn 6910: }
6911: } else {
6912: return 'refused';
6913: }
1.1028 raeburn 6914: } elsif (!&allowed('ccc',$udom)) {
6915: return 'refused';
1.84 www 6916: }
1.1011 raeburn 6917: # --------------------------------------------------------------- Get Unique ID
6918: my $uname;
6919: if ($cnum =~ /^$match_courseid$/) {
6920: my $chome=&homeserver($cnum,$udom,'true');
6921: if (($chome eq '') || ($chome eq 'no_host')) {
6922: $uname = $cnum;
6923: } else {
1.1038 raeburn 6924: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6925: }
6926: } else {
1.1038 raeburn 6927: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6928: }
6929: return $uname if ($uname =~ /^error/);
6930: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6931: if (!defined($course_server)) {
6932: if (defined(&domain($udom,'primary'))) {
6933: $course_server = &domain($udom,'primary');
6934: } else {
6935: $course_server = $env{'user.home'};
6936: }
6937: }
6938: my %host_servers =
6939: &Apache::lonnet::get_servers($udom,'library');
6940: unless ($host_servers{$course_server}) {
6941: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6942: }
1.84 www 6943: # ------------------------------------------------------------- Make the course
6944: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6945: $course_server);
1.84 www 6946: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6947: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6948: if (($uhome eq '') || ($uhome eq 'no_host')) {
6949: return 'error: no such course';
6950: }
1.271 www 6951: # ----------------------------------------------------------------- Course made
1.516 raeburn 6952: # log existence
1.1029 raeburn 6953: my $now = time;
1.918 raeburn 6954: my $newcourse = {
6955: $udom.'_'.$uname => {
1.921 raeburn 6956: description => $description,
6957: inst_code => $inst_code,
6958: owner => $course_owner,
6959: type => $crstype,
1.1029 raeburn 6960: creator => $env{'user.name'}.':'.
6961: $env{'user.domain'},
6962: created => $now,
6963: context => $context,
1.918 raeburn 6964: },
6965: };
1.921 raeburn 6966: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6967: # set toplevel url
1.271 www 6968: my $topurl=$url;
6969: unless ($nonstandard) {
6970: # ------------------------------------------ For standard courses, make top url
6971: my $mapurl=&clutter($url);
1.278 www 6972: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6973: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6974: <map>
6975: <resource id="1" type="start"></resource>
6976: <resource id="2" src="$mapurl"></resource>
6977: <resource id="3" type="finish"></resource>
6978: <link index="1" from="1" to="2"></link>
6979: <link index="2" from="2" to="3"></link>
6980: </map>
6981: ENDINITMAP
6982: $topurl=&declutter(
1.638 albertel 6983: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6984: );
6985: }
6986: # ----------------------------------------------------------- Write preferences
1.84 www 6987: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6988: ('description' => $description,
6989: 'url' => $topurl,
6990: 'internal.creator' => $env{'user.name'}.':'.
6991: $env{'user.domain'},
6992: 'internal.created' => $now,
6993: 'internal.creationcontext' => $context)
6994: );
1.84 www 6995: return '/'.$udom.'/'.$uname;
6996: }
6997:
1.1011 raeburn 6998: # ------------------------------------------------------------------- Create ID
6999: sub generate_coursenum {
1.1038 raeburn 7000: my ($udom,$crstype) = @_;
1.1011 raeburn 7001: my $domdesc = &domain($udom);
7002: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7003: my $first;
7004: if ($crstype eq 'Community') {
7005: $first = '0';
7006: } else {
7007: $first = int(1+rand(9));
7008: }
7009: my $uname=$first.
1.1011 raeburn 7010: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7011: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7012: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7013: # ----------------------------------------------- Make sure that does not exist
7014: my $uhome=&homeserver($uname,$udom,'true');
7015: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7016: if ($crstype eq 'Community') {
7017: $first = '0';
7018: } else {
7019: $first = int(1+rand(9));
7020: }
7021: $uname=$first.
1.1011 raeburn 7022: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7023: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7024: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7025: $uhome=&homeserver($uname,$udom,'true');
7026: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7027: return 'error: unable to generate unique course-ID';
7028: }
7029: }
7030: return $uname;
7031: }
7032:
1.813 albertel 7033: sub is_course {
7034: my ($cdom,$cnum) = @_;
7035: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7036: undef,'.');
1.813 albertel 7037: if (exists($courses{$cdom.'_'.$cnum})) {
7038: return 1;
7039: }
7040: return 0;
7041: }
7042:
1.1015 raeburn 7043: sub store_userdata {
7044: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7045: my $result;
1.1016 raeburn 7046: if ($datakey ne '') {
1.1013 raeburn 7047: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7048: if ($udom eq '' || $uname eq '') {
7049: $udom = $env{'user.domain'};
7050: $uname = $env{'user.name'};
7051: }
7052: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7053: if (($uhome eq '') || ($uhome eq 'no_host')) {
7054: $result = 'error: no_host';
7055: } else {
7056: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7057: $storehash->{'host'} = $perlvar{'lonHostID'};
7058:
7059: my $namevalue='';
7060: foreach my $key (keys(%{$storehash})) {
7061: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7062: }
7063: $namevalue=~s/\&$//;
7064: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7065: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7066: }
7067: } else {
7068: $result = 'error: data to store was not a hash reference';
7069: }
7070: } else {
7071: $result= 'error: invalid requestkey';
7072: }
7073: return $result;
7074: }
7075:
1.21 www 7076: # ---------------------------------------------------------- Assign Custom Role
7077:
7078: sub assigncustomrole {
1.957 raeburn 7079: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7080: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7081: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7082: }
7083:
7084: # ----------------------------------------------------------------- Revoke Role
7085:
7086: sub revokerole {
1.957 raeburn 7087: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7088: my $now=time;
1.965 raeburn 7089: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7090: }
7091:
7092: # ---------------------------------------------------------- Revoke Custom Role
7093:
7094: sub revokecustomrole {
1.957 raeburn 7095: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7096: my $now=time;
1.357 www 7097: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7098: $deleteflag,$selfenroll,$context);
1.17 www 7099: }
7100:
1.533 banghart 7101: # ------------------------------------------------------------ Disk usage
1.535 albertel 7102: sub diskusage {
1.955 raeburn 7103: my ($udom,$uname,$directorypath,$getpropath)=@_;
7104: $directorypath =~ s/\/$//;
7105: my $listing=&reply('du2:'.&escape($directorypath).':'
7106: .&escape($getpropath).':'.&escape($uname).':'
7107: .&escape($udom),homeserver($uname,$udom));
7108: if ($listing eq 'unknown_cmd') {
7109: if ($getpropath) {
7110: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7111: }
7112: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7113: }
1.514 albertel 7114: return $listing;
1.512 banghart 7115: }
7116:
1.566 banghart 7117: sub is_locked {
7118: my ($file_name, $domain, $user) = @_;
7119: my @check;
7120: my $is_locked;
1.1056.2.10! raeburn 7121: push(@check,$file_name);
1.613 albertel 7122: my %locked = &get('file_permissions',\@check,
1.620 albertel 7123: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7124: my ($tmp)=keys(%locked);
7125: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7126:
1.566 banghart 7127: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7128: $is_locked = 'false';
7129: foreach my $entry (@{$locked{$file_name}}) {
7130: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7131: $is_locked = 'true';
7132: last;
1.745 raeburn 7133: }
7134: }
1.566 banghart 7135: } else {
7136: $is_locked = 'false';
7137: }
1.1056.2.10! raeburn 7138: return $is_locked;
1.566 banghart 7139: }
7140:
1.759 albertel 7141: sub declutter_portfile {
7142: my ($file) = @_;
1.833 albertel 7143: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7144: return $file;
7145: }
7146:
1.559 banghart 7147: # ------------------------------------------------------------- Mark as Read Only
7148:
7149: sub mark_as_readonly {
7150: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7151: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7152: my ($tmp)=keys(%current_permissions);
7153: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7154: foreach my $file (@{$files}) {
1.759 albertel 7155: $file = &declutter_portfile($file);
1.561 banghart 7156: push(@{$current_permissions{$file}},$what);
1.559 banghart 7157: }
1.613 albertel 7158: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7159: return;
7160: }
7161:
1.572 banghart 7162: # ------------------------------------------------------------Save Selected Files
7163:
7164: sub save_selected_files {
7165: my ($user, $path, @files) = @_;
7166: my $filename = $user."savedfiles";
1.573 banghart 7167: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7168: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7169: foreach my $file (@files) {
1.620 albertel 7170: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7171: }
7172: foreach my $file (@other_files) {
1.574 banghart 7173: print (OUT $file."\n");
1.572 banghart 7174: }
1.574 banghart 7175: close (OUT);
1.572 banghart 7176: return 'ok';
7177: }
7178:
1.574 banghart 7179: sub clear_selected_files {
7180: my ($user) = @_;
7181: my $filename = $user."savedfiles";
7182: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7183: print (OUT undef);
7184: close (OUT);
7185: return ("ok");
7186: }
7187:
1.572 banghart 7188: sub files_in_path {
7189: my ($user, $path) = @_;
7190: my $filename = $user."savedfiles";
7191: my %return_files;
1.574 banghart 7192: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7193: while (my $line_in = <IN>) {
1.574 banghart 7194: chomp ($line_in);
7195: my @paths_and_file = split (m!/!, $line_in);
7196: my $file_part = pop (@paths_and_file);
7197: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7198: $path_part.='/';
7199: my $path_and_file = $path_part.$file_part;
7200: if ($path_part eq $path) {
7201: $return_files{$file_part}= 'selected';
7202: }
7203: }
1.574 banghart 7204: close (IN);
7205: return (\%return_files);
1.572 banghart 7206: }
7207:
7208: # called in portfolio select mode, to show files selected NOT in current directory
7209: sub files_not_in_path {
7210: my ($user, $path) = @_;
7211: my $filename = $user."savedfiles";
7212: my @return_files;
7213: my $path_part;
1.800 albertel 7214: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7215: while (my $line = <IN>) {
1.572 banghart 7216: #ok, I know it's clunky, but I want it to work
1.800 albertel 7217: my @paths_and_file = split(m|/|, $line);
7218: my $file_part = pop(@paths_and_file);
7219: chomp($file_part);
7220: my $path_part = join('/', @paths_and_file);
1.572 banghart 7221: $path_part .= '/';
7222: my $path_and_file = $path_part.$file_part;
7223: if ($path_part ne $path) {
1.800 albertel 7224: push(@return_files, ($path_and_file));
1.572 banghart 7225: }
7226: }
1.800 albertel 7227: close(OUT);
1.574 banghart 7228: return (@return_files);
1.572 banghart 7229: }
7230:
1.745 raeburn 7231: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7232:
1.745 raeburn 7233: sub get_portfile_permissions {
7234: my ($domain,$user) = @_;
1.613 albertel 7235: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7236: my ($tmp)=keys(%current_permissions);
7237: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7238: return \%current_permissions;
7239: }
7240:
7241: #---------------------------------------------Get portfolio file access controls
7242:
1.749 raeburn 7243: sub get_access_controls {
1.745 raeburn 7244: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7245: my %access;
7246: my $real_file = $file;
7247: $file =~ s/\.meta$//;
1.745 raeburn 7248: if (defined($file)) {
1.749 raeburn 7249: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7250: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7251: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7252: }
7253: }
1.745 raeburn 7254: } else {
1.749 raeburn 7255: foreach my $key (keys(%{$current_permissions})) {
7256: if ($key =~ /\0accesscontrol$/) {
7257: if (defined($group)) {
7258: if ($key !~ m-^\Q$group\E/-) {
7259: next;
7260: }
7261: }
7262: my ($fullpath) = split(/\0/,$key);
7263: if (ref($$current_permissions{$key}) eq 'HASH') {
7264: foreach my $control (keys(%{$$current_permissions{$key}})) {
7265: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7266: }
7267: }
7268: }
7269: }
7270: }
7271: return %access;
7272: }
7273:
7274: sub modify_access_controls {
7275: my ($file_name,$changes,$domain,$user)=@_;
7276: my ($outcome,$deloutcome);
7277: my %store_permissions;
7278: my %new_values;
7279: my %new_control;
7280: my %translation;
7281: my @deletions = ();
7282: my $now = time;
7283: if (exists($$changes{'activate'})) {
7284: if (ref($$changes{'activate'}) eq 'HASH') {
7285: my @newitems = sort(keys(%{$$changes{'activate'}}));
7286: my $numnew = scalar(@newitems);
7287: for (my $i=0; $i<$numnew; $i++) {
7288: my $newkey = $newitems[$i];
7289: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7290: if ($newkey =~ /^\d+:/) {
7291: $newkey =~ s/^(\d+)/$newid/;
7292: $translation{$1} = $newid;
7293: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7294: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7295: $translation{$1} = $newid;
7296: }
1.749 raeburn 7297: $new_values{$file_name."\0".$newkey} =
7298: $$changes{'activate'}{$newitems[$i]};
7299: $new_control{$newkey} = $now;
7300: }
7301: }
7302: }
7303: my %todelete;
7304: my %changed_items;
7305: foreach my $action ('delete','update') {
7306: if (exists($$changes{$action})) {
7307: if (ref($$changes{$action}) eq 'HASH') {
7308: foreach my $key (keys(%{$$changes{$action}})) {
7309: my ($itemnum) = ($key =~ /^([^:]+):/);
7310: if ($action eq 'delete') {
7311: $todelete{$itemnum} = 1;
7312: } else {
7313: $changed_items{$itemnum} = $key;
7314: }
7315: }
1.745 raeburn 7316: }
7317: }
1.749 raeburn 7318: }
7319: # get lock on access controls for file.
7320: my $lockhash = {
7321: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7322: ':'.$env{'user.domain'},
7323: };
7324: my $tries = 0;
7325: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7326:
7327: while (($gotlock ne 'ok') && $tries <3) {
7328: $tries ++;
7329: sleep 1;
7330: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7331: }
7332: if ($gotlock eq 'ok') {
7333: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7334: my ($tmp)=keys(%curr_permissions);
7335: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7336: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7337: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7338: if (ref($curr_controls) eq 'HASH') {
7339: foreach my $control_item (keys(%{$curr_controls})) {
7340: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7341: if (defined($todelete{$itemnum})) {
7342: push(@deletions,$file_name."\0".$control_item);
7343: } else {
7344: if (defined($changed_items{$itemnum})) {
7345: $new_control{$changed_items{$itemnum}} = $now;
7346: push(@deletions,$file_name."\0".$control_item);
7347: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7348: } else {
7349: $new_control{$control_item} = $$curr_controls{$control_item};
7350: }
7351: }
1.745 raeburn 7352: }
7353: }
7354: }
1.970 raeburn 7355: my ($group);
7356: if (&is_course($domain,$user)) {
7357: ($group,my $file) = split(/\//,$file_name,2);
7358: }
1.749 raeburn 7359: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7360: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7361: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7362: # remove lock
7363: my @del_lock = ($file_name."\0".'locked_access_records');
7364: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7365: my $sqlresult =
1.970 raeburn 7366: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7367: $group);
1.749 raeburn 7368: } else {
7369: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7370: }
1.749 raeburn 7371: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7372: }
7373:
1.827 raeburn 7374: sub make_public_indefinitely {
7375: my ($requrl) = @_;
7376: my $now = time;
7377: my $action = 'activate';
7378: my $aclnum = 0;
7379: if (&is_portfolio_url($requrl)) {
7380: my (undef,$udom,$unum,$file_name,$group) =
7381: &parse_portfolio_url($requrl);
7382: my $current_perms = &get_portfile_permissions($udom,$unum);
7383: my %access_controls = &get_access_controls($current_perms,
7384: $group,$file_name);
7385: foreach my $key (keys(%{$access_controls{$file_name}})) {
7386: my ($num,$scope,$end,$start) =
7387: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7388: if ($scope eq 'public') {
7389: if ($start <= $now && $end == 0) {
7390: $action = 'none';
7391: } else {
7392: $action = 'update';
7393: $aclnum = $num;
7394: }
7395: last;
7396: }
7397: }
7398: if ($action eq 'none') {
7399: return 'ok';
7400: } else {
7401: my %changes;
7402: my $newend = 0;
7403: my $newstart = $now;
7404: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7405: $changes{$action}{$newkey} = {
7406: type => 'public',
7407: time => {
7408: start => $newstart,
7409: end => $newend,
7410: },
7411: };
7412: my ($outcome,$deloutcome,$new_values,$translation) =
7413: &modify_access_controls($file_name,\%changes,$udom,$unum);
7414: return $outcome;
7415: }
7416: } else {
7417: return 'invalid';
7418: }
7419: }
7420:
1.745 raeburn 7421: #------------------------------------------------------Get Marked as Read Only
7422:
7423: sub get_marked_as_readonly {
7424: my ($domain,$user,$what,$group) = @_;
7425: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7426: my @readonly_files;
1.629 banghart 7427: my $cmp1=$what;
7428: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7429: while (my ($file_name,$value) = each(%{$current_permissions})) {
7430: if (defined($group)) {
7431: if ($file_name !~ m-^\Q$group\E/-) {
7432: next;
7433: }
7434: }
1.561 banghart 7435: if (ref($value) eq "ARRAY"){
7436: foreach my $stored_what (@{$value}) {
1.629 banghart 7437: my $cmp2=$stored_what;
1.759 albertel 7438: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7439: $cmp2=join('',@{$stored_what});
1.745 raeburn 7440: }
1.629 banghart 7441: if ($cmp1 eq $cmp2) {
1.561 banghart 7442: push(@readonly_files, $file_name);
1.745 raeburn 7443: last;
1.563 banghart 7444: } elsif (!defined($what)) {
7445: push(@readonly_files, $file_name);
1.745 raeburn 7446: last;
1.561 banghart 7447: }
7448: }
1.745 raeburn 7449: }
1.561 banghart 7450: }
7451: return @readonly_files;
7452: }
1.577 banghart 7453: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7454:
1.577 banghart 7455: sub get_marked_as_readonly_hash {
1.745 raeburn 7456: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7457: my %readonly_files;
1.745 raeburn 7458: while (my ($file_name,$value) = each(%{$current_permissions})) {
7459: if (defined($group)) {
7460: if ($file_name !~ m-^\Q$group\E/-) {
7461: next;
7462: }
7463: }
1.577 banghart 7464: if (ref($value) eq "ARRAY"){
7465: foreach my $stored_what (@{$value}) {
1.745 raeburn 7466: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7467: foreach my $lock_descriptor(@{$stored_what}) {
7468: if ($lock_descriptor eq 'graded') {
7469: $readonly_files{$file_name} = 'graded';
7470: } elsif ($lock_descriptor eq 'handback') {
7471: $readonly_files{$file_name} = 'handback';
7472: } else {
7473: if (!exists($readonly_files{$file_name})) {
7474: $readonly_files{$file_name} = 'locked';
7475: }
7476: }
1.745 raeburn 7477: }
1.750 banghart 7478: }
1.577 banghart 7479: }
7480: }
7481: }
7482: return %readonly_files;
7483: }
1.559 banghart 7484: # ------------------------------------------------------------ Unmark as Read Only
7485:
7486: sub unmark_as_readonly {
1.629 banghart 7487: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7488: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7489: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7490: $file_name = &declutter_portfile($file_name);
1.634 albertel 7491: my $symb_crs = $what;
7492: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7493: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7494: my ($tmp)=keys(%current_permissions);
7495: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7496: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7497: foreach my $file (@readonly_files) {
1.759 albertel 7498: my $clean_file = &declutter_portfile($file);
7499: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7500: my $current_locks = $current_permissions{$file};
1.563 banghart 7501: my @new_locks;
7502: my @del_keys;
7503: if (ref($current_locks) eq "ARRAY"){
7504: foreach my $locker (@{$current_locks}) {
1.632 albertel 7505: my $compare=$locker;
1.749 raeburn 7506: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7507: $compare=join('',@{$locker});
1.746 raeburn 7508: if ($compare ne $symb_crs) {
7509: push(@new_locks, $locker);
7510: }
1.563 banghart 7511: }
7512: }
1.650 albertel 7513: if (scalar(@new_locks) > 0) {
1.563 banghart 7514: $current_permissions{$file} = \@new_locks;
7515: } else {
7516: push(@del_keys, $file);
1.613 albertel 7517: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7518: delete($current_permissions{$file});
1.563 banghart 7519: }
7520: }
1.561 banghart 7521: }
1.613 albertel 7522: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7523: return;
7524: }
1.512 banghart 7525:
1.17 www 7526: # ------------------------------------------------------------ Directory lister
7527:
7528: sub dirlist {
1.955 raeburn 7529: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7530: $uri=~s/^\///;
7531: $uri=~s/\/$//;
1.253 stredwic 7532: my ($udom, $uname);
1.955 raeburn 7533: if ($getuserdir) {
1.253 stredwic 7534: $udom = $userdomain;
7535: $uname = $username;
1.955 raeburn 7536: } else {
7537: (undef,$udom,$uname)=split(/\//,$uri);
7538: if(defined($userdomain)) {
7539: $udom = $userdomain;
7540: }
7541: if(defined($username)) {
7542: $uname = $username;
7543: }
1.253 stredwic 7544: }
1.955 raeburn 7545: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7546:
1.955 raeburn 7547: $dirRoot = $perlvar{'lonDocRoot'};
7548: if (defined($getpropath)) {
7549: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7550: $dirRoot =~ s/\/$//;
1.955 raeburn 7551: } elsif (defined($getuserdir)) {
7552: my $subdir=$uname.'__';
7553: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7554: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7555: ."/$udom/$subdir/$uname";
7556: } elsif (defined($alternateRoot)) {
7557: $dirRoot = $alternateRoot;
1.751 banghart 7558: }
1.253 stredwic 7559:
7560: if($udom) {
7561: if($uname) {
1.955 raeburn 7562: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7563: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7564: .':'.&escape($uname).':'.&escape($udom),
7565: &homeserver($uname,$udom));
7566: if ($listing eq 'unknown_cmd') {
7567: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7568: &homeserver($uname,$udom));
7569: } else {
7570: @listing_results = map { &unescape($_); } split(/:/,$listing);
7571: }
1.605 matthew 7572: if ($listing eq 'unknown_cmd') {
1.800 albertel 7573: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7574: &homeserver($uname,$udom));
1.605 matthew 7575: @listing_results = split(/:/,$listing);
7576: } else {
7577: @listing_results = map { &unescape($_); } split(/:/,$listing);
7578: }
7579: return @listing_results;
1.955 raeburn 7580: } elsif(!$alternateRoot) {
1.800 albertel 7581: my %allusers;
1.841 albertel 7582: my %servers = &get_servers($udom,'library');
1.955 raeburn 7583: foreach my $tryserver (keys(%servers)) {
7584: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7585: &escape($udom),$tryserver);
7586: if ($listing eq 'unknown_cmd') {
7587: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7588: $udom, $tryserver);
7589: } else {
7590: @listing_results = map { &unescape($_); } split(/:/,$listing);
7591: }
1.841 albertel 7592: if ($listing eq 'unknown_cmd') {
7593: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7594: $udom, $tryserver);
7595: @listing_results = split(/:/,$listing);
7596: } else {
7597: @listing_results =
7598: map { &unescape($_); } split(/:/,$listing);
7599: }
7600: if ($listing_results[0] ne 'no_such_dir' &&
7601: $listing_results[0] ne 'empty' &&
7602: $listing_results[0] ne 'con_lost') {
7603: foreach my $line (@listing_results) {
7604: my ($entry) = split(/&/,$line,2);
7605: $allusers{$entry} = 1;
7606: }
7607: }
1.253 stredwic 7608: }
7609: my $alluserstr='';
1.800 albertel 7610: foreach my $user (sort(keys(%allusers))) {
7611: $alluserstr.=$user.'&user:';
1.253 stredwic 7612: }
7613: $alluserstr=~s/:$//;
7614: return split(/:/,$alluserstr);
7615: } else {
1.800 albertel 7616: return ('missing user name');
1.253 stredwic 7617: }
1.955 raeburn 7618: } elsif(!defined($getpropath)) {
1.841 albertel 7619: my @all_domains = sort(&all_domains());
1.955 raeburn 7620: foreach my $domain (@all_domains) {
7621: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7622: }
7623: return @all_domains;
7624: } else {
1.800 albertel 7625: return ('missing domain');
1.275 stredwic 7626: }
7627: }
7628:
7629: # --------------------------------------------- GetFileTimestamp
7630: # This function utilizes dirlist and returns the date stamp for
7631: # when it was last modified. It will also return an error of -1
7632: # if an error occurs
7633:
7634: sub GetFileTimestamp {
1.955 raeburn 7635: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7636: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7637: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7638: my ($fileStat) =
7639: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7640: undef,$getuserdir);
1.275 stredwic 7641: my @stats = split('&', $fileStat);
7642: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7643: # @stats contains first the filename, then the stat output
7644: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7645: } else {
7646: return -1;
1.253 stredwic 7647: }
1.26 www 7648: }
7649:
1.712 albertel 7650: sub stat_file {
7651: my ($uri) = @_;
1.787 albertel 7652: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7653:
1.955 raeburn 7654: my ($udom,$uname,$file);
1.712 albertel 7655: if ($uri =~ m-^/(uploaded|editupload)/-) {
7656: ($udom,$uname,$file) =
1.811 albertel 7657: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7658: $file = 'userfiles/'.$file;
7659: }
7660: if ($uri =~ m-^/res/-) {
7661: ($udom,$uname) =
1.807 albertel 7662: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7663: $file = $uri;
7664: }
7665:
7666: if (!$udom || !$uname || !$file) {
7667: # unable to handle the uri
7668: return ();
7669: }
1.956 raeburn 7670: my $getpropath;
7671: if ($file =~ /^userfiles\//) {
7672: $getpropath = 1;
7673: }
1.955 raeburn 7674: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7675: my @stats = split('&', $result);
1.721 banghart 7676:
1.712 albertel 7677: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7678: shift(@stats); #filename is first
7679: return @stats;
7680: }
7681: return ();
7682: }
7683:
1.26 www 7684: # -------------------------------------------------------- Value of a Condition
7685:
1.713 albertel 7686: # gets the value of a specific preevaluated condition
7687: # stored in the string $env{user.state.<cid>}
7688: # or looks up a condition reference in the bighash and if if hasn't
7689: # already been evaluated recurses into docondval to get the value of
7690: # the condition, then memoizing it to
7691: # $env{user.state.<cid>.<condition>}
1.40 www 7692: sub directcondval {
7693: my $number=shift;
1.620 albertel 7694: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7695: &Apache::lonuserstate::evalstate();
7696: }
1.713 albertel 7697: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7698: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7699: } elsif ($number =~ /^_/) {
7700: my $sub_condition;
7701: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7702: &GDBM_READER(),0640)) {
7703: $sub_condition=$bighash{'conditions'.$number};
7704: untie(%bighash);
7705: }
7706: my $value = &docondval($sub_condition);
1.949 raeburn 7707: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7708: return $value;
7709: }
1.620 albertel 7710: if ($env{'user.state.'.$env{'request.course.id'}}) {
7711: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7712: } else {
7713: return 2;
7714: }
7715: }
7716:
1.713 albertel 7717: # get the collection of conditions for this resource
1.26 www 7718: sub condval {
7719: my $condidx=shift;
1.54 www 7720: my $allpathcond='';
1.713 albertel 7721: foreach my $cond (split(/\|/,$condidx)) {
7722: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7723: $allpathcond.=
7724: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7725: }
1.191 harris41 7726: }
1.54 www 7727: $allpathcond=~s/\|$//;
1.713 albertel 7728: return &docondval($allpathcond);
7729: }
7730:
7731: #evaluates an expression of conditions
7732: sub docondval {
7733: my ($allpathcond) = @_;
7734: my $result=0;
7735: if ($env{'request.course.id'}
7736: && defined($allpathcond)) {
7737: my $operand='|';
7738: my @stack;
7739: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7740: if ($chunk eq '(') {
7741: push @stack,($operand,$result);
7742: } elsif ($chunk eq ')') {
7743: my $before=pop @stack;
7744: if (pop @stack eq '&') {
7745: $result=$result>$before?$before:$result;
7746: } else {
7747: $result=$result>$before?$result:$before;
7748: }
7749: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7750: $operand=$chunk;
7751: } else {
7752: my $new=directcondval($chunk);
7753: if ($operand eq '&') {
7754: $result=$result>$new?$new:$result;
7755: } else {
7756: $result=$result>$new?$result:$new;
7757: }
7758: }
7759: }
1.26 www 7760: }
7761: return $result;
1.421 albertel 7762: }
7763:
7764: # ---------------------------------------------------- Devalidate courseresdata
7765:
7766: sub devalidatecourseresdata {
7767: my ($coursenum,$coursedomain)=@_;
7768: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7769: &devalidate_cache_new('courseres',$hashid);
1.28 www 7770: }
7771:
1.763 www 7772:
1.200 www 7773: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7774: #
7775: # Parameters:
7776: # $coursenum - Number of the course.
7777: # $coursedomain - Domain at which the course was created.
7778: # Returns:
7779: # A hash of the course parameters along (I think) with timestamps
7780: # and version info.
1.877 foxr 7781:
1.624 albertel 7782: sub get_courseresdata {
7783: my ($coursenum,$coursedomain)=@_;
1.200 www 7784: my $coursehom=&homeserver($coursenum,$coursedomain);
7785: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7786: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7787: my %dumpreply;
1.417 albertel 7788: unless (defined($cached)) {
1.624 albertel 7789: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7790: $result=\%dumpreply;
1.251 albertel 7791: my ($tmp) = keys(%dumpreply);
7792: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7793: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7794: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7795: return $tmp;
1.416 albertel 7796: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7797: $result=undef;
1.599 albertel 7798: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7799: }
7800: }
1.624 albertel 7801: return $result;
7802: }
7803:
1.633 albertel 7804: sub devalidateuserresdata {
7805: my ($uname,$udom)=@_;
7806: my $hashid="$udom:$uname";
7807: &devalidate_cache_new('userres',$hashid);
7808: }
7809:
1.624 albertel 7810: sub get_userresdata {
7811: my ($uname,$udom)=@_;
7812: #most student don\'t have any data set, check if there is some data
7813: if (&EXT_cache_status($udom,$uname)) { return undef; }
7814:
7815: my $hashid="$udom:$uname";
7816: my ($result,$cached)=&is_cached_new('userres',$hashid);
7817: if (!defined($cached)) {
7818: my %resourcedata=&dump('resourcedata',$udom,$uname);
7819: $result=\%resourcedata;
7820: &do_cache_new('userres',$hashid,$result,600);
7821: }
7822: my ($tmp)=keys(%$result);
7823: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7824: return $result;
7825: }
7826: #error 2 occurs when the .db doesn't exist
7827: if ($tmp!~/error: 2 /) {
1.672 albertel 7828: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7829: " Trying to get resource data for ".
7830: $uname." at ".$udom.": ".
7831: $tmp."</font>");
7832: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7833: #&EXT_cache_set($udom,$uname);
7834: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7835: undef($tmp); # not really an error so don't send it back
1.624 albertel 7836: }
7837: return $tmp;
7838: }
1.879 foxr 7839: #----------------------------------------------- resdata - return resource data
7840: # Purpose:
7841: # Return resource data for either users or for a course.
7842: # Parameters:
7843: # $name - Course/user name.
7844: # $domain - Name of the domain the user/course is registered on.
7845: # $type - Type of thing $name is (must be 'course' or 'user'
7846: # @which - Array of names of resources desired.
7847: # Returns:
7848: # The value of the first reasource in @which that is found in the
7849: # resource hash.
7850: # Exceptional Conditions:
7851: # If the $type passed in is not valid (not the string 'course' or
7852: # 'user', an undefined reference is returned.
7853: # If none of the resources are found, an undef is returned
1.624 albertel 7854: sub resdata {
7855: my ($name,$domain,$type,@which)=@_;
7856: my $result;
7857: if ($type eq 'course') {
7858: $result=&get_courseresdata($name,$domain);
7859: } elsif ($type eq 'user') {
7860: $result=&get_userresdata($name,$domain);
7861: }
7862: if (!ref($result)) { return $result; }
1.251 albertel 7863: foreach my $item (@which) {
1.927 albertel 7864: if (defined($result->{$item->[0]})) {
7865: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7866: }
1.250 albertel 7867: }
1.291 albertel 7868: return undef;
1.200 www 7869: }
7870:
1.379 matthew 7871: #
7872: # EXT resource caching routines
7873: #
7874:
7875: sub clear_EXT_cache_status {
1.383 albertel 7876: &delenv('cache.EXT.');
1.379 matthew 7877: }
7878:
7879: sub EXT_cache_status {
7880: my ($target_domain,$target_user) = @_;
1.383 albertel 7881: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7882: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7883: # We know already the user has no data
7884: return 1;
7885: } else {
7886: return 0;
7887: }
7888: }
7889:
7890: sub EXT_cache_set {
7891: my ($target_domain,$target_user) = @_;
1.383 albertel 7892: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7893: #&appenv({$cachename => time});
1.379 matthew 7894: }
7895:
1.28 www 7896: # --------------------------------------------------------- Value of a Variable
1.58 www 7897: sub EXT {
1.715 albertel 7898:
1.395 albertel 7899: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7900: unless ($varname) { return ''; }
1.218 albertel 7901: #get real user name/domain, courseid and symb
7902: my $courseid;
1.359 albertel 7903: my $publicuser;
1.427 www 7904: if ($symbparm) {
7905: $symbparm=&get_symb_from_alias($symbparm);
7906: }
1.218 albertel 7907: if (!($uname && $udom)) {
1.790 albertel 7908: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7909: if (!$symbparm) { $symbparm=$cursymb; }
7910: } else {
1.620 albertel 7911: $courseid=$env{'request.course.id'};
1.218 albertel 7912: }
1.48 www 7913: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7914: my $rest;
1.320 albertel 7915: if (defined($therest[0])) {
1.48 www 7916: $rest=join('.',@therest);
7917: } else {
7918: $rest='';
7919: }
1.320 albertel 7920:
1.57 www 7921: my $qualifierrest=$qualifier;
7922: if ($rest) { $qualifierrest.='.'.$rest; }
7923: my $spacequalifierrest=$space;
7924: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7925: if ($realm eq 'user') {
1.48 www 7926: # --------------------------------------------------------------- user.resource
7927: if ($space eq 'resource') {
1.651 albertel 7928: if ( (defined($Apache::lonhomework::parsing_a_problem)
7929: || defined($Apache::lonhomework::parsing_a_task))
7930: &&
1.744 albertel 7931: ($symbparm eq &symbread()) ) {
7932: # if we are in the middle of processing the resource the
7933: # get the value we are planning on committing
7934: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7935: return $Apache::lonhomework::results{$qualifierrest};
7936: } else {
7937: return $Apache::lonhomework::history{$qualifierrest};
7938: }
1.335 albertel 7939: } else {
1.359 albertel 7940: my %restored;
1.620 albertel 7941: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7942: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7943: } else {
7944: %restored=&restore($symbparm,$courseid,$udom,$uname);
7945: }
1.335 albertel 7946: return $restored{$qualifierrest};
7947: }
1.48 www 7948: # ----------------------------------------------------------------- user.access
7949: } elsif ($space eq 'access') {
1.218 albertel 7950: # FIXME - not supporting calls for a specific user
1.48 www 7951: return &allowed($qualifier,$rest);
7952: # ------------------------------------------ user.preferences, user.environment
7953: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7954: if (($uname eq $env{'user.name'}) &&
7955: ($udom eq $env{'user.domain'})) {
7956: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7957: } else {
1.359 albertel 7958: my %returnhash;
7959: if (!$publicuser) {
7960: %returnhash=&userenvironment($udom,$uname,
7961: $qualifierrest);
7962: }
1.218 albertel 7963: return $returnhash{$qualifierrest};
7964: }
1.48 www 7965: # ----------------------------------------------------------------- user.course
7966: } elsif ($space eq 'course') {
1.218 albertel 7967: # FIXME - not supporting calls for a specific user
1.620 albertel 7968: return $env{join('.',('request.course',$qualifier))};
1.48 www 7969: # ------------------------------------------------------------------- user.role
7970: } elsif ($space eq 'role') {
1.218 albertel 7971: # FIXME - not supporting calls for a specific user
1.620 albertel 7972: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7973: if ($qualifier eq 'value') {
7974: return $role;
7975: } elsif ($qualifier eq 'extent') {
7976: return $where;
7977: }
7978: # ----------------------------------------------------------------- user.domain
7979: } elsif ($space eq 'domain') {
1.218 albertel 7980: return $udom;
1.48 www 7981: # ------------------------------------------------------------------- user.name
7982: } elsif ($space eq 'name') {
1.218 albertel 7983: return $uname;
1.48 www 7984: # ---------------------------------------------------- Any other user namespace
1.29 www 7985: } else {
1.359 albertel 7986: my %reply;
7987: if (!$publicuser) {
7988: %reply=&get($space,[$qualifierrest],$udom,$uname);
7989: }
7990: return $reply{$qualifierrest};
1.48 www 7991: }
1.236 www 7992: } elsif ($realm eq 'query') {
7993: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7994: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7995: [$spacequalifierrest]);
1.620 albertel 7996: return $env{'form.'.$spacequalifierrest};
1.236 www 7997: } elsif ($realm eq 'request') {
1.48 www 7998: # ------------------------------------------------------------- request.browser
7999: if ($space eq 'browser') {
1.430 www 8000: if ($qualifier eq 'textremote') {
1.676 albertel 8001: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8002: return 1;
8003: } else {
8004: return 0;
8005: }
8006: } else {
1.620 albertel 8007: return $env{'browser.'.$qualifier};
1.430 www 8008: }
1.57 www 8009: # ------------------------------------------------------------ request.filename
8010: } else {
1.620 albertel 8011: return $env{'request.'.$spacequalifierrest};
1.29 www 8012: }
1.28 www 8013: } elsif ($realm eq 'course') {
1.48 www 8014: # ---------------------------------------------------------- course.description
1.620 albertel 8015: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8016: } elsif ($realm eq 'resource') {
1.165 www 8017:
1.620 albertel 8018: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8019: if (!$symbparm) { $symbparm=&symbread(); }
8020: }
1.693 albertel 8021:
8022: if ($space eq 'title') {
8023: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8024: return &gettitle($symbparm);
8025: }
8026:
8027: if ($space eq 'map') {
8028: my ($map) = &decode_symb($symbparm);
8029: return &symbread($map);
8030: }
1.905 albertel 8031: if ($space eq 'filename') {
8032: if ($symbparm) {
8033: return &clutter((&decode_symb($symbparm))[2]);
8034: }
8035: return &hreflocation('',$env{'request.filename'});
8036: }
1.693 albertel 8037:
8038: my ($section, $group, @groups);
1.593 albertel 8039: my ($courselevelm,$courselevel);
1.539 albertel 8040: if ($symbparm && defined($courseid) &&
1.620 albertel 8041: $courseid eq $env{'request.course.id'}) {
1.165 www 8042:
1.218 albertel 8043: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8044:
1.60 www 8045: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8046: my $symbp=$symbparm;
1.735 albertel 8047: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8048:
8049: my $symbparm=$symbp.'.'.$spacequalifierrest;
8050: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8051:
1.620 albertel 8052: if (($env{'user.name'} eq $uname) &&
8053: ($env{'user.domain'} eq $udom)) {
8054: $section=$env{'request.course.sec'};
1.733 raeburn 8055: @groups = split(/:/,$env{'request.course.groups'});
8056: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8057: } else {
1.539 albertel 8058: if (! defined($usection)) {
1.551 albertel 8059: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8060: } else {
8061: $section = $usection;
8062: }
1.733 raeburn 8063: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8064: }
8065:
8066: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8067: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8068: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8069:
1.593 albertel 8070: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8071: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8072: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8073:
1.60 www 8074: # ----------------------------------------------------------- first, check user
1.624 albertel 8075:
8076: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8077: ([$courselevelr,'resource'],
8078: [$courselevelm,'map' ],
8079: [$courselevel, 'course' ]));
1.931 albertel 8080: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8081:
1.594 albertel 8082: # ------------------------------------------------ second, check some of course
1.684 raeburn 8083: my $coursereply;
1.691 raeburn 8084: if (@groups > 0) {
8085: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8086: $mapparm,$spacequalifierrest);
1.927 albertel 8087: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8088: }
1.96 www 8089:
1.684 raeburn 8090: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8091: $env{'course.'.$courseid.'.domain'},
8092: 'course',
8093: ([$seclevelr, 'resource'],
8094: [$seclevelm, 'map' ],
8095: [$seclevel, 'course' ],
8096: [$courselevelr,'resource']));
8097: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8098:
1.60 www 8099: # ------------------------------------------------------ third, check map parms
1.218 albertel 8100: my %parmhash=();
8101: my $thisparm='';
8102: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8103: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8104: &GDBM_READER(),0640)) {
1.218 albertel 8105: $thisparm=$parmhash{$symbparm};
8106: untie(%parmhash);
8107: }
1.927 albertel 8108: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8109: }
1.594 albertel 8110: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8111:
1.218 albertel 8112: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8113: my $filename;
8114: if (!$symbparm) { $symbparm=&symbread(); }
8115: if ($symbparm) {
1.409 www 8116: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8117: } else {
1.620 albertel 8118: $filename=$env{'request.filename'};
1.282 albertel 8119: }
8120: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8121: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8122: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8123: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8124:
1.927 albertel 8125: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8126: if ($symbparm && defined($courseid) &&
1.620 albertel 8127: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8128: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8129: $env{'course.'.$courseid.'.domain'},
8130: 'course',
1.927 albertel 8131: ([$courselevelm,'map' ],
8132: [$courselevel, 'course']));
8133: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8134: }
1.145 www 8135: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8136: unless ($space eq '0') {
1.336 albertel 8137: my @parts=split(/_/,$space);
8138: my $id=pop(@parts);
8139: my $part=join('_',@parts);
8140: if ($part eq '') { $part='0'; }
1.927 albertel 8141: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8142: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8143: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8144: }
1.395 albertel 8145: if ($recurse) { return undef; }
8146: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8147: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8148: # ---------------------------------------------------- Any other user namespace
8149: } elsif ($realm eq 'environment') {
8150: # ----------------------------------------------------------------- environment
1.620 albertel 8151: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8152: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8153: } else {
1.770 albertel 8154: if ($uname eq 'anonymous' && $udom eq '') {
8155: return '';
8156: }
1.219 albertel 8157: my %returnhash=&userenvironment($udom,$uname,
8158: $spacequalifierrest);
8159: return $returnhash{$spacequalifierrest};
8160: }
1.28 www 8161: } elsif ($realm eq 'system') {
1.48 www 8162: # ----------------------------------------------------------------- system.time
8163: if ($space eq 'time') {
8164: return time;
8165: }
1.696 albertel 8166: } elsif ($realm eq 'server') {
8167: # ----------------------------------------------------------------- system.time
8168: if ($space eq 'name') {
8169: return $ENV{'SERVER_NAME'};
8170: }
1.28 www 8171: }
1.48 www 8172: return '';
1.61 www 8173: }
8174:
1.927 albertel 8175: sub get_reply {
8176: my ($reply_value) = @_;
1.940 raeburn 8177: if (ref($reply_value) eq 'ARRAY') {
8178: if (wantarray) {
8179: return @$reply_value;
8180: }
8181: return $reply_value->[0];
8182: } else {
8183: return $reply_value;
1.927 albertel 8184: }
8185: }
8186:
1.691 raeburn 8187: sub check_group_parms {
8188: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8189: my @groupitems = ();
8190: my $resultitem;
1.927 albertel 8191: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8192: foreach my $group (@{$groups}) {
8193: foreach my $level (@levels) {
1.927 albertel 8194: my $item = $courseid.'.['.$group.'].'.$level->[0];
8195: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8196: }
8197: }
8198: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8199: $env{'course.'.$courseid.'.domain'},
8200: 'course',@groupitems);
8201: return $coursereply;
8202: }
8203:
8204: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8205: my ($courseid,@groups) = @_;
8206: @groups = sort(@groups);
1.691 raeburn 8207: return @groups;
8208: }
8209:
1.395 albertel 8210: sub packages_tab_default {
8211: my ($uri,$varname)=@_;
8212: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8213:
8214: my (@extension,@specifics,$do_default);
8215: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8216: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8217: if ($pack_type eq 'default') {
8218: $do_default=1;
8219: } elsif ($pack_type eq 'extension') {
8220: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8221: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8222: # only look at packages defaults for packages that this id is
1.738 albertel 8223: push(@specifics,[$package,$pack_type,$pack_part]);
8224: }
8225: }
8226: # first look for a package that matches the requested part id
8227: foreach my $package (@specifics) {
8228: my (undef,$pack_type,$pack_part)=@{$package};
8229: next if ($pack_part ne $part);
8230: if (defined($packagetab{"$pack_type&$name&default"})) {
8231: return $packagetab{"$pack_type&$name&default"};
8232: }
8233: }
8234: # look for any possible matching non extension_ package
8235: foreach my $package (@specifics) {
8236: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8237: if (defined($packagetab{"$pack_type&$name&default"})) {
8238: return $packagetab{"$pack_type&$name&default"};
8239: }
1.585 albertel 8240: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8241: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8242: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8243: }
8244: }
1.738 albertel 8245: # look for any posible extension_ match
8246: foreach my $package (@extension) {
8247: my ($package,$pack_type)=@{$package};
8248: if (defined($packagetab{"$pack_type&$name&default"})) {
8249: return $packagetab{"$pack_type&$name&default"};
8250: }
8251: if (defined($packagetab{$package."&$name&default"})) {
8252: return $packagetab{$package."&$name&default"};
8253: }
8254: }
8255: # look for a global default setting
8256: if ($do_default && defined($packagetab{"default&$name&default"})) {
8257: return $packagetab{"default&$name&default"};
8258: }
1.395 albertel 8259: return undef;
8260: }
8261:
1.334 albertel 8262: sub add_prefix_and_part {
8263: my ($prefix,$part)=@_;
8264: my $keyroot;
8265: if (defined($prefix) && $prefix !~ /^__/) {
8266: # prefix that has a part already
8267: $keyroot=$prefix;
8268: } elsif (defined($prefix)) {
8269: # prefix that is missing a part
8270: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8271: } else {
8272: # no prefix at all
8273: if (defined($part)) { $keyroot='_'.$part; }
8274: }
8275: return $keyroot;
8276: }
8277:
1.71 www 8278: # ---------------------------------------------------------------- Get metadata
8279:
1.599 albertel 8280: my %metaentry;
1.71 www 8281: sub metadata {
1.176 www 8282: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8283: $uri=&declutter($uri);
1.288 albertel 8284: # if it is a non metadata possible uri return quickly
1.529 albertel 8285: if (($uri eq '') ||
8286: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8287: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8288: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8289: return undef;
8290: }
8291: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8292: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8293: return undef;
1.288 albertel 8294: }
1.73 www 8295: my $filename=$uri;
8296: $uri=~s/\.meta$//;
1.172 www 8297: #
8298: # Is the metadata already cached?
1.177 www 8299: # Look at timestamp of caching
1.172 www 8300: # Everything is cached by the main uri, libraries are never directly cached
8301: #
1.428 albertel 8302: if (!defined($liburi)) {
1.599 albertel 8303: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8304: if (defined($cached)) { return $result->{':'.$what}; }
8305: }
8306: {
1.172 www 8307: #
8308: # Is this a recursive call for a library?
8309: #
1.599 albertel 8310: # if (! exists($metacache{$uri})) {
8311: # $metacache{$uri}={};
8312: # }
1.924 albertel 8313: my $cachetime = 60*60;
1.171 www 8314: if ($liburi) {
8315: $liburi=&declutter($liburi);
8316: $filename=$liburi;
1.401 bowersj2 8317: } else {
1.599 albertel 8318: &devalidate_cache_new('meta',$uri);
8319: undef(%metaentry);
1.401 bowersj2 8320: }
1.140 www 8321: my %metathesekeys=();
1.73 www 8322: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8323: my $metastring;
1.924 albertel 8324: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8325: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8326: $metastring =
1.929 albertel 8327: &Apache::lonnet::ssi_body($which,
1.924 albertel 8328: ('grade_target' => 'meta'));
8329: $cachetime = 1; # only want this cached in the child not long term
8330: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8331: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8332: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8333: $metastring=&getfile($file);
1.489 albertel 8334: }
1.208 albertel 8335: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8336: my $token;
1.140 www 8337: undef %metathesekeys;
1.71 www 8338: while ($token=$parser->get_token) {
1.339 albertel 8339: if ($token->[0] eq 'S') {
8340: if (defined($token->[2]->{'package'})) {
1.172 www 8341: #
8342: # This is a package - get package info
8343: #
1.339 albertel 8344: my $package=$token->[2]->{'package'};
8345: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8346: if (defined($token->[2]->{'id'})) {
8347: $keyroot.='_'.$token->[2]->{'id'};
8348: }
1.599 albertel 8349: if ($metaentry{':packages'}) {
8350: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8351: } else {
1.599 albertel 8352: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8353: }
1.736 albertel 8354: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8355: my $part=$keyroot;
8356: $part=~s/^\_//;
1.736 albertel 8357: if ($pack_entry=~/^\Q$package\E\&/ ||
8358: $pack_entry=~/^\Q$package\E_0\&/) {
8359: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8360: # ignore package.tab specified default values
8361: # here &package_tab_default() will fetch those
8362: if ($subp eq 'default') { next; }
1.736 albertel 8363: my $value=$packagetab{$pack_entry};
1.432 albertel 8364: my $unikey;
8365: if ($pack =~ /_0$/) {
8366: $unikey='parameter_0_'.$name;
8367: $part=0;
8368: } else {
8369: $unikey='parameter'.$keyroot.'_'.$name;
8370: }
1.339 albertel 8371: if ($subp eq 'display') {
8372: $value.=' [Part: '.$part.']';
8373: }
1.599 albertel 8374: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8375: $metathesekeys{$unikey}=1;
1.599 albertel 8376: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8377: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8378: }
1.599 albertel 8379: if (defined($metaentry{':'.$unikey.'.default'})) {
8380: $metaentry{':'.$unikey}=
8381: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8382: }
1.339 albertel 8383: }
8384: }
8385: } else {
1.172 www 8386: #
8387: # This is not a package - some other kind of start tag
1.339 albertel 8388: #
8389: my $entry=$token->[1];
8390: my $unikey;
8391: if ($entry eq 'import') {
8392: $unikey='';
8393: } else {
8394: $unikey=$entry;
8395: }
8396: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8397:
8398: if (defined($token->[2]->{'id'})) {
8399: $unikey.='_'.$token->[2]->{'id'};
8400: }
1.175 www 8401:
1.339 albertel 8402: if ($entry eq 'import') {
1.175 www 8403: #
8404: # Importing a library here
1.339 albertel 8405: #
8406: if ($depthcount<20) {
8407: my $location=$parser->get_text('/import');
8408: my $dir=$filename;
8409: $dir=~s|[^/]*$||;
8410: $location=&filelocation($dir,$location);
1.736 albertel 8411: my $metadata =
8412: &metadata($uri,'keys', $location,$unikey,
8413: $depthcount+1);
8414: foreach my $meta (split(',',$metadata)) {
8415: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8416: $metathesekeys{$meta}=1;
1.339 albertel 8417: }
8418: }
8419: } else {
8420:
8421: if (defined($token->[2]->{'name'})) {
8422: $unikey.='_'.$token->[2]->{'name'};
8423: }
8424: $metathesekeys{$unikey}=1;
1.736 albertel 8425: foreach my $param (@{$token->[3]}) {
8426: $metaentry{':'.$unikey.'.'.$param} =
8427: $token->[2]->{$param};
1.339 albertel 8428: }
8429: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8430: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8431: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8432: # only ws inside the tag, and not in default, so use default
8433: # as value
1.599 albertel 8434: $metaentry{':'.$unikey}=$default;
1.908 albertel 8435: } elsif ( $internaltext =~ /\S/ ) {
8436: # something interesting inside the tag
8437: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8438: } else {
1.908 albertel 8439: # no interesting values, don't set a default
1.339 albertel 8440: }
1.172 www 8441: # end of not-a-package not-a-library import
1.339 albertel 8442: }
1.172 www 8443: # end of not-a-package start tag
1.339 albertel 8444: }
1.172 www 8445: # the next is the end of "start tag"
1.339 albertel 8446: }
8447: }
1.483 albertel 8448: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8449: $extension = lc($extension);
8450: if ($extension eq 'htm') { $extension='html'; }
8451:
1.737 albertel 8452: foreach my $key (keys(%packagetab)) {
1.483 albertel 8453: #no specific packages #how's our extension
8454: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8455: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8456: \%metathesekeys);
8457: }
1.883 albertel 8458:
8459: if (!exists($metaentry{':packages'})
8460: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8461: foreach my $key (keys(%packagetab)) {
1.483 albertel 8462: #no specific packages well let's get default then
8463: if ($key!~/^default&/) { next; }
1.488 albertel 8464: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8465: \%metathesekeys);
8466: }
8467: }
1.338 www 8468: # are there custom rights to evaluate
1.599 albertel 8469: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8470:
1.338 www 8471: #
8472: # Importing a rights file here
1.339 albertel 8473: #
8474: unless ($depthcount) {
1.599 albertel 8475: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8476: my $dir=$filename;
8477: $dir=~s|[^/]*$||;
8478: $location=&filelocation($dir,$location);
1.736 albertel 8479: my $rights_metadata =
8480: &metadata($uri,'keys',$location,'_rights',
8481: $depthcount+1);
8482: foreach my $rights (split(',',$rights_metadata)) {
8483: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8484: $metathesekeys{$rights}=1;
1.339 albertel 8485: }
8486: }
8487: }
1.737 albertel 8488: # uniqifiy package listing
8489: my %seen;
8490: my @uniq_packages =
8491: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8492: $metaentry{':packages'} = join(',',@uniq_packages);
8493:
8494: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8495: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8496: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8497: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8498: # this is the end of "was not already recently cached
1.71 www 8499: }
1.599 albertel 8500: return $metaentry{':'.$what};
1.261 albertel 8501: }
8502:
1.488 albertel 8503: sub metadata_create_package_def {
1.483 albertel 8504: my ($uri,$key,$package,$metathesekeys)=@_;
8505: my ($pack,$name,$subp)=split(/\&/,$key);
8506: if ($subp eq 'default') { next; }
8507:
1.599 albertel 8508: if (defined($metaentry{':packages'})) {
8509: $metaentry{':packages'}.=','.$package;
1.483 albertel 8510: } else {
1.599 albertel 8511: $metaentry{':packages'}=$package;
1.483 albertel 8512: }
8513: my $value=$packagetab{$key};
8514: my $unikey;
8515: $unikey='parameter_0_'.$name;
1.599 albertel 8516: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8517: $$metathesekeys{$unikey}=1;
1.599 albertel 8518: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8519: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8520: }
1.599 albertel 8521: if (defined($metaentry{':'.$unikey.'.default'})) {
8522: $metaentry{':'.$unikey}=
8523: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8524: }
8525: }
8526:
1.261 albertel 8527: sub metadata_generate_part0 {
8528: my ($metadata,$metacache,$uri) = @_;
8529: my %allnames;
1.737 albertel 8530: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8531: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8532: my $part=$$metacache{':'.$metakey.'.part'};
8533: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8534: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8535: $allnames{$name}=$part;
8536: }
8537: }
8538: }
8539: foreach my $name (keys(%allnames)) {
8540: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8541: my $key=":parameter_0_$name";
1.261 albertel 8542: $$metacache{"$key.part"}='0';
8543: $$metacache{"$key.name"}=$name;
1.428 albertel 8544: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8545: $allnames{$name}.'_'.$name.
8546: '.type'};
1.428 albertel 8547: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8548: '.display'};
1.644 www 8549: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8550: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8551: $$metacache{"$key.display"}=$olddis;
8552: }
1.71 www 8553: }
8554:
1.764 albertel 8555: # ------------------------------------------------------ Devalidate title cache
8556:
8557: sub devalidate_title_cache {
8558: my ($url)=@_;
8559: if (!$env{'request.course.id'}) { return; }
8560: my $symb=&symbread($url);
8561: if (!$symb) { return; }
8562: my $key=$env{'request.course.id'}."\0".$symb;
8563: &devalidate_cache_new('title',$key);
8564: }
8565:
1.1014 droeschl 8566: # ------------------------------------------------- Get the title of a course
8567:
8568: sub current_course_title {
8569: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8570: }
1.301 www 8571: # ------------------------------------------------- Get the title of a resource
8572:
8573: sub gettitle {
8574: my $urlsymb=shift;
8575: my $symb=&symbread($urlsymb);
1.534 albertel 8576: if ($symb) {
1.620 albertel 8577: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8578: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8579: if (defined($cached)) {
8580: return $result;
8581: }
1.534 albertel 8582: my ($map,$resid,$url)=&decode_symb($symb);
8583: my $title='';
1.907 albertel 8584: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8585: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8586: } else {
8587: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8588: &GDBM_READER(),0640)) {
8589: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8590: $title=$bighash{'title_'.$mapid.'.'.$resid};
8591: untie(%bighash);
8592: }
1.534 albertel 8593: }
8594: $title=~s/\&colon\;/\:/gs;
8595: if ($title) {
1.599 albertel 8596: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8597: }
8598: $urlsymb=$url;
8599: }
8600: my $title=&metadata($urlsymb,'title');
8601: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8602: return $title;
1.301 www 8603: }
1.613 albertel 8604:
1.614 albertel 8605: sub get_slot {
8606: my ($which,$cnum,$cdom)=@_;
8607: if (!$cnum || !$cdom) {
1.790 albertel 8608: (undef,my $courseid)=&whichuser();
1.620 albertel 8609: $cdom=$env{'course.'.$courseid.'.domain'};
8610: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8611: }
1.703 albertel 8612: my $key=join("\0",'slots',$cdom,$cnum,$which);
8613: my %slotinfo;
8614: if (exists($remembered{$key})) {
8615: $slotinfo{$which} = $remembered{$key};
8616: } else {
8617: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8618: &Apache::lonhomework::showhash(%slotinfo);
8619: my ($tmp)=keys(%slotinfo);
8620: if ($tmp=~/^error:/) { return (); }
8621: $remembered{$key} = $slotinfo{$which};
8622: }
1.616 albertel 8623: if (ref($slotinfo{$which}) eq 'HASH') {
8624: return %{$slotinfo{$which}};
8625: }
8626: return $slotinfo{$which};
1.614 albertel 8627: }
1.31 www 8628: # ------------------------------------------------- Update symbolic store links
8629:
8630: sub symblist {
8631: my ($mapname,%newhash)=@_;
1.438 www 8632: $mapname=&deversion(&declutter($mapname));
1.31 www 8633: my %hash;
1.620 albertel 8634: if (($env{'request.course.fn'}) && (%newhash)) {
8635: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8636: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8637: foreach my $url (keys(%newhash)) {
1.711 albertel 8638: next if ($url eq 'last_known'
8639: && $env{'form.no_update_last_known'});
8640: $hash{declutter($url)}=&encode_symb($mapname,
8641: $newhash{$url}->[1],
8642: $newhash{$url}->[0]);
1.191 harris41 8643: }
1.31 www 8644: if (untie(%hash)) {
8645: return 'ok';
8646: }
8647: }
8648: }
8649: return 'error';
1.212 www 8650: }
8651:
8652: # --------------------------------------------------------------- Verify a symb
8653:
8654: sub symbverify {
1.510 www 8655: my ($symb,$thisurl)=@_;
8656: my $thisfn=$thisurl;
1.439 www 8657: $thisfn=&declutter($thisfn);
1.215 www 8658: # direct jump to resource in page or to a sequence - will construct own symbs
8659: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8660: # check URL part
1.409 www 8661: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8662:
1.431 www 8663: unless ($url eq $thisfn) { return 0; }
1.213 www 8664:
1.216 www 8665: $symb=&symbclean($symb);
1.510 www 8666: $thisurl=&deversion($thisurl);
1.439 www 8667: $thisfn=&deversion($thisfn);
1.213 www 8668:
8669: my %bighash;
8670: my $okay=0;
1.431 www 8671:
1.620 albertel 8672: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8673: &GDBM_READER(),0640)) {
1.1032 raeburn 8674: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8675: $thisurl =~ s/\?.+$//;
8676: }
1.510 www 8677: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8678: unless ($ids) {
1.510 www 8679: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8680: }
8681: if ($ids) {
8682: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8683: foreach my $id (split(/\,/,$ids)) {
8684: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8685: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8686: $symb =~ s/\?.+$//;
8687: }
1.216 www 8688: if (
8689: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8690: eq $symb) {
1.620 albertel 8691: if (($env{'request.role.adv'}) ||
1.800 albertel 8692: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8693: $okay=1;
8694: }
8695: }
1.216 www 8696: }
8697: }
1.213 www 8698: untie(%bighash);
8699: }
8700: return $okay;
1.31 www 8701: }
8702:
1.210 www 8703: # --------------------------------------------------------------- Clean-up symb
8704:
8705: sub symbclean {
8706: my $symb=shift;
1.568 albertel 8707: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8708: # remove version from map
8709: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8710:
1.210 www 8711: # remove version from URL
8712: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8713:
1.507 www 8714: # remove wrapper
8715:
1.510 www 8716: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8717: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8718: return $symb;
1.409 www 8719: }
8720:
8721: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8722:
8723: sub encode_symb {
8724: my ($map,$resid,$url)=@_;
8725: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8726: }
1.409 www 8727:
8728: sub decode_symb {
1.568 albertel 8729: my $symb=shift;
8730: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8731: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8732: return (&fixversion($map),$resid,&fixversion($url));
8733: }
8734:
8735: sub fixversion {
8736: my $fn=shift;
1.609 banghart 8737: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8738: my %bighash;
8739: my $uri=&clutter($fn);
1.620 albertel 8740: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8741: # is this cached?
1.599 albertel 8742: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8743: if (defined($cached)) { return $result; }
8744: # unfortunately not cached, or expired
1.620 albertel 8745: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8746: &GDBM_READER(),0640)) {
8747: if ($bighash{'version_'.$uri}) {
8748: my $version=$bighash{'version_'.$uri};
1.444 www 8749: unless (($version eq 'mostrecent') ||
8750: ($version==&getversion($uri))) {
1.440 www 8751: $uri=~s/\.(\w+)$/\.$version\.$1/;
8752: }
8753: }
8754: untie %bighash;
1.413 www 8755: }
1.599 albertel 8756: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8757: }
8758:
8759: sub deversion {
8760: my $url=shift;
8761: $url=~s/\.\d+\.(\w+)$/\.$1/;
8762: return $url;
1.210 www 8763: }
8764:
1.31 www 8765: # ------------------------------------------------------ Return symb list entry
8766:
8767: sub symbread {
1.249 www 8768: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8769: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8770: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8771: # no filename provided? try from environment
1.44 www 8772: unless ($thisfn) {
1.620 albertel 8773: if ($env{'request.symb'}) {
8774: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8775: }
1.620 albertel 8776: $thisfn=$env{'request.filename'};
1.44 www 8777: }
1.569 albertel 8778: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8779: # is that filename actually a symb? Verify, clean, and return
8780: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8781: if (&symbverify($thisfn,$1)) {
1.620 albertel 8782: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8783: }
1.242 www 8784: }
1.44 www 8785: $thisfn=declutter($thisfn);
1.31 www 8786: my %hash;
1.37 www 8787: my %bighash;
8788: my $syval='';
1.620 albertel 8789: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8790: my $targetfn = $thisfn;
1.609 banghart 8791: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8792: $targetfn = 'adm/wrapper/'.$thisfn;
8793: }
1.687 albertel 8794: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8795: $targetfn=$1;
8796: }
1.620 albertel 8797: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8798: &GDBM_READER(),0640)) {
1.481 raeburn 8799: $syval=$hash{$targetfn};
1.37 www 8800: untie(%hash);
8801: }
8802: # ---------------------------------------------------------- There was an entry
8803: if ($syval) {
1.601 albertel 8804: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8805: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8806: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8807: #return $env{$cache_str}='';
1.601 albertel 8808: #}
8809: #$syval.=$1;
8810: #}
1.37 www 8811: } else {
8812: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8813: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8814: &GDBM_READER(),0640)) {
1.37 www 8815: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8816: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8817: unless ($ids) {
8818: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8819: }
8820: unless ($ids) {
8821: # alias?
8822: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8823: }
1.37 www 8824: if ($ids) {
8825: # ------------------------------------------------------------------- Has ID(s)
8826: my @possibilities=split(/\,/,$ids);
1.39 www 8827: if ($#possibilities==0) {
8828: # ----------------------------------------------- There is only one possibility
1.37 www 8829: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8830: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8831: $resid,$thisfn);
1.249 www 8832: } elsif (!$donotrecurse) {
1.39 www 8833: # ------------------------------------------ There is more than one possibility
8834: my $realpossible=0;
1.800 albertel 8835: foreach my $id (@possibilities) {
8836: my $file=$bighash{'src_'.$id};
1.39 www 8837: if (&allowed('bre',$file)) {
1.800 albertel 8838: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8839: if ($bighash{'map_type_'.$mapid} ne 'page') {
8840: $realpossible++;
1.626 albertel 8841: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8842: $resid,$thisfn);
1.39 www 8843: }
8844: }
1.191 harris41 8845: }
1.39 www 8846: if ($realpossible!=1) { $syval=''; }
1.249 www 8847: } else {
8848: $syval='';
1.37 www 8849: }
8850: }
8851: untie(%bighash)
1.481 raeburn 8852: }
1.31 www 8853: }
1.62 www 8854: if ($syval) {
1.620 albertel 8855: return $env{$cache_str}=$syval;
1.62 www 8856: }
1.31 www 8857: }
1.949 raeburn 8858: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8859: return $env{$cache_str}='';
1.31 www 8860: }
8861:
8862: # ---------------------------------------------------------- Return random seed
8863:
1.32 www 8864: sub numval {
8865: my $txt=shift;
8866: $txt=~tr/A-J/0-9/;
8867: $txt=~tr/a-j/0-9/;
8868: $txt=~tr/K-T/0-9/;
8869: $txt=~tr/k-t/0-9/;
8870: $txt=~tr/U-Z/0-5/;
8871: $txt=~tr/u-z/0-5/;
8872: $txt=~s/\D//g;
1.564 albertel 8873: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8874: return int($txt);
1.368 albertel 8875: }
8876:
1.484 albertel 8877: sub numval2 {
8878: my $txt=shift;
8879: $txt=~tr/A-J/0-9/;
8880: $txt=~tr/a-j/0-9/;
8881: $txt=~tr/K-T/0-9/;
8882: $txt=~tr/k-t/0-9/;
8883: $txt=~tr/U-Z/0-5/;
8884: $txt=~tr/u-z/0-5/;
8885: $txt=~s/\D//g;
8886: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8887: my $total;
8888: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8889: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8890: return int($total);
8891: }
8892:
1.575 albertel 8893: sub numval3 {
8894: use integer;
8895: my $txt=shift;
8896: $txt=~tr/A-J/0-9/;
8897: $txt=~tr/a-j/0-9/;
8898: $txt=~tr/K-T/0-9/;
8899: $txt=~tr/k-t/0-9/;
8900: $txt=~tr/U-Z/0-5/;
8901: $txt=~tr/u-z/0-5/;
8902: $txt=~s/\D//g;
8903: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8904: my $total;
8905: foreach my $val (@txts) { $total+=$val; }
8906: if ($_64bit) { $total=(($total<<32)>>32); }
8907: return $total;
8908: }
8909:
1.675 albertel 8910: sub digest {
8911: my ($data)=@_;
8912: my $digest=&Digest::MD5::md5($data);
8913: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8914: my ($e,$f);
8915: {
8916: use integer;
8917: $e=($a+$b);
8918: $f=($c+$d);
8919: if ($_64bit) {
8920: $e=(($e<<32)>>32);
8921: $f=(($f<<32)>>32);
8922: }
8923: }
8924: if (wantarray) {
8925: return ($e,$f);
8926: } else {
8927: my $g;
8928: {
8929: use integer;
8930: $g=($e+$f);
8931: if ($_64bit) {
8932: $g=(($g<<32)>>32);
8933: }
8934: }
8935: return $g;
8936: }
8937: }
8938:
1.368 albertel 8939: sub latest_rnd_algorithm_id {
1.675 albertel 8940: return '64bit5';
1.366 albertel 8941: }
1.32 www 8942:
1.503 albertel 8943: sub get_rand_alg {
8944: my ($courseid)=@_;
1.790 albertel 8945: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8946: if ($courseid) {
1.620 albertel 8947: return $env{"course.$courseid.rndseed"};
1.503 albertel 8948: }
8949: return &latest_rnd_algorithm_id();
8950: }
8951:
1.562 albertel 8952: sub validCODE {
8953: my ($CODE)=@_;
8954: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8955: return 0;
8956: }
8957:
1.491 albertel 8958: sub getCODE {
1.620 albertel 8959: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8960: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8961: defined($Apache::lonhomework::parsing_a_task) ) &&
8962: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8963: return $Apache::lonhomework::history{'resource.CODE'};
8964: }
8965: return undef;
8966: }
8967:
1.31 www 8968: sub rndseed {
1.155 albertel 8969: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8970: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8971: if (!defined($symb)) {
1.366 albertel 8972: unless ($symb=$wsymb) { return time; }
8973: }
8974: if (!$courseid) { $courseid=$wcourseid; }
8975: if (!$domain) { $domain=$wdomain; }
8976: if (!$username) { $username=$wusername }
1.503 albertel 8977: my $which=&get_rand_alg();
1.803 albertel 8978:
1.491 albertel 8979: if (defined(&getCODE())) {
1.675 albertel 8980: if ($which eq '64bit5') {
8981: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8982: } elsif ($which eq '64bit4') {
1.575 albertel 8983: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8984: } else {
8985: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8986: }
1.675 albertel 8987: } elsif ($which eq '64bit5') {
8988: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8989: } elsif ($which eq '64bit4') {
8990: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8991: } elsif ($which eq '64bit3') {
8992: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8993: } elsif ($which eq '64bit2') {
8994: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8995: } elsif ($which eq '64bit') {
8996: return &rndseed_64bit($symb,$courseid,$domain,$username);
8997: }
8998: return &rndseed_32bit($symb,$courseid,$domain,$username);
8999: }
9000:
9001: sub rndseed_32bit {
9002: my ($symb,$courseid,$domain,$username)=@_;
9003: {
9004: use integer;
9005: my $symbchck=unpack("%32C*",$symb) << 27;
9006: my $symbseed=numval($symb) << 22;
9007: my $namechck=unpack("%32C*",$username) << 17;
9008: my $nameseed=numval($username) << 12;
9009: my $domainseed=unpack("%32C*",$domain) << 7;
9010: my $courseseed=unpack("%32C*",$courseid);
9011: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9012: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9013: #&logthis("rndseed :$num:$symb");
1.564 albertel 9014: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9015: return $num;
9016: }
9017: }
9018:
9019: sub rndseed_64bit {
9020: my ($symb,$courseid,$domain,$username)=@_;
9021: {
9022: use integer;
9023: my $symbchck=unpack("%32S*",$symb) << 21;
9024: my $symbseed=numval($symb) << 10;
9025: my $namechck=unpack("%32S*",$username);
9026:
9027: my $nameseed=numval($username) << 21;
9028: my $domainseed=unpack("%32S*",$domain) << 10;
9029: my $courseseed=unpack("%32S*",$courseid);
9030:
9031: my $num1=$symbchck+$symbseed+$namechck;
9032: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9033: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9034: #&logthis("rndseed :$num:$symb");
1.564 albertel 9035: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9036: return "$num1,$num2";
1.155 albertel 9037: }
1.366 albertel 9038: }
9039:
1.443 albertel 9040: sub rndseed_64bit2 {
9041: my ($symb,$courseid,$domain,$username)=@_;
9042: {
9043: use integer;
9044: # strings need to be an even # of cahracters long, it it is odd the
9045: # last characters gets thrown away
9046: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9047: my $symbseed=numval($symb) << 10;
9048: my $namechck=unpack("%32S*",$username.' ');
9049:
9050: my $nameseed=numval($username) << 21;
1.501 albertel 9051: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9052: my $courseseed=unpack("%32S*",$courseid.' ');
9053:
9054: my $num1=$symbchck+$symbseed+$namechck;
9055: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9056: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9057: #&logthis("rndseed :$num:$symb");
1.803 albertel 9058: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9059: return "$num1,$num2";
9060: }
9061: }
9062:
9063: sub rndseed_64bit3 {
9064: my ($symb,$courseid,$domain,$username)=@_;
9065: {
9066: use integer;
9067: # strings need to be an even # of cahracters long, it it is odd the
9068: # last characters gets thrown away
9069: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9070: my $symbseed=numval2($symb) << 10;
9071: my $namechck=unpack("%32S*",$username.' ');
9072:
9073: my $nameseed=numval2($username) << 21;
1.443 albertel 9074: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9075: my $courseseed=unpack("%32S*",$courseid.' ');
9076:
9077: my $num1=$symbchck+$symbseed+$namechck;
9078: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9079: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9080: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9081: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9082:
1.503 albertel 9083: return "$num1:$num2";
1.443 albertel 9084: }
9085: }
9086:
1.575 albertel 9087: sub rndseed_64bit4 {
9088: my ($symb,$courseid,$domain,$username)=@_;
9089: {
9090: use integer;
9091: # strings need to be an even # of cahracters long, it it is odd the
9092: # last characters gets thrown away
9093: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9094: my $symbseed=numval3($symb) << 10;
9095: my $namechck=unpack("%32S*",$username.' ');
9096:
9097: my $nameseed=numval3($username) << 21;
9098: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9099: my $courseseed=unpack("%32S*",$courseid.' ');
9100:
9101: my $num1=$symbchck+$symbseed+$namechck;
9102: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9103: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9104: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9105: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9106:
9107: return "$num1:$num2";
9108: }
9109: }
9110:
1.675 albertel 9111: sub rndseed_64bit5 {
9112: my ($symb,$courseid,$domain,$username)=@_;
9113: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9114: return "$num1:$num2";
9115: }
9116:
1.366 albertel 9117: sub rndseed_CODE_64bit {
9118: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9119: {
1.366 albertel 9120: use integer;
1.443 albertel 9121: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9122: my $symbseed=numval2($symb);
1.491 albertel 9123: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9124: my $CODEseed=numval(&getCODE());
1.443 albertel 9125: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9126: my $num1=$symbseed+$CODEchck;
9127: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9128: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9129: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9130: if ($_64bit) { $num1=(($num1<<32)>>32); }
9131: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9132: return "$num1:$num2";
1.366 albertel 9133: }
9134: }
9135:
1.575 albertel 9136: sub rndseed_CODE_64bit4 {
9137: my ($symb,$courseid,$domain,$username)=@_;
9138: {
9139: use integer;
9140: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9141: my $symbseed=numval3($symb);
9142: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9143: my $CODEseed=numval3(&getCODE());
9144: my $courseseed=unpack("%32S*",$courseid.' ');
9145: my $num1=$symbseed+$CODEchck;
9146: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9147: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9148: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9149: if ($_64bit) { $num1=(($num1<<32)>>32); }
9150: if ($_64bit) { $num2=(($num2<<32)>>32); }
9151: return "$num1:$num2";
9152: }
9153: }
9154:
1.675 albertel 9155: sub rndseed_CODE_64bit5 {
9156: my ($symb,$courseid,$domain,$username)=@_;
9157: my $code = &getCODE();
9158: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9159: return "$num1:$num2";
9160: }
9161:
1.366 albertel 9162: sub setup_random_from_rndseed {
9163: my ($rndseed)=@_;
1.503 albertel 9164: if ($rndseed =~/([,:])/) {
9165: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9166: &Math::Random::random_set_seed(abs($num1),abs($num2));
9167: } else {
9168: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9169: }
1.36 albertel 9170: }
9171:
1.474 albertel 9172: sub latest_receipt_algorithm_id {
1.835 albertel 9173: return 'receipt3';
1.474 albertel 9174: }
9175:
1.480 www 9176: sub recunique {
9177: my $fucourseid=shift;
9178: my $unique;
1.835 albertel 9179: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9180: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9181: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9182: } else {
9183: $unique=$perlvar{'lonReceipt'};
9184: }
9185: return unpack("%32C*",$unique);
9186: }
9187:
9188: sub recprefix {
9189: my $fucourseid=shift;
9190: my $prefix;
1.835 albertel 9191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9192: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9193: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9194: } else {
9195: $prefix=$perlvar{'lonHostID'};
9196: }
9197: return unpack("%32C*",$prefix);
9198: }
9199:
1.76 www 9200: sub ireceipt {
1.474 albertel 9201: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9202:
9203: my $return =&recprefix($fucourseid).'-';
9204:
9205: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9206: $env{'request.state'} eq 'construct') {
9207: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9208: return $return;
9209: }
9210:
1.76 www 9211: my $cuname=unpack("%32C*",$funame);
9212: my $cudom=unpack("%32C*",$fudom);
9213: my $cucourseid=unpack("%32C*",$fucourseid);
9214: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9215: my $cunique=&recunique($fucourseid);
1.474 albertel 9216: my $cpart=unpack("%32S*",$part);
1.835 albertel 9217: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9218:
1.790 albertel 9219: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9220:
9221: $return.= ($cunique%$cuname+
9222: $cunique%$cudom+
9223: $cusymb%$cuname+
9224: $cusymb%$cudom+
9225: $cucourseid%$cuname+
9226: $cucourseid%$cudom+
9227: $cpart%$cuname+
9228: $cpart%$cudom);
9229: } else {
9230: $return.= ($cunique%$cuname+
9231: $cunique%$cudom+
9232: $cusymb%$cuname+
9233: $cusymb%$cudom+
9234: $cucourseid%$cuname+
9235: $cucourseid%$cudom);
9236: }
9237: return $return;
1.76 www 9238: }
9239:
9240: sub receipt {
1.474 albertel 9241: my ($part)=@_;
1.790 albertel 9242: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9243: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9244: }
1.260 ng 9245:
1.790 albertel 9246: sub whichuser {
9247: my ($passedsymb)=@_;
9248: my ($symb,$courseid,$domain,$name,$publicuser);
9249: if (defined($env{'form.grade_symb'})) {
9250: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9251: my $allowed=&allowed('vgr',$tmp_courseid);
9252: if (!$allowed &&
9253: exists($env{'request.course.sec'}) &&
9254: $env{'request.course.sec'} !~ /^\s*$/) {
9255: $allowed=&allowed('vgr',$tmp_courseid.
9256: '/'.$env{'request.course.sec'});
9257: }
9258: if ($allowed) {
9259: ($symb)=&get_env_multiple('form.grade_symb');
9260: $courseid=$tmp_courseid;
9261: ($domain)=&get_env_multiple('form.grade_domain');
9262: ($name)=&get_env_multiple('form.grade_username');
9263: return ($symb,$courseid,$domain,$name,$publicuser);
9264: }
9265: }
9266: if (!$passedsymb) {
9267: $symb=&symbread();
9268: } else {
9269: $symb=$passedsymb;
9270: }
9271: $courseid=$env{'request.course.id'};
9272: $domain=$env{'user.domain'};
9273: $name=$env{'user.name'};
9274: if ($name eq 'public' && $domain eq 'public') {
9275: if (!defined($env{'form.username'})) {
9276: $env{'form.username'}.=time.rand(10000000);
9277: }
9278: $name.=$env{'form.username'};
9279: }
9280: return ($symb,$courseid,$domain,$name,$publicuser);
9281:
9282: }
9283:
1.36 albertel 9284: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9285: # returns either the contents of the file or
9286: # -1 if the file doesn't exist
1.481 raeburn 9287: #
9288: # if the target is a file that was uploaded via DOCS,
9289: # a check will be made to see if a current copy exists on the local server,
9290: # if it does this will be served, otherwise a copy will be retrieved from
9291: # the home server for the course and stored in /home/httpd/html/userfiles on
9292: # the local server.
1.472 albertel 9293:
1.36 albertel 9294: sub getfile {
1.538 albertel 9295: my ($file) = @_;
1.609 banghart 9296: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9297: &repcopy($file);
9298: return &readfile($file);
9299: }
9300:
9301: sub repcopy_userfile {
9302: my ($file)=@_;
1.609 banghart 9303: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9304: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9305: my ($cdom,$cnum,$filename) =
1.811 albertel 9306: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9307: my $uri="/uploaded/$cdom/$cnum/$filename";
9308: if (-e "$file") {
1.828 www 9309: # we already have a local copy, check it out
1.538 albertel 9310: my @fileinfo = stat($file);
1.828 www 9311: my $rtncode;
9312: my $info;
1.538 albertel 9313: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9314: if ($lwpresp ne 'ok') {
1.828 www 9315: # there is no such file anymore, even though we had a local copy
1.482 albertel 9316: if ($rtncode eq '404') {
1.538 albertel 9317: unlink($file);
1.482 albertel 9318: }
9319: return -1;
9320: }
9321: if ($info < $fileinfo[9]) {
1.828 www 9322: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9323: return 'ok';
1.828 www 9324: } else {
9325: # the file is outdated, get rid of it
9326: unlink($file);
1.482 albertel 9327: }
1.828 www 9328: }
9329: # one way or the other, at this point, we don't have the file
9330: # construct the correct path for the file
9331: my @parts = ($cdom,$cnum);
9332: if ($filename =~ m|^(.+)/[^/]+$|) {
9333: push @parts, split(/\//,$1);
9334: }
9335: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9336: foreach my $part (@parts) {
9337: $path .= '/'.$part;
9338: if (!-e $path) {
9339: mkdir($path,0770);
1.482 albertel 9340: }
9341: }
1.828 www 9342: # now the path exists for sure
9343: # get a user agent
9344: my $ua=new LWP::UserAgent;
9345: my $transferfile=$file.'.in.transfer';
9346: # FIXME: this should flock
9347: if (-e $transferfile) { return 'ok'; }
9348: my $request;
9349: $uri=~s/^\///;
1.980 raeburn 9350: my $homeserver = &homeserver($cnum,$cdom);
9351: my $protocol = $protocol{$homeserver};
9352: $protocol = 'http' if ($protocol ne 'https');
9353: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9354: my $response=$ua->request($request,$transferfile);
9355: # did it work?
9356: if ($response->is_error()) {
9357: unlink($transferfile);
9358: &logthis("Userfile repcopy failed for $uri");
9359: return -1;
9360: }
9361: # worked, rename the transfer file
9362: rename($transferfile,$file);
1.607 raeburn 9363: return 'ok';
1.481 raeburn 9364: }
9365:
1.517 albertel 9366: sub tokenwrapper {
9367: my $uri=shift;
1.980 raeburn 9368: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9369: $uri=~s|^/||;
1.620 albertel 9370: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9371: my $token=$1;
1.552 albertel 9372: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9373: if ($udom && $uname && $file) {
9374: $file=~s|(\?\.*)*$||;
1.949 raeburn 9375: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9376: my $homeserver = &homeserver($uname,$udom);
9377: my $protocol = $protocol{$homeserver};
9378: $protocol = 'http' if ($protocol ne 'https');
9379: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9380: (($uri=~/\?/)?'&':'?').'token='.$token.
9381: '&tokenissued='.$perlvar{'lonHostID'};
9382: } else {
9383: return '/adm/notfound.html';
9384: }
9385: }
9386:
1.828 www 9387: # call with reqtype HEAD: get last modification time
9388: # call with reqtype GET: get the file contents
9389: # Do not call this with reqtype GET for large files! It loads everything into memory
9390: #
1.481 raeburn 9391: sub getuploaded {
9392: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9393: $uri=~s/^\///;
1.980 raeburn 9394: my $homeserver = &homeserver($cnum,$cdom);
9395: my $protocol = $protocol{$homeserver};
9396: $protocol = 'http' if ($protocol ne 'https');
9397: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9398: my $ua=new LWP::UserAgent;
9399: my $request=new HTTP::Request($reqtype,$uri);
9400: my $response=$ua->request($request);
9401: $$rtncode = $response->code;
1.482 albertel 9402: if (! $response->is_success()) {
9403: return 'failed';
9404: }
9405: if ($reqtype eq 'HEAD') {
1.486 www 9406: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9407: } elsif ($reqtype eq 'GET') {
9408: $$info = $response->content;
1.472 albertel 9409: }
1.482 albertel 9410: return 'ok';
1.36 albertel 9411: }
9412:
1.481 raeburn 9413: sub readfile {
9414: my $file = shift;
9415: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9416: my $fh;
9417: open($fh,"<$file");
9418: my $a='';
1.800 albertel 9419: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9420: return $a;
9421: }
9422:
1.36 albertel 9423: sub filelocation {
1.590 banghart 9424: my ($dir,$file) = @_;
9425: my $location;
9426: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9427:
9428: if ($file =~ m-^/adm/-) {
9429: $file=~s-^/adm/wrapper/-/-;
9430: $file=~s-^/adm/coursedocs/showdoc/-/-;
9431: }
1.882 albertel 9432:
1.590 banghart 9433: if ($file=~m:^/~:) { # is a contruction space reference
9434: $location = $file;
9435: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9436: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9437: # is a correct contruction space reference
9438: $location = $file;
1.956 raeburn 9439: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9440: $location = $file;
1.609 banghart 9441: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9442: my ($udom,$uname,$filename)=
1.811 albertel 9443: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9444: my $home=&homeserver($uname,$udom);
9445: my $is_me=0;
9446: my @ids=¤t_machine_ids();
9447: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9448: if ($is_me) {
1.955 raeburn 9449: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9450: } else {
9451: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9452: $udom.'/'.$uname.'/'.$filename;
9453: }
1.882 albertel 9454: } elsif ($file =~ m-^/adm/-) {
9455: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9456: } else {
9457: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9458: $file=~s:^/res/:/:;
9459: if ( !( $file =~ m:^/:) ) {
9460: $location = $dir. '/'.$file;
9461: } else {
9462: $location = '/home/httpd/html/res'.$file;
9463: }
1.59 albertel 9464: }
1.590 banghart 9465: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9466: while ($location=~m{/\.\./}) {
9467: if ($location =~ m{/[^/]+/\.\./}) {
9468: $location=~ s{/[^/]+/\.\./}{/}g;
9469: } else {
9470: $location=~ s{/\.\./}{/}g;
9471: }
9472: } #remove dir/..
1.590 banghart 9473: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9474: return $location;
1.46 www 9475: }
1.36 albertel 9476:
1.46 www 9477: sub hreflocation {
9478: my ($dir,$file)=@_;
1.980 raeburn 9479: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9480: $file=filelocation($dir,$file);
1.700 albertel 9481: } elsif ($file=~m-^/adm/-) {
9482: $file=~s-^/adm/wrapper/-/-;
9483: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9484: }
9485: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9486: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9487: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9488: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9489: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9490: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9491: -/uploaded/$1/$2/-x;
1.46 www 9492: }
1.913 albertel 9493: if ($file=~ m{^/userfiles/}) {
9494: $file =~ s{^/userfiles/}{/uploaded/};
9495: }
1.462 albertel 9496: return $file;
1.465 albertel 9497: }
9498:
9499: sub current_machine_domains {
1.853 albertel 9500: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9501: }
9502:
9503: sub machine_domains {
9504: my ($hostname) = @_;
1.465 albertel 9505: my @domains;
1.838 albertel 9506: my %hostname = &all_hostnames();
1.465 albertel 9507: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9508: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9509: if ($hostname eq $name) {
1.844 albertel 9510: push(@domains,&host_domain($id));
1.465 albertel 9511: }
9512: }
9513: return @domains;
9514: }
9515:
9516: sub current_machine_ids {
1.853 albertel 9517: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9518: }
9519:
9520: sub machine_ids {
9521: my ($hostname) = @_;
9522: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9523: my @ids;
1.888 albertel 9524: my %name_to_host = &all_names();
1.889 albertel 9525: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9526: return @{ $name_to_host{$hostname} };
9527: }
9528: return;
1.31 www 9529: }
9530:
1.824 raeburn 9531: sub additional_machine_domains {
9532: my @domains;
9533: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9534: while( my $line = <$fh>) {
9535: $line =~ s/\s//g;
9536: push(@domains,$line);
9537: }
9538: return @domains;
9539: }
9540:
9541: sub default_login_domain {
9542: my $domain = $perlvar{'lonDefDomain'};
9543: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9544: foreach my $posdom (¤t_machine_domains(),
9545: &additional_machine_domains()) {
9546: if (lc($posdom) eq lc($testdomain)) {
9547: $domain=$posdom;
9548: last;
9549: }
9550: }
9551: return $domain;
9552: }
9553:
1.31 www 9554: # ------------------------------------------------------------- Declutters URLs
9555:
9556: sub declutter {
9557: my $thisfn=shift;
1.569 albertel 9558: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9559: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9560: $thisfn=~s/^\///;
1.697 albertel 9561: $thisfn=~s|^adm/wrapper/||;
9562: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9563: $thisfn=~s/^res\///;
1.1032 raeburn 9564: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9565: $thisfn=~s/\?.+$//;
9566: }
1.268 www 9567: return $thisfn;
9568: }
9569:
9570: # ------------------------------------------------------------- Clutter up URLs
9571:
9572: sub clutter {
9573: my $thisfn='/'.&declutter(shift);
1.887 albertel 9574: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9575: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9576: $thisfn='/res'.$thisfn;
9577: }
1.1031 raeburn 9578: if ($thisfn !~m|^/adm|) {
9579: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9580: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9581: } else {
9582: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9583: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9584: if ($embstyle eq 'ssi'
9585: || ($embstyle eq 'hdn')
9586: || ($embstyle eq 'rat')
9587: || ($embstyle eq 'prv')
9588: || ($embstyle eq 'ign')) {
9589: #do nothing with these
9590: } elsif (($embstyle eq 'img')
1.695 albertel 9591: || ($embstyle eq 'emb')
9592: || ($embstyle eq 'wrp')) {
9593: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9594: } elsif ($embstyle eq 'unk'
9595: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9596: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9597: } else {
1.718 www 9598: # &logthis("Got a blank emb style");
1.695 albertel 9599: }
1.694 albertel 9600: }
9601: }
1.31 www 9602: return $thisfn;
1.12 www 9603: }
9604:
1.787 albertel 9605: sub clutter_with_no_wrapper {
9606: my $uri = &clutter(shift);
9607: if ($uri =~ m-^/adm/-) {
9608: $uri =~ s-^/adm/wrapper/-/-;
9609: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9610: }
9611: return $uri;
9612: }
9613:
1.557 albertel 9614: sub freeze_escape {
9615: my ($value)=@_;
9616: if (ref($value)) {
9617: $value=&nfreeze($value);
9618: return '__FROZEN__'.&escape($value);
9619: }
9620: return &escape($value);
9621: }
9622:
1.11 www 9623:
1.557 albertel 9624: sub thaw_unescape {
9625: my ($value)=@_;
9626: if ($value =~ /^__FROZEN__/) {
9627: substr($value,0,10,undef);
9628: $value=&unescape($value);
9629: return &thaw($value);
9630: }
9631: return &unescape($value);
9632: }
9633:
1.436 albertel 9634: sub correct_line_ends {
9635: my ($result)=@_;
9636: $$result =~s/\r\n/\n/mg;
9637: $$result =~s/\r/\n/mg;
1.415 albertel 9638: }
1.1 albertel 9639: # ================================================================ Main Program
9640:
1.184 www 9641: sub goodbye {
1.204 albertel 9642: &logthis("Starting Shut down");
1.443 albertel 9643: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9644: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9645: #converted
1.599 albertel 9646: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9647: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9648: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9649: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9650: #1.1 only
1.870 albertel 9651: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9652: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9653: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9654: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9655: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9656: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9657: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9658: &flushcourselogs();
9659: &logthis("Shutting down");
9660: }
9661:
1.852 albertel 9662: sub get_dns {
1.869 albertel 9663: my ($url,$func,$ignore_cache) = @_;
9664: if (!$ignore_cache) {
9665: my ($content,$cached)=
9666: &Apache::lonnet::is_cached_new('dns',$url);
9667: if ($cached) {
9668: &$func($content);
9669: return;
9670: }
9671: }
9672:
9673: my %alldns;
1.852 albertel 9674: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9675: foreach my $dns (<$config>) {
9676: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9677: my $line = $1;
9678: my ($host,$protocol) = split(/:/,$line);
9679: if ($protocol ne 'https') {
9680: $protocol = 'http';
9681: }
9682: $alldns{$host} = $protocol;
1.869 albertel 9683: }
9684: while (%alldns) {
9685: my ($dns) = keys(%alldns);
1.852 albertel 9686: my $ua=new LWP::UserAgent;
1.979 raeburn 9687: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9688: my $response=$ua->request($request);
1.979 raeburn 9689: delete($alldns{$dns});
1.852 albertel 9690: next if ($response->is_error());
9691: my @content = split("\n",$response->content);
1.869 albertel 9692: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9693: &$func(\@content);
1.869 albertel 9694: return;
1.852 albertel 9695: }
9696: close($config);
1.871 albertel 9697: my $which = (split('/',$url))[3];
9698: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9699: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9700: my @content = <$config>;
9701: &$func(\@content);
9702: return;
1.852 albertel 9703: }
1.327 albertel 9704: # ------------------------------------------------------------ Read domain file
9705: {
1.852 albertel 9706: my $loaded;
1.846 albertel 9707: my %domain;
9708:
1.852 albertel 9709: sub parse_domain_tab {
9710: my ($lines) = @_;
9711: foreach my $line (@$lines) {
9712: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9713:
1.846 albertel 9714: chomp($line);
1.852 albertel 9715: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9716: my %this_domain;
9717: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9718: 'lang_def', 'city', 'longi', 'lati',
9719: 'primary') {
9720: $this_domain{$field} = shift(@elements);
9721: }
9722: $domain{$name} = \%this_domain;
1.852 albertel 9723: }
9724: }
1.864 albertel 9725:
9726: sub reset_domain_info {
9727: undef($loaded);
9728: undef(%domain);
9729: }
9730:
1.852 albertel 9731: sub load_domain_tab {
1.869 albertel 9732: my ($ignore_cache) = @_;
9733: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9734: my $fh;
9735: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9736: my @lines = <$fh>;
9737: &parse_domain_tab(\@lines);
1.448 albertel 9738: }
1.852 albertel 9739: close($fh);
9740: $loaded = 1;
1.327 albertel 9741: }
1.846 albertel 9742:
9743: sub domain {
1.852 albertel 9744: &load_domain_tab() if (!$loaded);
9745:
1.846 albertel 9746: my ($name,$what) = @_;
9747: return if ( !exists($domain{$name}) );
9748:
9749: if (!$what) {
9750: return $domain{$name}{'description'};
9751: }
9752: return $domain{$name}{$what};
9753: }
1.974 raeburn 9754:
9755: sub domain_info {
9756: &load_domain_tab() if (!$loaded);
9757: return %domain;
9758: }
9759:
1.327 albertel 9760: }
9761:
9762:
1.1 albertel 9763: # ------------------------------------------------------------- Read hosts file
9764: {
1.838 albertel 9765: my %hostname;
1.844 albertel 9766: my %hostdom;
1.845 albertel 9767: my %libserv;
1.852 albertel 9768: my $loaded;
1.888 albertel 9769: my %name_to_host;
1.852 albertel 9770:
9771: sub parse_hosts_tab {
9772: my ($file) = @_;
9773: foreach my $configline (@$file) {
9774: next if ($configline =~ /^(\#|\s*$ )/x);
9775: next if ($configline =~ /^\^/);
9776: chomp($configline);
1.968 raeburn 9777: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9778: $name=~s/\s//g;
9779: if ($id && $domain && $role && $name) {
9780: $hostname{$id}=$name;
1.888 albertel 9781: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9782: $hostdom{$id}=$domain;
9783: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9784: if (defined($protocol)) {
9785: if ($protocol eq 'https') {
9786: $protocol{$id} = $protocol;
9787: } else {
9788: $protocol{$id} = 'http';
9789: }
1.968 raeburn 9790: } else {
1.969 raeburn 9791: $protocol{$id} = 'http';
1.968 raeburn 9792: }
1.852 albertel 9793: }
9794: }
9795: }
1.864 albertel 9796:
9797: sub reset_hosts_info {
1.897 albertel 9798: &purge_remembered();
1.864 albertel 9799: &reset_domain_info();
9800: &reset_hosts_ip_info();
1.892 albertel 9801: undef(%name_to_host);
1.864 albertel 9802: undef(%hostname);
9803: undef(%hostdom);
9804: undef(%libserv);
9805: undef($loaded);
9806: }
1.1 albertel 9807:
1.852 albertel 9808: sub load_hosts_tab {
1.869 albertel 9809: my ($ignore_cache) = @_;
9810: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9811: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9812: my @config = <$config>;
9813: &parse_hosts_tab(\@config);
9814: close($config);
9815: $loaded=1;
1.1 albertel 9816: }
1.852 albertel 9817:
1.838 albertel 9818: sub hostname {
1.852 albertel 9819: &load_hosts_tab() if (!$loaded);
9820:
1.838 albertel 9821: my ($lonid) = @_;
9822: return $hostname{$lonid};
9823: }
1.845 albertel 9824:
1.838 albertel 9825: sub all_hostnames {
1.852 albertel 9826: &load_hosts_tab() if (!$loaded);
9827:
1.838 albertel 9828: return %hostname;
9829: }
1.845 albertel 9830:
1.888 albertel 9831: sub all_names {
9832: &load_hosts_tab() if (!$loaded);
9833:
9834: return %name_to_host;
9835: }
9836:
1.974 raeburn 9837: sub all_host_domain {
9838: &load_hosts_tab() if (!$loaded);
9839: return %hostdom;
9840: }
9841:
1.845 albertel 9842: sub is_library {
1.852 albertel 9843: &load_hosts_tab() if (!$loaded);
9844:
1.845 albertel 9845: return exists($libserv{$_[0]});
9846: }
9847:
9848: sub all_library {
1.852 albertel 9849: &load_hosts_tab() if (!$loaded);
9850:
1.845 albertel 9851: return %libserv;
9852: }
9853:
1.841 albertel 9854: sub get_servers {
1.852 albertel 9855: &load_hosts_tab() if (!$loaded);
9856:
1.841 albertel 9857: my ($domain,$type) = @_;
9858: my %possible_hosts = ($type eq 'library') ? %libserv
9859: : %hostname;
9860: my %result;
1.842 albertel 9861: if (ref($domain) eq 'ARRAY') {
9862: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9863: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9864: $result{$host} = $hostname;
9865: }
9866: }
9867: } else {
9868: while ( my ($host,$hostname) = each(%possible_hosts)) {
9869: if ($hostdom{$host} eq $domain) {
9870: $result{$host} = $hostname;
9871: }
1.841 albertel 9872: }
9873: }
9874: return %result;
9875: }
1.845 albertel 9876:
1.844 albertel 9877: sub host_domain {
1.852 albertel 9878: &load_hosts_tab() if (!$loaded);
9879:
1.844 albertel 9880: my ($lonid) = @_;
9881: return $hostdom{$lonid};
9882: }
9883:
1.841 albertel 9884: sub all_domains {
1.852 albertel 9885: &load_hosts_tab() if (!$loaded);
9886:
1.841 albertel 9887: my %seen;
9888: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9889: return @uniq;
9890: }
1.1 albertel 9891: }
9892:
1.847 albertel 9893: {
9894: my %iphost;
1.856 albertel 9895: my %name_to_ip;
9896: my %lonid_to_ip;
1.869 albertel 9897:
1.847 albertel 9898: sub get_hosts_from_ip {
9899: my ($ip) = @_;
9900: my %iphosts = &get_iphost();
9901: if (ref($iphosts{$ip})) {
9902: return @{$iphosts{$ip}};
9903: }
9904: return;
1.839 albertel 9905: }
1.864 albertel 9906:
9907: sub reset_hosts_ip_info {
9908: undef(%iphost);
9909: undef(%name_to_ip);
9910: undef(%lonid_to_ip);
9911: }
1.856 albertel 9912:
9913: sub get_host_ip {
9914: my ($lonid) = @_;
9915: if (exists($lonid_to_ip{$lonid})) {
9916: return $lonid_to_ip{$lonid};
9917: }
9918: my $name=&hostname($lonid);
9919: my $ip = gethostbyname($name);
9920: return if (!$ip || length($ip) ne 4);
9921: $ip=inet_ntoa($ip);
9922: $name_to_ip{$name} = $ip;
9923: $lonid_to_ip{$lonid} = $ip;
9924: return $ip;
9925: }
1.847 albertel 9926:
9927: sub get_iphost {
1.869 albertel 9928: my ($ignore_cache) = @_;
1.894 albertel 9929:
1.869 albertel 9930: if (!$ignore_cache) {
9931: if (%iphost) {
9932: return %iphost;
9933: }
9934: my ($ip_info,$cached)=
9935: &Apache::lonnet::is_cached_new('iphost','iphost');
9936: if ($cached) {
9937: %iphost = %{$ip_info->[0]};
9938: %name_to_ip = %{$ip_info->[1]};
9939: %lonid_to_ip = %{$ip_info->[2]};
9940: return %iphost;
9941: }
9942: }
1.894 albertel 9943:
9944: # get yesterday's info for fallback
9945: my %old_name_to_ip;
9946: my ($ip_info,$cached)=
9947: &Apache::lonnet::is_cached_new('iphost','iphost');
9948: if ($cached) {
9949: %old_name_to_ip = %{$ip_info->[1]};
9950: }
9951:
1.888 albertel 9952: my %name_to_host = &all_names();
9953: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9954: my $ip;
9955: if (!exists($name_to_ip{$name})) {
9956: $ip = gethostbyname($name);
9957: if (!$ip || length($ip) ne 4) {
1.894 albertel 9958: if (defined($old_name_to_ip{$name})) {
9959: $ip = $old_name_to_ip{$name};
9960: &logthis("Can't find $name defaulting to old $ip");
9961: } else {
9962: &logthis("Name $name no IP found");
9963: next;
9964: }
9965: } else {
9966: $ip=inet_ntoa($ip);
1.847 albertel 9967: }
9968: $name_to_ip{$name} = $ip;
9969: } else {
9970: $ip = $name_to_ip{$name};
1.653 albertel 9971: }
1.888 albertel 9972: foreach my $id (@{ $name_to_host{$name} }) {
9973: $lonid_to_ip{$id} = $ip;
9974: }
9975: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9976: }
1.869 albertel 9977: &Apache::lonnet::do_cache_new('iphost','iphost',
9978: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9979: 48*60*60);
1.869 albertel 9980:
1.847 albertel 9981: return %iphost;
1.598 albertel 9982: }
9983:
1.992 raeburn 9984: #
9985: # Given a DNS returns the loncapa host name for that DNS
9986: #
9987: sub host_from_dns {
9988: my ($dns) = @_;
9989: my @hosts;
9990: my $ip;
9991:
1.993 raeburn 9992: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9993: $ip = $name_to_ip{$dns};
9994: }
9995: if (!$ip) {
9996: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9997: if (length($ip) == 4) {
9998: $ip = &IO::Socket::inet_ntoa($ip);
9999: }
10000: }
10001: if ($ip) {
10002: @hosts = get_hosts_from_ip($ip);
10003: return $hosts[0];
10004: }
10005: return undef;
1.986 foxr 10006: }
1.992 raeburn 10007:
1.986 foxr 10008: }
10009:
1.862 albertel 10010: BEGIN {
10011:
10012: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10013: unless ($readit) {
10014: {
10015: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10016: %perlvar = (%perlvar,%{$configvars});
10017: }
10018:
10019:
1.1 albertel 10020: # ------------------------------------------------------ Read spare server file
10021: {
1.448 albertel 10022: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10023:
10024: while (my $configline=<$config>) {
10025: chomp($configline);
1.284 matthew 10026: if ($configline) {
1.784 albertel 10027: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10028: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10029: push(@{ $spareid{$type} }, $host);
1.1 albertel 10030: }
10031: }
1.448 albertel 10032: close($config);
1.1 albertel 10033: }
1.11 www 10034: # ------------------------------------------------------------ Read permissions
10035: {
1.448 albertel 10036: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10037:
10038: while (my $configline=<$config>) {
1.448 albertel 10039: chomp($configline);
10040: if ($configline) {
10041: my ($role,$perm)=split(/ /,$configline);
10042: if ($perm ne '') { $pr{$role}=$perm; }
10043: }
1.11 www 10044: }
1.448 albertel 10045: close($config);
1.11 www 10046: }
10047:
10048: # -------------------------------------------- Read plain texts for permissions
10049: {
1.448 albertel 10050: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10051:
10052: while (my $configline=<$config>) {
1.448 albertel 10053: chomp($configline);
10054: if ($configline) {
1.742 raeburn 10055: my ($short,@plain)=split(/:/,$configline);
10056: %{$prp{$short}} = ();
10057: if (@plain > 0) {
10058: $prp{$short}{'std'} = $plain[0];
10059: for (my $i=1; $i<@plain; $i++) {
10060: $prp{$short}{'alt'.$i} = $plain[$i];
10061: }
10062: }
1.448 albertel 10063: }
1.135 www 10064: }
1.448 albertel 10065: close($config);
1.135 www 10066: }
10067:
10068: # ---------------------------------------------------------- Read package table
10069: {
1.448 albertel 10070: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10071:
10072: while (my $configline=<$config>) {
1.483 albertel 10073: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10074: chomp($configline);
10075: my ($short,$plain)=split(/:/,$configline);
10076: my ($pack,$name)=split(/\&/,$short);
10077: if ($plain ne '') {
10078: $packagetab{$pack.'&'.$name.'&name'}=$name;
10079: $packagetab{$short}=$plain;
10080: }
1.11 www 10081: }
1.448 albertel 10082: close($config);
1.329 matthew 10083: }
10084:
10085: # ------------- set up temporary directory
10086: {
10087: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10088:
1.11 www 10089: }
10090:
1.794 albertel 10091: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10092: 'compress_threshold'=> 20_000,
10093: });
1.185 www 10094:
1.281 www 10095: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10096: $dumpcount=0;
1.958 www 10097: $locknum=0;
1.22 www 10098:
1.163 harris41 10099: &logtouch();
1.672 albertel 10100: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10101: $readit=1;
1.564 albertel 10102: {
10103: use integer;
10104: my $test=(2**32)+1;
1.568 albertel 10105: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10106: &logthis(" Detected 64bit platform ($_64bit)");
10107: }
1.195 www 10108: }
1.1 albertel 10109: }
1.179 www 10110:
1.1 albertel 10111: 1;
1.191 harris41 10112: __END__
10113:
1.243 albertel 10114: =pod
10115:
1.191 harris41 10116: =head1 NAME
10117:
1.243 albertel 10118: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10119:
10120: =head1 SYNOPSIS
10121:
1.243 albertel 10122: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10123:
10124: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10125:
1.243 albertel 10126: Common parameters:
10127:
10128: =over 4
10129:
10130: =item *
10131:
10132: $uname : an internal username (if $cname expecting a course Id specifically)
10133:
10134: =item *
10135:
10136: $udom : a domain (if $cdom expecting a course's domain specifically)
10137:
10138: =item *
10139:
10140: $symb : a resource instance identifier
10141:
10142: =item *
10143:
10144: $namespace : the name of a .db file that contains the data needed or
10145: being set.
10146:
10147: =back
10148:
1.394 bowersj2 10149: =head1 OVERVIEW
1.191 harris41 10150:
1.394 bowersj2 10151: lonnet provides subroutines which interact with the
10152: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10153: about classes, users, and resources.
1.243 albertel 10154:
10155: For many of these objects you can also use this to store data about
10156: them or modify them in various ways.
1.191 harris41 10157:
1.394 bowersj2 10158: =head2 Symbs
1.191 harris41 10159:
1.394 bowersj2 10160: To identify a specific instance of a resource, LON-CAPA uses symbols
10161: or "symbs"X<symb>. These identifiers are built from the URL of the
10162: map, the resource number of the resource in the map, and the URL of
10163: the resource itself. The latter is somewhat redundant, but might help
10164: if maps change.
10165:
10166: An example is
10167:
10168: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10169:
10170: The respective map entry is
10171:
10172: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10173: title="Problem 2">
10174: </resource>
10175:
10176: Symbs are used by the random number generator, as well as to store and
10177: restore data specific to a certain instance of for example a problem.
10178:
10179: =head2 Storing And Retrieving Data
10180:
10181: X<store()>X<cstore()>X<restore()>Three of the most important functions
10182: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10183: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10184: is is the non-critical message twin of cstore. These functions are for
10185: handlers to store a perl hash to a user's permanent data space in an
10186: easy manner, and to retrieve it again on another call. It is expected
10187: that a handler would use this once at the beginning to retrieve data,
10188: and then again once at the end to send only the new data back.
10189:
10190: The data is stored in the user's data directory on the user's
10191: homeserver under the ID of the course.
10192:
10193: The hash that is returned by restore will have all of the previous
10194: value for all of the elements of the hash.
10195:
10196: Example:
10197:
10198: #creating a hash
10199: my %hash;
10200: $hash{'foo'}='bar';
10201:
10202: #storing it
10203: &Apache::lonnet::cstore(\%hash);
10204:
10205: #changing a value
10206: $hash{'foo'}='notbar';
10207:
10208: #adding a new value
10209: $hash{'bar'}='foo';
10210: &Apache::lonnet::cstore(\%hash);
10211:
10212: #retrieving the hash
10213: my %history=&Apache::lonnet::restore();
10214:
10215: #print the hash
10216: foreach my $key (sort(keys(%history))) {
10217: print("\%history{$key} = $history{$key}");
10218: }
10219:
10220: Will print out:
1.191 harris41 10221:
1.394 bowersj2 10222: %history{1:foo} = bar
10223: %history{1:keys} = foo:timestamp
10224: %history{1:timestamp} = 990455579
10225: %history{2:bar} = foo
10226: %history{2:foo} = notbar
10227: %history{2:keys} = foo:bar:timestamp
10228: %history{2:timestamp} = 990455580
10229: %history{bar} = foo
10230: %history{foo} = notbar
10231: %history{timestamp} = 990455580
10232: %history{version} = 2
10233:
10234: Note that the special hash entries C<keys>, C<version> and
10235: C<timestamp> were added to the hash. C<version> will be equal to the
10236: total number of versions of the data that have been stored. The
10237: C<timestamp> attribute will be the UNIX time the hash was
10238: stored. C<keys> is available in every historical section to list which
10239: keys were added or changed at a specific historical revision of a
10240: hash.
10241:
10242: B<Warning>: do not store the hash that restore returns directly. This
10243: will cause a mess since it will restore the historical keys as if the
10244: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10245:
1.394 bowersj2 10246: Calling convention:
1.191 harris41 10247:
1.394 bowersj2 10248: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10249: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10250:
1.394 bowersj2 10251: For more detailed information, see lonnet specific documentation.
1.191 harris41 10252:
1.394 bowersj2 10253: =head1 RETURN MESSAGES
1.191 harris41 10254:
1.394 bowersj2 10255: =over 4
1.191 harris41 10256:
1.394 bowersj2 10257: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10258:
1.394 bowersj2 10259: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10260: when the connection is brought back up
1.191 harris41 10261:
1.394 bowersj2 10262: =item * B<con_failed>: unable to contact remote host and unable to save message
10263: for later delivery
1.191 harris41 10264:
1.967 bisitz 10265: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10266:
1.394 bowersj2 10267: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10268: that was requested
1.191 harris41 10269:
1.243 albertel 10270: =back
1.191 harris41 10271:
1.243 albertel 10272: =head1 PUBLIC SUBROUTINES
1.191 harris41 10273:
1.243 albertel 10274: =head2 Session Environment Functions
1.191 harris41 10275:
1.243 albertel 10276: =over 4
1.191 harris41 10277:
1.394 bowersj2 10278: =item *
10279: X<appenv()>
1.949 raeburn 10280: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10281: the user envirnoment file, and will be restored for each access this
1.620 albertel 10282: user makes during this session, also modifies the %env for the current
1.949 raeburn 10283: process. Optional rolesarrayref - if defined contains a reference to an array
10284: of roles which are exempt from the restriction on modifying user.role entries
10285: in the user's environment.db and in %env.
1.191 harris41 10286:
10287: =item *
1.394 bowersj2 10288: X<delenv()>
1.987 raeburn 10289: B<delenv($delthis,$regexp)>: removes all items from the session
10290: environment file that begin with $delthis. If the
10291: optional second arg - $regexp - is true, $delthis is treated as a
10292: regular expression, otherwise \Q$delthis\E is used.
10293: The values are also deleted from the current processes %env.
1.191 harris41 10294:
1.795 albertel 10295: =item * get_env_multiple($name)
10296:
10297: gets $name from the %env hash, it seemlessly handles the cases where multiple
10298: values may be defined and end up as an array ref.
10299:
10300: returns an array of values
10301:
1.243 albertel 10302: =back
10303:
10304: =head2 User Information
1.191 harris41 10305:
1.243 albertel 10306: =over 4
1.191 harris41 10307:
10308: =item *
1.394 bowersj2 10309: X<queryauthenticate()>
10310: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10311: authentication scheme
10312:
10313: =item *
1.394 bowersj2 10314: X<authenticate()>
10315: B<authenticate($uname,$upass,$udom)>: try to
10316: authenticate user from domain's lib servers (first use the current
10317: one). C<$upass> should be the users password.
1.191 harris41 10318:
10319: =item *
1.394 bowersj2 10320: X<homeserver()>
10321: B<homeserver($uname,$udom)>: find the server which has
10322: the user's directory and files (there must be only one), this caches
10323: the answer, and also caches if there is a borken connection.
1.191 harris41 10324:
10325: =item *
1.394 bowersj2 10326: X<idget()>
10327: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10328: (IDs are a unique resource in a domain, there must be only 1 ID per
10329: username, and only 1 username per ID in a specific domain) (returns
10330: hash: id=>name,id=>name)
1.191 harris41 10331:
10332: =item *
1.394 bowersj2 10333: X<idrget()>
10334: B<idrget($udom,@unames)>: find the IDs behind a list of
10335: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10336:
10337: =item *
1.394 bowersj2 10338: X<idput()>
10339: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10340:
10341: =item *
1.394 bowersj2 10342: X<rolesinit()>
10343: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10344:
10345: =item *
1.551 albertel 10346: X<getsection()>
10347: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10348: course $cname, return section name/number or '' for "not in course"
10349: and '-1' for "no section"
10350:
10351: =item *
1.394 bowersj2 10352: X<userenvironment()>
10353: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10354: passed in @what from the requested user's environment, returns a hash
10355:
1.858 raeburn 10356: =item *
10357: X<userlog_query()>
1.859 albertel 10358: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10359: activity.log file. %filters defines filters applied when parsing the
10360: log file. These can be start or end timestamps, or the type of action
10361: - log to look for Login or Logout events, check for Checkin or
10362: Checkout, role for role selection. The response is in the form
10363: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10364: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10365:
1.243 albertel 10366: =back
10367:
10368: =head2 User Roles
10369:
10370: =over 4
10371:
10372: =item *
10373:
1.810 raeburn 10374: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10375: F: full access
10376: U,I,K: authentication modes (cxx only)
10377: '': forbidden
10378: 1: user needs to choose course
10379: 2: browse allowed
1.766 albertel 10380: A: passphrase authentication needed
1.243 albertel 10381:
10382: =item *
10383:
10384: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10385: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10386: and course level
10387:
10388: =item *
10389:
1.988 raeburn 10390: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10391: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10392: $type is Course (default) or Community.
1.988 raeburn 10393: If $forcedefault evaluates to true, text returned will be default
10394: text for $type. Otherwise, if this is a course, the text returned
10395: will be a custom name for the role (if defined in the course's
10396: environment). If no custom name is defined the default is returned.
10397:
1.832 raeburn 10398: =item *
10399:
1.935 raeburn 10400: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10401: All arguments are optional. Returns a hash of a roles, either for
10402: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10403: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10404: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10405: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10406: For each key, value is set to colon-separated start and end times for
10407: the role. If no username and domain are specified, will default to
1.934 raeburn 10408: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10409: of role statuses (active, future or previous), roles
10410: (e.g., cc,in, st etc.) and domains of the roles which can be used
10411: to restrict the list of roles reported. If no array ref is
10412: provided for types, will default to return only active roles.
1.834 albertel 10413:
1.243 albertel 10414: =back
10415:
10416: =head2 User Modification
10417:
10418: =over 4
10419:
10420: =item *
10421:
1.957 raeburn 10422: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10423: user for the level given by URL. Optional start and end dates (leave empty
10424: string or zero for "no date")
1.191 harris41 10425:
10426: =item *
10427:
1.243 albertel 10428: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10429: change a users, password, possible return values are: ok,
10430: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10431: refused
1.191 harris41 10432:
10433: =item *
10434:
1.243 albertel 10435: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10436:
10437: =item *
10438:
1.1056.2.1 raeburn 10439: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10440: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10441:
10442: will update user information (firstname,middlename,lastname,generation,
10443: permanentemail), and if forceid is true, student/employee ID also.
10444: A user's institutional affiliation(s) can also be updated.
10445: User information fields will not be overwritten with empty entries
10446: unless the field is included in the $candelete array reference.
10447: This array is included when a single user is modified via "Manage Users",
10448: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10449:
10450: =item *
10451:
1.286 matthew 10452: modifystudent
10453:
1.957 raeburn 10454: modify a student's enrollment and identification information.
1.286 matthew 10455: The course id is resolved based on the current users environment.
10456: This means the envoking user must be a course coordinator or otherwise
10457: associated with a course.
10458:
1.297 matthew 10459: This call is essentially a wrapper for lonnet::modifyuser and
10460: lonnet::modify_student_enrollment
1.286 matthew 10461:
10462: Inputs:
10463:
10464: =over 4
10465:
1.957 raeburn 10466: =item B<$udom> Student's loncapa domain
1.286 matthew 10467:
1.957 raeburn 10468: =item B<$uname> Student's loncapa login name
1.286 matthew 10469:
1.964 bisitz 10470: =item B<$uid> Student/Employee ID
1.286 matthew 10471:
1.957 raeburn 10472: =item B<$umode> Student's authentication mode
1.286 matthew 10473:
1.957 raeburn 10474: =item B<$upass> Student's password
1.286 matthew 10475:
1.957 raeburn 10476: =item B<$first> Student's first name
1.286 matthew 10477:
1.957 raeburn 10478: =item B<$middle> Student's middle name
1.286 matthew 10479:
1.957 raeburn 10480: =item B<$last> Student's last name
1.286 matthew 10481:
1.957 raeburn 10482: =item B<$gene> Student's generation
1.286 matthew 10483:
1.957 raeburn 10484: =item B<$usec> Student's section in course
1.286 matthew 10485:
10486: =item B<$end> Unix time of the roles expiration
10487:
10488: =item B<$start> Unix time of the roles start date
10489:
10490: =item B<$forceid> If defined, allow $uid to be changed
10491:
10492: =item B<$desiredhome> server to use as home server for student
10493:
1.957 raeburn 10494: =item B<$email> Student's permanent e-mail address
10495:
10496: =item B<$type> Type of enrollment (auto or manual)
10497:
1.963 raeburn 10498: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10499:
10500: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10501:
1.963 raeburn 10502: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10503:
1.963 raeburn 10504: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10505:
1.963 raeburn 10506: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10507:
1.286 matthew 10508: =back
1.297 matthew 10509:
10510: =item *
10511:
10512: modify_student_enrollment
10513:
10514: Change a students enrollment status in a class. The environment variable
10515: 'role.request.course' must be defined for this function to proceed.
10516:
10517: Inputs:
10518:
10519: =over 4
10520:
10521: =item $udom, students domain
10522:
10523: =item $uname, students name
10524:
10525: =item $uid, students user id
10526:
10527: =item $first, students first name
10528:
10529: =item $middle
10530:
10531: =item $last
10532:
10533: =item $gene
10534:
10535: =item $usec
10536:
10537: =item $end
10538:
10539: =item $start
10540:
1.957 raeburn 10541: =item $type
10542:
10543: =item $locktype
10544:
10545: =item $cid
10546:
10547: =item $selfenroll
10548:
10549: =item $context
10550:
1.297 matthew 10551: =back
10552:
1.191 harris41 10553:
10554: =item *
10555:
1.243 albertel 10556: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10557: custom role; give a custom role to a user for the level given by URL. Specify
10558: name and domain of role author, and role name
1.191 harris41 10559:
10560: =item *
10561:
1.243 albertel 10562: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10563:
10564: =item *
10565:
1.243 albertel 10566: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10567:
10568: =back
10569:
10570: =head2 Course Infomation
10571:
10572: =over 4
1.191 harris41 10573:
10574: =item *
10575:
1.631 albertel 10576: coursedescription($courseid) : returns a hash of information about the
10577: specified course id, including all environment settings for the
10578: course, the description of the course will be in the hash under the
10579: key 'description'
1.191 harris41 10580:
10581: =item *
10582:
1.624 albertel 10583: resdata($name,$domain,$type,@which) : request for current parameter
10584: setting for a specific $type, where $type is either 'course' or 'user',
10585: @what should be a list of parameters to ask about. This routine caches
10586: answers for 5 minutes.
1.243 albertel 10587:
1.877 foxr 10588: =item *
10589:
10590: get_courseresdata($courseid, $domain) : dump the entire course resource
10591: data base, returning a hash that is keyed by the resource name and has
10592: values that are the resource value. I believe that the timestamps and
10593: versions are also returned.
10594:
10595:
1.243 albertel 10596: =back
10597:
10598: =head2 Course Modification
10599:
10600: =over 4
1.191 harris41 10601:
10602: =item *
10603:
1.243 albertel 10604: writecoursepref($courseid,%prefs) : write preferences (environment
10605: database) for a course
1.191 harris41 10606:
10607: =item *
10608:
1.1011 raeburn 10609: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10610:
10611: =item *
10612:
1.1038 raeburn 10613: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10614:
10615: =back
10616:
10617: =head2 Resource Subroutines
10618:
10619: =over 4
1.191 harris41 10620:
10621: =item *
10622:
1.243 albertel 10623: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10624:
10625: =item *
10626:
1.243 albertel 10627: repcopy($filename) : subscribes to the requested file, and attempts to
10628: replicate from the owning library server, Might return
1.607 raeburn 10629: 'unavailable', 'not_found', 'forbidden', 'ok', or
10630: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10631: resource. Expects the local filesystem pathname
10632: (/home/httpd/html/res/....)
10633:
10634: =back
10635:
10636: =head2 Resource Information
10637:
10638: =over 4
1.191 harris41 10639:
10640: =item *
10641:
1.243 albertel 10642: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10643: a vairety of different possible values, $varname should be a request
10644: string, and the other parameters can be used to specify who and what
10645: one is asking about.
10646:
10647: Possible values for $varname are environment.lastname (or other item
10648: from the envirnment hash), user.name (or someother aspect about the
10649: user), resource.0.maxtries (or some other part and parameter of a
10650: resource)
1.204 albertel 10651:
10652: =item *
10653:
1.243 albertel 10654: directcondval($number) : get current value of a condition; reads from a state
10655: string
1.204 albertel 10656:
10657: =item *
10658:
1.243 albertel 10659: condval($condidx) : value of condition index based on state
1.204 albertel 10660:
10661: =item *
10662:
1.243 albertel 10663: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10664: resource's metadata, $what should be either a specific key, or either
10665: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10666: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10667:
10668: this function automatically caches all requests
1.191 harris41 10669:
10670: =item *
10671:
1.243 albertel 10672: metadata_query($query,$custom,$customshow) : make a metadata query against the
10673: network of library servers; returns file handle of where SQL and regex results
10674: will be stored for query
1.191 harris41 10675:
10676: =item *
10677:
1.243 albertel 10678: symbread($filename) : return symbolic list entry (filename argument optional);
10679: returns the data handle
1.191 harris41 10680:
10681: =item *
10682:
1.243 albertel 10683: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10684: a possible symb for the URL in $thisfn, and if is an encryypted
10685: resource that the user accessed using /enc/ returns a 1 on success, 0
10686: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10687: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10688:
1.191 harris41 10689:
10690: =item *
10691:
1.243 albertel 10692: symbclean($symb) : removes versions numbers from a symb, returns the
10693: cleaned symb
1.191 harris41 10694:
10695: =item *
10696:
1.243 albertel 10697: is_on_map($uri) : checks if the $uri is somewhere on the current
10698: course map, user must be in a course for it to work.
1.191 harris41 10699:
10700: =item *
10701:
1.243 albertel 10702: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10703:
10704: =item *
10705:
1.243 albertel 10706: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10707: a random seed, all arguments are optional, if they aren't sent it uses the
10708: environment to derive them. Note: if symb isn't sent and it can't get one
10709: from &symbread it will use the current time as its return value
1.191 harris41 10710:
10711: =item *
10712:
1.243 albertel 10713: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10714: unfakeable, receipt
1.191 harris41 10715:
10716: =item *
10717:
1.620 albertel 10718: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10719:
10720: =item *
10721:
1.243 albertel 10722: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10723:
10724: =item *
10725:
1.243 albertel 10726: 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 10727:
10728: =item *
10729:
1.243 albertel 10730: 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 10731:
10732: =item *
10733:
1.243 albertel 10734: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10735:
10736: =item *
10737:
1.243 albertel 10738: devalidate($symb) : devalidate temporary spreadsheet calculations,
10739: forcing spreadsheet to reevaluate the resource scores next time.
10740:
10741: =back
10742:
10743: =head2 Storing/Retreiving Data
10744:
10745: =over 4
1.191 harris41 10746:
10747: =item *
10748:
1.243 albertel 10749: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10750: for this url; hashref needs to be given and should be a \%hashname; the
10751: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10752: be derived from the env
1.191 harris41 10753:
10754: =item *
10755:
1.243 albertel 10756: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10757: uses critical subroutine
1.191 harris41 10758:
10759: =item *
10760:
1.243 albertel 10761: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10762: all args are optional
1.191 harris41 10763:
10764: =item *
10765:
1.717 albertel 10766: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10767: dumps the complete (or key matching regexp) namespace into a hash
10768: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10769: normally &store()ed into
10770:
10771: $range should be either an integer '100' (give me the first 100
10772: matching records)
10773: or be two integers sperated by a - with no spaces
10774: '30-50' (give me the 30th through the 50th matching
10775: records)
10776:
10777:
10778: =item *
10779:
10780: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10781: replaces a &store() version of data with a replacement set of data
10782: for a particular resource in a namespace passed in the $storehash hash
10783: reference
10784:
10785: =item *
10786:
1.243 albertel 10787: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10788: works very similar to store/cstore, but all data is stored in a
10789: temporary location and can be reset using tmpreset, $storehash should
10790: be a hash reference, returns nothing on success
1.191 harris41 10791:
10792: =item *
10793:
1.243 albertel 10794: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10795: similar to restore, but all data is stored in a temporary location and
10796: can be reset using tmpreset. Returns a hash of values on success,
10797: error string otherwise.
1.191 harris41 10798:
10799: =item *
10800:
1.243 albertel 10801: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10802: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10803:
10804: =item *
10805:
1.243 albertel 10806: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10807: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10808:
10809: =item *
10810:
1.243 albertel 10811: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10812: namesp ($udom and $uname are optional)
1.191 harris41 10813:
10814: =item *
10815:
1.702 albertel 10816: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10817: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10818: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10819:
1.702 albertel 10820: $range should be either an integer '100' (give me the first 100
10821: matching records)
10822: or be two integers sperated by a - with no spaces
10823: '30-50' (give me the 30th through the 50th matching
10824: records)
1.449 matthew 10825: =item *
10826:
10827: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10828: $store can be a scalar, an array reference, or if the amount to be
10829: incremented is > 1, a hash reference.
10830:
10831: ($udom and $uname are optional)
1.191 harris41 10832:
10833: =item *
10834:
1.243 albertel 10835: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10836: ($udom and $uname are optional)
1.191 harris41 10837:
10838: =item *
10839:
1.243 albertel 10840: cput($namespace,$storehash,$udom,$uname) : critical put
10841: ($udom and $uname are optional)
1.191 harris41 10842:
10843: =item *
10844:
1.748 albertel 10845: newput($namespace,$storehash,$udom,$uname) :
10846:
10847: Attempts to store the items in the $storehash, but only if they don't
10848: currently exist, if this succeeds you can be certain that you have
10849: successfully created a new key value pair in the $namespace db.
10850:
10851:
10852: Args:
10853: $namespace: name of database to store values to
10854: $storehash: hashref to store to the db
10855: $udom: (optional) domain of user containing the db
10856: $uname: (optional) name of user caontaining the db
10857:
10858: Returns:
10859: 'ok' -> succeeded in storing all keys of $storehash
10860: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10861: least <key> already existed in the db (other
10862: requested keys may also already exist)
1.967 bisitz 10863: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10864: 'con_lost' -> unable to contact request server
10865: 'refused' -> action was not allowed by remote machine
10866:
10867:
10868: =item *
10869:
1.243 albertel 10870: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10871: reference filled in from namesp (encrypts the return communication)
10872: ($udom and $uname are optional)
1.191 harris41 10873:
10874: =item *
10875:
1.243 albertel 10876: log($udom,$name,$home,$message) : write to permanent log for user; use
10877: critical subroutine
10878:
1.806 raeburn 10879: =item *
10880:
1.860 raeburn 10881: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10882: array reference filled in from namespace found in domain level on either
10883: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10884:
10885: =item *
10886:
1.860 raeburn 10887: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10888: domain level either on specified domain server ($uhome) or primary domain
10889: server ($udom and $uhome are optional)
1.806 raeburn 10890:
1.943 raeburn 10891: =item *
10892:
10893: get_domain_defaults($target_domain) : returns hash with defaults for
10894: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10895: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10896: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10897: Values are retrieved from cache (if current), or from domain's configuration.db
10898: (if available), or lastly from values in lonTabs/dns_domain,tab,
10899: or lonTabs/domain.tab.
10900:
10901: %domdefaults = &get_auth_defaults($target_domain);
10902:
1.243 albertel 10903: =back
10904:
10905: =head2 Network Status Functions
10906:
10907: =over 4
1.191 harris41 10908:
10909: =item *
10910:
10911: dirlist($uri) : return directory list based on URI
10912:
10913: =item *
10914:
1.243 albertel 10915: spareserver() : find server with least workload from spare.tab
10916:
1.986 foxr 10917:
10918: =item *
10919:
10920: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10921: if there is no corresponding loncapa host.
10922:
1.243 albertel 10923: =back
10924:
1.986 foxr 10925:
1.243 albertel 10926: =head2 Apache Request
10927:
10928: =over 4
1.191 harris41 10929:
10930: =item *
10931:
1.243 albertel 10932: ssi($url,%hash) : server side include, does a complete request cycle on url to
10933: localhost, posts hash
10934:
10935: =back
10936:
10937: =head2 Data to String to Data
10938:
10939: =over 4
1.191 harris41 10940:
10941: =item *
10942:
1.243 albertel 10943: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10944: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10945:
10946: =item *
10947:
1.243 albertel 10948: hashref2str($hashref) : convert a hashref into a string complete with
10949: escaping and '=' and '&' separators, supports elements that are
10950: arrayrefs and hashrefs
1.191 harris41 10951:
10952: =item *
10953:
1.243 albertel 10954: arrayref2str($arrayref) : convert an arrayref into a string complete
10955: with escaping and '&' separators, supports elements that are arrayrefs
10956: and hashrefs
1.191 harris41 10957:
10958: =item *
10959:
1.243 albertel 10960: str2hash($string) : convert string to hash using unescaping and
10961: splitting on '=' and '&', supports elements that are arrayrefs and
10962: hashrefs
1.191 harris41 10963:
10964: =item *
10965:
1.243 albertel 10966: str2array($string) : convert string to hash using unescaping and
10967: splitting on '&', supports elements that are arrayrefs and hashrefs
10968:
10969: =back
10970:
10971: =head2 Logging Routines
10972:
10973: =over 4
10974:
10975: These routines allow one to make log messages in the lonnet.log and
10976: lonnet.perm logfiles.
1.191 harris41 10977:
10978: =item *
10979:
1.243 albertel 10980: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10981:
10982: =item *
10983:
1.243 albertel 10984: logthis() : append message to the normal lonnet.log file, it gets
10985: preiodically rolled over and deleted.
1.191 harris41 10986:
10987: =item *
10988:
1.243 albertel 10989: logperm() : append a permanent message to lonnet.perm.log, this log
10990: file never gets deleted by any automated portion of the system, only
10991: messages of critical importance should go in here.
10992:
10993: =back
10994:
10995: =head2 General File Helper Routines
10996:
10997: =over 4
1.191 harris41 10998:
10999: =item *
11000:
1.481 raeburn 11001: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11002: (a) files in /uploaded
11003: (i) If a local copy of the file exists -
11004: compares modification date of local copy with last-modified date for
11005: definitive version stored on home server for course. If local copy is
11006: stale, requests a new version from the home server and stores it.
11007: If the original has been removed from the home server, then local copy
11008: is unlinked.
11009: (ii) If local copy does not exist -
11010: requests the file from the home server and stores it.
11011:
11012: If $caller is 'uploadrep':
11013: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11014: for request for files originally uploaded via DOCS.
11015: - returns 'ok' if fresh local copy now available, -1 otherwise.
11016:
11017: Otherwise:
11018: This indicates a call from the content generation phase of the request.
11019: - returns the entire contents of the file or -1.
11020:
11021: (b) files in /res
11022: - returns the entire contents of a file or -1;
11023: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11024:
1.712 albertel 11025:
11026: =item *
11027:
11028: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11029: reference
11030:
11031: returns either a stat() list of data about the file or an empty list
11032: if the file doesn't exist or couldn't find out about it (connection
11033: problems or user unknown)
11034:
1.191 harris41 11035: =item *
11036:
1.243 albertel 11037: filelocation($dir,$file) : returns file system location of a file
11038: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11039: directory that relative $file lookups are to looked in ($dir of /a/dir
11040: and a file of ../bob will become /a/bob)
1.191 harris41 11041:
11042: =item *
11043:
11044: hreflocation($dir,$file) : returns file system location or a URL; same as
11045: filelocation except for hrefs
11046:
11047: =item *
11048:
11049: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11050:
1.243 albertel 11051: =back
11052:
1.608 albertel 11053: =head2 Usererfile file routines (/uploaded*)
11054:
11055: =over 4
11056:
11057: =item *
11058:
11059: userfileupload(): main rotine for putting a file in a user or course's
11060: filespace, arguments are,
11061:
1.620 albertel 11062: formname - required - this is the name of the element in $env where the
1.608 albertel 11063: filename, and the contents of the file to create/modifed exist
1.620 albertel 11064: the filename is in $env{'form.'.$formname.'.filename'} and the
11065: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11066: coursedoc - if true, store the file in the course of the active role
11067: of the current user
11068: subdir - required - subdirectory to put the file in under ../userfiles/
11069: if undefined, it will be placed in "unknown"
11070:
11071: (This routine calls clean_filename() to remove any dangerous
11072: characters from the filename, and then calls finuserfileupload() to
11073: complete the transaction)
11074:
11075: returns either the url of the uploaded file (/uploaded/....) if successful
11076: and /adm/notfound.html if unsuccessful
11077:
11078: =item *
11079:
11080: clean_filename(): routine for cleaing a filename up for storage in
11081: userfile space, argument is:
11082:
11083: filename - proposed filename
11084:
11085: returns: the new clean filename
11086:
11087: =item *
11088:
11089: finishuserfileupload(): routine that creaes and sends the file to
11090: userspace, probably shouldn't be called directly
11091:
11092: docuname: username or courseid of destination for the file
11093: docudom: domain of user/course of destination for the file
11094: formname: same as for userfileupload()
11095: fname: filename (inculding subdirectories) for the file
11096:
11097: returns either the url of the uploaded file (/uploaded/....) if successful
11098: and /adm/notfound.html if unsuccessful
11099:
11100: =item *
11101:
11102: renameuserfile(): renames an existing userfile to a new name
11103:
11104: Args:
11105: docuname: username or courseid of destination for the file
11106: docudom: domain of user/course of destination for the file
11107: old: current file name (including any subdirs under userfiles)
11108: new: desired file name (including any subdirs under userfiles)
11109:
11110: =item *
11111:
11112: mkdiruserfile(): creates a directory is a userfiles dir
11113:
11114: Args:
11115: docuname: username or courseid of destination for the file
11116: docudom: domain of user/course of destination for the file
11117: dir: dir to create (including any subdirs under userfiles)
11118:
11119: =item *
11120:
11121: removeuserfile(): removes a file that exists in userfiles
11122:
11123: Args:
11124: docuname: username or courseid of destination for the file
11125: docudom: domain of user/course of destination for the file
11126: fname: filname to delete (including any subdirs under userfiles)
11127:
11128: =item *
11129:
11130: removeuploadedurl(): convience function for removeuserfile()
11131:
11132: Args:
11133: url: a full /uploaded/... url to delete
11134:
1.747 albertel 11135: =item *
11136:
11137: get_portfile_permissions():
11138: Args:
11139: domain: domain of user or course contain the portfolio files
11140: user: name of user or num of course contain the portfolio files
11141: Returns:
11142: hashref of a dump of the proper file_permissions.db
11143:
11144:
11145: =item *
11146:
11147: get_access_controls():
11148:
11149: Args:
11150: current_permissions: the hash ref returned from get_portfile_permissions()
11151: group: (optional) the group you want the files associated with
11152: file: (optional) the file you want access info on
11153:
11154: Returns:
1.749 raeburn 11155: a hash (keys are file names) of hashes containing
11156: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11157: values are XML containing access control settings (see below)
1.747 albertel 11158:
11159: Internal notes:
11160:
1.749 raeburn 11161: access controls are stored in file_permissions.db as key=value pairs.
11162: key -> path to file/file_name\0uniqueID:scope_end_start
11163: where scope -> public,guest,course,group,domains or users.
11164: end -> UNIX time for end of access (0 -> no end date)
11165: start -> UNIX time for start of access
11166:
11167: value -> XML description of access control
11168: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11169: <start></start>
11170: <end></end>
11171:
11172: <password></password> for scope type = guest
11173:
11174: <domain></domain> for scope type = course or group
11175: <number></number>
11176: <roles id="">
11177: <role></role>
11178: <access></access>
11179: <section></section>
11180: <group></group>
11181: </roles>
11182:
11183: <dom></dom> for scope type = domains
11184:
11185: <users> for scope type = users
11186: <user>
11187: <uname></uname>
11188: <udom></udom>
11189: </user>
11190: </users>
11191: </scope>
11192:
11193: Access data is also aggregated for each file in an additional key=value pair:
11194: key -> path to file/file_name\0accesscontrol
11195: value -> reference to hash
11196: hash contains key = value pairs
11197: where key = uniqueID:scope_end_start
11198: value = UNIX time record was last updated
11199:
11200: Used to improve speed of look-ups of access controls for each file.
11201:
11202: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11203:
11204: modify_access_controls():
11205:
11206: Modifies access controls for a portfolio file
11207: Args
11208: 1. file name
11209: 2. reference to hash of required changes,
11210: 3. domain
11211: 4. username
11212: where domain,username are the domain of the portfolio owner
11213: (either a user or a course)
11214:
11215: Returns:
11216: 1. result of additions or updates ('ok' or 'error', with error message).
11217: 2. result of deletions ('ok' or 'error', with error message).
11218: 3. reference to hash of any new or updated access controls.
11219: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11220: key = integer (inbound ID)
11221: value = uniqueID
1.747 albertel 11222:
1.608 albertel 11223: =back
11224:
1.243 albertel 11225: =head2 HTTP Helper Routines
11226:
11227: =over 4
11228:
1.191 harris41 11229: =item *
11230:
11231: escape() : unpack non-word characters into CGI-compatible hex codes
11232:
11233: =item *
11234:
11235: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11236:
1.243 albertel 11237: =back
11238:
11239: =head1 PRIVATE SUBROUTINES
11240:
11241: =head2 Underlying communication routines (Shouldn't call)
11242:
11243: =over 4
11244:
11245: =item *
11246:
11247: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11248:
11249: =item *
11250:
11251: reply() : uses subreply to send a message to remote machine, logs all failures
11252:
11253: =item *
11254:
11255: critical() : passes a critical message to another server; if cannot
11256: get through then place message in connection buffer directory and
11257: returns con_delayed, if incapable of saving message, returns
11258: con_failed
11259:
11260: =item *
11261:
11262: reconlonc() : tries to reconnect lonc client processes.
11263:
11264: =back
11265:
11266: =head2 Resource Access Logging
11267:
11268: =over 4
11269:
11270: =item *
11271:
11272: flushcourselogs() : flush (save) buffer logs and access logs
11273:
11274: =item *
11275:
11276: courselog($what) : save message for course in hash
11277:
11278: =item *
11279:
11280: courseacclog($what) : save message for course using &courselog(). Perform
11281: special processing for specific resource types (problems, exams, quizzes, etc).
11282:
1.191 harris41 11283: =item *
11284:
11285: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11286: as a PerlChildExitHandler
1.243 albertel 11287:
11288: =back
11289:
11290: =head2 Other
11291:
11292: =over 4
11293:
11294: =item *
11295:
11296: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11297:
11298: =back
11299:
11300: =cut
1.877 foxr 11301:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>