Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.999
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.999 ! raeburn 4: # $Id: lonnet.pm,v 1.998 2009/05/08 12:45:28 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.807 albertel 95: use LONCAPA qw(:DEFAULT :match);
1.740 www 96: use LONCAPA::Configuration;
1.676 albertel 97:
1.195 www 98: my $readit;
1.550 foxr 99: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 100:
1.977 amueller 101: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.993 raeburn 199: sub get_server_loncaparev {
200: my ($dom,$lonhost) = @_;
201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
215: my $cachetime = 24*3600;
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: } else {
220: my $loncaparev = &reply('serverloncaparev',$lonhost);
221: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
222: }
223: }
224: }
225:
1.1 albertel 226: # -------------------------------------------------- Non-critical communication
227: sub subreply {
228: my ($cmd,$server)=@_;
1.838 albertel 229: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 230: #
231: # With loncnew process trimming, there's a timing hole between lonc server
232: # process exit and the master server picking up the listen on the AF_UNIX
233: # socket. In that time interval, a lock file will exist:
234:
235: my $lockfile=$peerfile.".lock";
236: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
237: sleep(1);
238: }
239: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 240: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 241: #
1.550 foxr 242: # We'll give the connection a few tries before abandoning it. If
243: # connection is not possible, we'll con_lost back to the client.
244: #
245: my $client;
246: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
247: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
248: Type => SOCK_STREAM,
249: Timeout => 10);
1.869 albertel 250: if ($client) {
1.550 foxr 251: last; # Connected!
1.850 albertel 252: } else {
1.853 albertel 253: &create_connection(&hostname($server),$server);
1.550 foxr 254: }
1.850 albertel 255: sleep(1); # Try again later if failed connection.
1.550 foxr 256: }
257: my $answer;
258: if ($client) {
1.704 albertel 259: print $client "sethost:$server:$cmd\n";
1.550 foxr 260: $answer=<$client>;
261: if (!$answer) { $answer="con_lost"; }
262: chomp($answer);
263: } else {
264: $answer = 'con_lost'; # Failed connection.
265: }
1.1 albertel 266: return $answer;
267: }
268:
269: sub reply {
270: my ($cmd,$server)=@_;
1.838 albertel 271: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 272: my $answer=subreply($cmd,$server);
1.65 www 273: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 274: &logthis("<font color=\"blue\">WARNING:".
1.12 www 275: " $cmd to $server returned $answer</font>");
276: }
1.1 albertel 277: return $answer;
278: }
279:
280: # ----------------------------------------------------------- Send USR1 to lonc
281:
282: sub reconlonc {
1.891 albertel 283: my ($lonid) = @_;
284: my $hostname = &hostname($lonid);
285: if ($lonid) {
286: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
287: if ($hostname && -e $peerfile) {
288: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
289: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
290: Type => SOCK_STREAM,
291: Timeout => 10);
292: if ($client) {
293: print $client ("reset_retries\n");
294: my $answer=<$client>;
295: #reset just this one.
296: }
297: }
298: return;
299: }
300:
1.836 www 301: &logthis("Trying to reconnect lonc");
1.1 albertel 302: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 303: if (open(my $fh,"<$loncfile")) {
1.1 albertel 304: my $loncpid=<$fh>;
305: chomp($loncpid);
306: if (kill 0 => $loncpid) {
307: &logthis("lonc at pid $loncpid responding, sending USR1");
308: kill USR1 => $loncpid;
309: sleep 1;
1.836 www 310: } else {
1.12 www 311: &logthis(
1.672 albertel 312: "<font color=\"blue\">WARNING:".
1.12 www 313: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 314: }
315: } else {
1.836 www 316: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 317: }
318: }
319:
320: # ------------------------------------------------------ Critical communication
1.12 www 321:
1.1 albertel 322: sub critical {
323: my ($cmd,$server)=@_;
1.838 albertel 324: unless (&hostname($server)) {
1.672 albertel 325: &logthis("<font color=\"blue\">WARNING:".
1.89 www 326: " Critical message to unknown server ($server)</font>");
327: return 'no_such_host';
328: }
1.1 albertel 329: my $answer=reply($cmd,$server);
330: if ($answer eq 'con_lost') {
331: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 332: my $answer=reply($cmd,$server);
1.1 albertel 333: if ($answer eq 'con_lost') {
334: my $now=time;
335: my $middlename=$cmd;
1.5 www 336: $middlename=substr($middlename,0,16);
1.1 albertel 337: $middlename=~s/\W//g;
338: my $dfilename=
1.305 www 339: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
340: $dumpcount++;
1.1 albertel 341: {
1.448 albertel 342: my $dfh;
343: if (open($dfh,">$dfilename")) {
344: print $dfh "$cmd\n";
345: close($dfh);
346: }
1.1 albertel 347: }
348: sleep 2;
349: my $wcmd='';
350: {
1.448 albertel 351: my $dfh;
352: if (open($dfh,"<$dfilename")) {
353: $wcmd=<$dfh>;
354: close($dfh);
355: }
1.1 albertel 356: }
357: chomp($wcmd);
1.7 www 358: if ($wcmd eq $cmd) {
1.672 albertel 359: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 360: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 361: &logperm("D:$server:$cmd");
362: return 'con_delayed';
363: } else {
1.672 albertel 364: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 365: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 366: &logperm("F:$server:$cmd");
367: return 'con_failed';
368: }
369: }
370: }
371: return $answer;
1.405 albertel 372: }
373:
1.755 albertel 374: # ------------------------------------------- check if return value is an error
375:
376: sub error {
377: my ($result) = @_;
1.756 albertel 378: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 379: if ($2 == 2) { return undef; }
380: return $1;
381: }
382: return undef;
383: }
384:
1.783 albertel 385: sub convert_and_load_session_env {
386: my ($lonidsdir,$handle)=@_;
387: my @profile;
388: {
1.917 albertel 389: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
390: if (!$opened) {
1.915 albertel 391: return 0;
392: }
1.783 albertel 393: flock($idf,LOCK_SH);
394: @profile=<$idf>;
395: close($idf);
396: }
397: my %temp_env;
398: foreach my $line (@profile) {
1.786 albertel 399: if ($line !~ m/=/) {
400: return 0;
401: }
1.783 albertel 402: chomp($line);
403: my ($envname,$envvalue)=split(/=/,$line,2);
404: $temp_env{&unescape($envname)} = &unescape($envvalue);
405: }
406: unlink("$lonidsdir/$handle.id");
407: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
408: 0640)) {
409: %disk_env = %temp_env;
410: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
411: untie(%disk_env);
412: }
1.786 albertel 413: return 1;
1.783 albertel 414: }
415:
1.374 www 416: # ------------------------------------------- Transfer profile into environment
1.780 albertel 417: my $env_loaded;
418: sub transfer_profile_to_env {
1.788 albertel 419: my ($lonidsdir,$handle,$force_transfer) = @_;
420: if (!$force_transfer && $env_loaded) { return; }
1.374 www 421:
1.720 albertel 422: if (!defined($lonidsdir)) {
423: $lonidsdir = $perlvar{'lonIDsDir'};
424: }
425: if (!defined($handle)) {
426: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
427: }
428:
1.786 albertel 429: my $convert;
430: {
1.917 albertel 431: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
432: if (!$opened) {
1.915 albertel 433: return;
434: }
1.786 albertel 435: flock($idf,LOCK_SH);
436: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
437: &GDBM_READER(),0640)) {
438: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
439: untie(%disk_env);
440: } else {
441: $convert = 1;
442: }
443: }
444: if ($convert) {
445: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
446: &logthis("Failed to load session, or convert session.");
447: }
1.374 www 448: }
1.783 albertel 449:
1.786 albertel 450: my %remove;
1.783 albertel 451: while ( my $envname = each(%env) ) {
1.433 matthew 452: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
453: if ($time < time-300) {
1.783 albertel 454: $remove{$key}++;
1.433 matthew 455: }
456: }
457: }
1.783 albertel 458:
1.619 albertel 459: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 460: $env_loaded=1;
1.783 albertel 461: foreach my $expired_key (keys(%remove)) {
1.433 matthew 462: &delenv($expired_key);
1.374 www 463: }
1.1 albertel 464: }
465:
1.916 albertel 466: # ---------------------------------------------------- Check for valid session
467: sub check_for_valid_session {
468: my ($r) = @_;
469: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
470: my $lonid=$cookies{'lonID'};
471: return undef if (!$lonid);
472:
473: my $handle=&LONCAPA::clean_handle($lonid->value);
474: my $lonidsdir=$r->dir_config('lonIDsDir');
475: return undef if (!-e "$lonidsdir/$handle.id");
476:
1.917 albertel 477: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
478: return undef if (!$opened);
1.916 albertel 479:
480: flock($idf,LOCK_SH);
481: my %disk_env;
482: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
483: &GDBM_READER(),0640)) {
484: return undef;
485: }
486:
487: if (!defined($disk_env{'user.name'})
488: || !defined($disk_env{'user.domain'})) {
489: return undef;
490: }
491: return $handle;
492: }
493:
1.830 albertel 494: sub timed_flock {
495: my ($file,$lock_type) = @_;
496: my $failed=0;
497: eval {
498: local $SIG{__DIE__}='DEFAULT';
499: local $SIG{ALRM}=sub {
500: $failed=1;
501: die("failed lock");
502: };
503: alarm(13);
504: flock($file,$lock_type);
505: alarm(0);
506: };
507: if ($failed) {
508: return undef;
509: } else {
510: return 1;
511: }
512: }
513:
1.5 www 514: # ---------------------------------------------------------- Append Environment
515:
516: sub appenv {
1.949 raeburn 517: my ($newenv,$roles) = @_;
518: if (ref($newenv) eq 'HASH') {
519: foreach my $key (keys(%{$newenv})) {
520: my $refused = 0;
521: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
522: $refused = 1;
523: if (ref($roles) eq 'ARRAY') {
524: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
525: if (grep(/^\Q$role\E$/,@{$roles})) {
526: $refused = 0;
527: }
528: }
529: }
530: if ($refused) {
531: &logthis("<font color=\"blue\">WARNING: ".
532: "Attempt to modify environment ".$key." to ".$newenv->{$key}
533: .'</font>');
534: delete($newenv->{$key});
535: } else {
536: $env{$key}=$newenv->{$key};
537: }
538: }
539: my $opened = open(my $env_file,'+<',$env{'user.environment'});
540: if ($opened
541: && &timed_flock($env_file,LOCK_EX)
542: &&
543: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
544: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
545: while (my ($key,$value) = each(%{$newenv})) {
546: $disk_env{$key} = $value;
547: }
548: untie(%disk_env);
1.35 www 549: }
1.191 harris41 550: }
1.56 www 551: return 'ok';
552: }
553: # ----------------------------------------------------- Delete from Environment
554:
555: sub delenv {
1.987 raeburn 556: my ($delthis,$regexp) = @_;
1.56 www 557: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 558: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 559: "Attempt to delete from environment ".$delthis);
560: return 'error';
561: }
1.917 albertel 562: my $opened = open(my $env_file,'+<',$env{'user.environment'});
563: if ($opened
1.915 albertel 564: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 565: &&
566: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
567: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 568: foreach my $key (keys(%disk_env)) {
1.987 raeburn 569: if ($regexp) {
570: if ($key=~/^$delthis/) {
571: delete($env{$key});
572: delete($disk_env{$key});
573: }
574: } else {
575: if ($key=~/^\Q$delthis\E/) {
576: delete($env{$key});
577: delete($disk_env{$key});
578: }
579: }
1.448 albertel 580: }
1.783 albertel 581: untie(%disk_env);
1.5 www 582: }
583: return 'ok';
1.369 albertel 584: }
585:
1.790 albertel 586: sub get_env_multiple {
587: my ($name) = @_;
588: my @values;
589: if (defined($env{$name})) {
590: # exists is it an array
591: if (ref($env{$name})) {
592: @values=@{ $env{$name} };
593: } else {
594: $values[0]=$env{$name};
595: }
596: }
597: return(@values);
598: }
599:
1.958 www 600: # ------------------------------------------------------------------- Locking
601:
602: sub set_lock {
603: my ($text)=@_;
604: $locknum++;
605: my $id=$$.'-'.$locknum;
606: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
607: 'session.lock.'.$id => $text});
608: return $id;
609: }
610:
611: sub get_locks {
612: my $num=0;
613: my %texts=();
614: foreach my $lock (split(/\,/,$env{'session.locks'})) {
615: if ($lock=~/\w/) {
616: $num++;
617: $texts{$lock}=$env{'session.lock.'.$lock};
618: }
619: }
620: return ($num,%texts);
621: }
622:
623: sub remove_lock {
624: my ($id)=@_;
625: my $newlocks='';
626: foreach my $lock (split(/\,/,$env{'session.locks'})) {
627: if (($lock=~/\w/) && ($lock ne $id)) {
628: $newlocks.=','.$lock;
629: }
630: }
631: &appenv({'session.locks' => $newlocks});
632: &delenv('session.lock.'.$id);
633: }
634:
635: sub remove_all_locks {
636: my $activelocks=$env{'session.locks'};
637: foreach my $lock (split(/\,/,$env{'session.locks'})) {
638: if ($lock=~/\w/) {
639: &remove_lock($lock);
640: }
641: }
642: }
643:
644:
1.369 albertel 645: # ------------------------------------------ Find out current server userload
646: sub userload {
647: my $numusers=0;
648: {
649: opendir(LONIDS,$perlvar{'lonIDsDir'});
650: my $filename;
651: my $curtime=time;
652: while ($filename=readdir(LONIDS)) {
1.925 albertel 653: next if ($filename eq '.' || $filename eq '..');
654: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 655: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 656: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 657: }
658: closedir(LONIDS);
659: }
660: my $userloadpercent=0;
661: my $maxuserload=$perlvar{'lonUserLoadLim'};
662: if ($maxuserload) {
1.371 albertel 663: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 664: }
1.372 albertel 665: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 666: return $userloadpercent;
1.283 www 667: }
668:
669: # ------------------------------------------ Fight off request when overloaded
670:
671: sub overloaderror {
672: my ($r,$checkserver)=@_;
673: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
674: my $loadavg;
675: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 676: open(my $loadfile,'/proc/loadavg');
1.283 www 677: $loadavg=<$loadfile>;
678: $loadavg =~ s/\s.*//g;
1.285 matthew 679: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 680: close($loadfile);
1.283 www 681: } else {
682: $loadavg=&reply('load',$checkserver);
683: }
1.285 matthew 684: my $overload=$loadavg-100;
1.283 www 685: if ($overload>0) {
1.285 matthew 686: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 687: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 688: return 413;
1.283 www 689: }
690: return '';
1.5 www 691: }
1.1 albertel 692:
693: # ------------------------------ Find server with least workload from spare.tab
1.11 www 694:
1.1 albertel 695: sub spareserver {
1.670 albertel 696: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 697: my $spare_server;
1.370 albertel 698: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 699: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
700: : $userloadpercent;
701:
702: foreach my $try_server (@{ $spareid{'primary'} }) {
703: ($spare_server, $lowest_load) =
704: &compare_server_load($try_server, $spare_server, $lowest_load);
705: }
706:
707: my $found_server = ($spare_server ne '' && $lowest_load < 100);
708:
709: if (!$found_server) {
710: foreach my $try_server (@{ $spareid{'default'} }) {
711: ($spare_server, $lowest_load) =
712: &compare_server_load($try_server, $spare_server, $lowest_load);
713: }
714: }
715:
716: if (!$want_server_name) {
1.968 raeburn 717: my $protocol = 'http';
718: if ($protocol{$spare_server} eq 'https') {
719: $protocol = $protocol{$spare_server};
720: }
721: $spare_server = $protocol.'://'.&hostname($spare_server);
1.784 albertel 722: }
723: return $spare_server;
724: }
725:
726: sub compare_server_load {
727: my ($try_server, $spare_server, $lowest_load) = @_;
728:
729: my $loadans = &reply('load', $try_server);
730: my $userloadans = &reply('userload',$try_server);
731:
732: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
733: next; #didn't get a number from the server
734: }
735:
736: my $load;
737: if ($loadans =~ /\d/) {
738: if ($userloadans =~ /\d/) {
739: #both are numbers, pick the bigger one
740: $load = ($loadans > $userloadans) ? $loadans
741: : $userloadans;
1.411 albertel 742: } else {
1.784 albertel 743: $load = $loadans;
1.411 albertel 744: }
1.784 albertel 745: } else {
746: $load = $userloadans;
747: }
748:
749: if (($load =~ /\d/) && ($load < $lowest_load)) {
750: $spare_server = $try_server;
751: $lowest_load = $load;
1.370 albertel 752: }
1.784 albertel 753: return ($spare_server,$lowest_load);
1.202 matthew 754: }
1.914 albertel 755:
756: # --------------------------- ask offload servers if user already has a session
757: sub find_existing_session {
758: my ($udom,$uname) = @_;
759: foreach my $try_server (@{ $spareid{'primary'} },
760: @{ $spareid{'default'} }) {
761: return $try_server if (&has_user_session($try_server, $udom, $uname));
762: }
763: return;
764: }
765:
766: # -------------------------------- ask if server already has a session for user
767: sub has_user_session {
768: my ($lonid,$udom,$uname) = @_;
769: my $result = &reply(join(':','userhassession',
770: map {&escape($_)} ($udom,$uname)),$lonid);
771: return 1 if ($result eq 'ok');
772:
773: return 0;
774: }
775:
1.202 matthew 776: # --------------------------------------------- Try to change a user's password
777:
778: sub changepass {
1.799 raeburn 779: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 780: $currentpass = &escape($currentpass);
781: $newpass = &escape($newpass);
1.799 raeburn 782: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 783: $server);
784: if (! $answer) {
785: &logthis("No reply on password change request to $server ".
786: "by $uname in domain $udom.");
787: } elsif ($answer =~ "^ok") {
788: &logthis("$uname in $udom successfully changed their password ".
789: "on $server.");
790: } elsif ($answer =~ "^pwchange_failure") {
791: &logthis("$uname in $udom was unable to change their password ".
792: "on $server. The action was blocked by either lcpasswd ".
793: "or pwchange");
794: } elsif ($answer =~ "^non_authorized") {
795: &logthis("$uname in $udom did not get their password correct when ".
796: "attempting to change it on $server.");
797: } elsif ($answer =~ "^auth_mode_error") {
798: &logthis("$uname in $udom attempted to change their password despite ".
799: "not being locally or internally authenticated on $server.");
800: } elsif ($answer =~ "^unknown_user") {
801: &logthis("$uname in $udom attempted to change their password ".
802: "on $server but were unable to because $server is not ".
803: "their home server.");
804: } elsif ($answer =~ "^refused") {
805: &logthis("$server refused to change $uname in $udom password because ".
806: "it was sent an unencrypted request to change the password.");
807: }
808: return $answer;
1.1 albertel 809: }
810:
1.169 harris41 811: # ----------------------- Try to determine user's current authentication scheme
812:
813: sub queryauthenticate {
814: my ($uname,$udom)=@_;
1.456 albertel 815: my $uhome=&homeserver($uname,$udom);
816: if (!$uhome) {
817: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
818: return 'no_host';
819: }
820: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
821: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
822: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 823: }
1.456 albertel 824: return $answer;
1.169 harris41 825: }
826:
1.1 albertel 827: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 828:
1.1 albertel 829: sub authenticate {
1.952 raeburn 830: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 831: $upass=&escape($upass);
832: $uname= &LONCAPA::clean_username($uname);
1.836 www 833: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 834: my $newhome;
1.836 www 835: if ((!$uhome) || ($uhome eq 'no_host')) {
836: # Maybe the machine was offline and only re-appeared again recently?
837: &reconlonc();
838: # One more
1.952 raeburn 839: $uhome=&homeserver($uname,$udom,1);
840: if (($uhome eq 'no_host') && $checkdefauth) {
841: if (defined(&domain($udom,'primary'))) {
842: $newhome=&domain($udom,'primary');
843: }
844: if ($newhome ne '') {
845: $uhome = $newhome;
846: }
847: }
1.836 www 848: if ((!$uhome) || ($uhome eq 'no_host')) {
849: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 850: return 'no_host';
851: }
1.1 albertel 852: }
1.952 raeburn 853: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 854: if ($answer eq 'authorized') {
1.952 raeburn 855: if ($newhome) {
856: &logthis("User $uname at $udom authorized by $uhome, but needs account");
857: return 'no_account_on_host';
858: } else {
859: &logthis("User $uname at $udom authorized by $uhome");
860: return $uhome;
861: }
1.471 albertel 862: }
863: if ($answer eq 'non_authorized') {
864: &logthis("User $uname at $udom rejected by $uhome");
865: return 'no_host';
1.9 www 866: }
1.471 albertel 867: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 868: return 'no_host';
869: }
870:
871: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 872:
1.599 albertel 873: my %homecache;
1.1 albertel 874: sub homeserver {
1.230 stredwic 875: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 876: my $index="$uname:$udom";
1.426 albertel 877:
1.599 albertel 878: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 879:
880: my %servers = &get_servers($udom,'library');
881: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 882: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 883: exists($badServerCache{$tryserver}));
1.841 albertel 884:
885: my $answer=reply("home:$udom:$uname",$tryserver);
886: if ($answer eq 'found') {
887: delete($badServerCache{$tryserver});
888: return $homecache{$index}=$tryserver;
889: } elsif ($answer eq 'no_host') {
890: $badServerCache{$tryserver}=1;
891: }
1.1 albertel 892: }
893: return 'no_host';
1.70 www 894: }
895:
896: # ------------------------------------- Find the usernames behind a list of IDs
897:
898: sub idget {
899: my ($udom,@ids)=@_;
900: my %returnhash=();
901:
1.841 albertel 902: my %servers = &get_servers($udom,'library');
903: foreach my $tryserver (keys(%servers)) {
904: my $idlist=join('&',@ids);
905: $idlist=~tr/A-Z/a-z/;
906: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
907: my @answer=();
908: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
909: @answer=split(/\&/,$reply);
910: } ;
911: my $i;
912: for ($i=0;$i<=$#ids;$i++) {
913: if ($answer[$i]) {
914: $returnhash{$ids[$i]}=$answer[$i];
915: }
916: }
917: }
1.70 www 918: return %returnhash;
919: }
920:
921: # ------------------------------------- Find the IDs behind a list of usernames
922:
923: sub idrget {
924: my ($udom,@unames)=@_;
925: my %returnhash=();
1.800 albertel 926: foreach my $uname (@unames) {
927: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 928: }
1.70 www 929: return %returnhash;
930: }
931:
932: # ------------------------------- Store away a list of names and associated IDs
933:
934: sub idput {
935: my ($udom,%ids)=@_;
936: my %servers=();
1.800 albertel 937: foreach my $uname (keys(%ids)) {
938: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
939: my $uhom=&homeserver($uname,$udom);
1.70 www 940: if ($uhom ne 'no_host') {
1.800 albertel 941: my $id=&escape($ids{$uname});
1.70 www 942: $id=~tr/A-Z/a-z/;
1.800 albertel 943: my $esc_unam=&escape($uname);
1.70 www 944: if ($servers{$uhom}) {
1.800 albertel 945: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 946: } else {
1.800 albertel 947: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 948: }
949: }
1.191 harris41 950: }
1.800 albertel 951: foreach my $server (keys(%servers)) {
952: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 953: }
1.344 www 954: }
955:
1.806 raeburn 956: # ------------------------------------------- get items from domain db files
957:
958: sub get_dom {
1.860 raeburn 959: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 960: my $items='';
961: foreach my $item (@$storearr) {
962: $items.=&escape($item).'&';
963: }
964: $items=~s/\&$//;
1.860 raeburn 965: if (!$udom) {
966: $udom=$env{'user.domain'};
967: if (defined(&domain($udom,'primary'))) {
968: $uhome=&domain($udom,'primary');
969: } else {
1.874 albertel 970: undef($uhome);
1.860 raeburn 971: }
972: } else {
973: if (!$uhome) {
974: if (defined(&domain($udom,'primary'))) {
975: $uhome=&domain($udom,'primary');
976: }
977: }
978: }
979: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 980: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 981: my %returnhash;
1.875 albertel 982: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 983: return %returnhash;
984: }
1.806 raeburn 985: my @pairs=split(/\&/,$rep);
986: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
987: return @pairs;
988: }
989: my $i=0;
990: foreach my $item (@$storearr) {
991: $returnhash{$item}=&thaw_unescape($pairs[$i]);
992: $i++;
993: }
994: return %returnhash;
995: } else {
1.880 banghart 996: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 997: }
998: }
999:
1000: # -------------------------------------------- put items in domain db files
1001:
1002: sub put_dom {
1.860 raeburn 1003: my ($namespace,$storehash,$udom,$uhome)=@_;
1004: if (!$udom) {
1005: $udom=$env{'user.domain'};
1006: if (defined(&domain($udom,'primary'))) {
1007: $uhome=&domain($udom,'primary');
1008: } else {
1.874 albertel 1009: undef($uhome);
1.860 raeburn 1010: }
1011: } else {
1012: if (!$uhome) {
1013: if (defined(&domain($udom,'primary'))) {
1014: $uhome=&domain($udom,'primary');
1015: }
1016: }
1017: }
1018: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1019: my $items='';
1020: foreach my $item (keys(%$storehash)) {
1021: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1022: }
1023: $items=~s/\&$//;
1024: return &reply("putdom:$udom:$namespace:$items",$uhome);
1025: } else {
1.860 raeburn 1026: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1027: }
1028: }
1029:
1.837 raeburn 1030: sub retrieve_inst_usertypes {
1031: my ($udom) = @_;
1032: my (%returnhash,@order);
1.989 raeburn 1033: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1034: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1035: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1036: %returnhash = %{$domdefs{'inststatustypes'}};
1037: @order = @{$domdefs{'inststatusorder'}};
1038: } else {
1039: if (defined(&domain($udom,'primary'))) {
1040: my $uhome=&domain($udom,'primary');
1041: my $rep=&reply("inst_usertypes:$udom",$uhome);
1042: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1043: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1044: return (\%returnhash,\@order);
1045: }
1046: my ($hashitems,$orderitems) = split(/:/,$rep);
1047: my @pairs=split(/\&/,$hashitems);
1048: foreach my $item (@pairs) {
1049: my ($key,$value)=split(/=/,$item,2);
1050: $key = &unescape($key);
1051: next if ($key =~ /^error: 2 /);
1052: $returnhash{$key}=&thaw_unescape($value);
1053: }
1054: my @esc_order = split(/\&/,$orderitems);
1055: foreach my $item (@esc_order) {
1056: push(@order,&unescape($item));
1057: }
1058: } else {
1059: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1060: }
1061: }
1062: return (\%returnhash,\@order);
1063: }
1064:
1.868 raeburn 1065: sub is_domainimage {
1066: my ($url) = @_;
1067: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1068: if (&domain($1) ne '') {
1069: return '1';
1070: }
1071: }
1072: return;
1073: }
1074:
1.899 raeburn 1075: sub inst_directory_query {
1076: my ($srch) = @_;
1077: my $udom = $srch->{'srchdomain'};
1078: my %results;
1079: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1080: my $outcome;
1.899 raeburn 1081: if ($homeserver ne '') {
1.904 albertel 1082: my $queryid=&reply("querysend:instdirsearch:".
1083: &escape($srch->{'srchby'}).':'.
1084: &escape($srch->{'srchterm'}).':'.
1085: &escape($srch->{'srchtype'}),$homeserver);
1086: my $host=&hostname($homeserver);
1087: if ($queryid !~/^\Q$host\E\_/) {
1088: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1089: return;
1090: }
1091: my $response = &get_query_reply($queryid);
1092: my $maxtries = 5;
1093: my $tries = 1;
1094: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1095: $response = &get_query_reply($queryid);
1096: $tries ++;
1097: }
1098:
1099: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1100: if ($response eq 'unavailable') {
1101: $outcome = $response;
1102: } else {
1103: $outcome = 'ok';
1104: my @matches = split(/\n/,$response);
1105: foreach my $match (@matches) {
1106: my ($key,$value) = split(/=/,$match);
1107: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1108: }
1.899 raeburn 1109: }
1110: }
1111: }
1.909 raeburn 1112: return ($outcome,%results);
1.899 raeburn 1113: }
1114:
1115: sub usersearch {
1116: my ($srch) = @_;
1117: my $dom = $srch->{'srchdomain'};
1118: my %results;
1119: my %libserv = &all_library();
1120: my $query = 'usersearch';
1121: foreach my $tryserver (keys(%libserv)) {
1122: if (&host_domain($tryserver) eq $dom) {
1123: my $host=&hostname($tryserver);
1124: my $queryid=
1.911 raeburn 1125: &reply("querysend:".&escape($query).':'.
1126: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1127: &escape($srch->{'srchtype'}).':'.
1128: &escape($srch->{'srchterm'}),$tryserver);
1129: if ($queryid !~/^\Q$host\E\_/) {
1130: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1131: next;
1.899 raeburn 1132: }
1133: my $reply = &get_query_reply($queryid);
1134: my $maxtries = 1;
1135: my $tries = 1;
1136: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1137: $reply = &get_query_reply($queryid);
1138: $tries ++;
1139: }
1140: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1141: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1142: } else {
1.911 raeburn 1143: my @matches;
1144: if ($reply =~ /\n/) {
1145: @matches = split(/\n/,$reply);
1146: } else {
1147: @matches = split(/\&/,$reply);
1148: }
1.899 raeburn 1149: foreach my $match (@matches) {
1150: my ($uname,$udom,%userhash);
1.911 raeburn 1151: foreach my $entry (split(/:/,$match)) {
1152: my ($key,$value) =
1153: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1154: $userhash{$key} = $value;
1155: if ($key eq 'username') {
1156: $uname = $value;
1157: } elsif ($key eq 'domain') {
1158: $udom = $value;
1.911 raeburn 1159: }
1.899 raeburn 1160: }
1161: $results{$uname.':'.$udom} = \%userhash;
1162: }
1163: }
1164: }
1165: }
1166: return %results;
1167: }
1168:
1.912 raeburn 1169: sub get_instuser {
1170: my ($udom,$uname,$id) = @_;
1171: my $homeserver = &domain($udom,'primary');
1172: my ($outcome,%results);
1173: if ($homeserver ne '') {
1174: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1175: &escape($id).':'.&escape($udom),$homeserver);
1176: my $host=&hostname($homeserver);
1177: if ($queryid !~/^\Q$host\E\_/) {
1178: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1179: return;
1180: }
1181: my $response = &get_query_reply($queryid);
1182: my $maxtries = 5;
1183: my $tries = 1;
1184: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1185: $response = &get_query_reply($queryid);
1186: $tries ++;
1187: }
1188: if (!&error($response) && $response ne 'refused') {
1189: if ($response eq 'unavailable') {
1190: $outcome = $response;
1191: } else {
1192: $outcome = 'ok';
1193: my @matches = split(/\n/,$response);
1194: foreach my $match (@matches) {
1195: my ($key,$value) = split(/=/,$match);
1196: $results{&unescape($key)} = &thaw_unescape($value);
1197: }
1198: }
1199: }
1200: }
1201: my %userinfo;
1202: if (ref($results{$uname}) eq 'HASH') {
1203: %userinfo = %{$results{$uname}};
1204: }
1205: return ($outcome,%userinfo);
1206: }
1207:
1208: sub inst_rulecheck {
1.923 raeburn 1209: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1210: my %returnhash;
1211: if ($udom ne '') {
1212: if (ref($rules) eq 'ARRAY') {
1213: @{$rules} = map {&escape($_);} (@{$rules});
1214: my $rulestr = join(':',@{$rules});
1215: my $homeserver=&domain($udom,'primary');
1216: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1217: my $response;
1218: if ($item eq 'username') {
1219: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1220: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1221: $homeserver));
1.923 raeburn 1222: } elsif ($item eq 'id') {
1223: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1224: ':'.&escape($id).':'.$rulestr,
1225: $homeserver));
1.945 raeburn 1226: } elsif ($item eq 'selfcreate') {
1227: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1228: &escape($udom).':'.&escape($uname).
1229: ':'.$rulestr,$homeserver));
1.923 raeburn 1230: }
1.912 raeburn 1231: if ($response ne 'refused') {
1232: my @pairs=split(/\&/,$response);
1233: foreach my $item (@pairs) {
1234: my ($key,$value)=split(/=/,$item,2);
1235: $key = &unescape($key);
1236: next if ($key =~ /^error: 2 /);
1237: $returnhash{$key}=&thaw_unescape($value);
1238: }
1239: }
1240: }
1241: }
1242: }
1243: return %returnhash;
1244: }
1245:
1246: sub inst_userrules {
1.923 raeburn 1247: my ($udom,$check) = @_;
1.912 raeburn 1248: my (%ruleshash,@ruleorder);
1249: if ($udom ne '') {
1250: my $homeserver=&domain($udom,'primary');
1251: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1252: my $response;
1253: if ($check eq 'id') {
1254: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1255: $homeserver);
1.943 raeburn 1256: } elsif ($check eq 'email') {
1257: $response=&reply('instemailrules:'.&escape($udom),
1258: $homeserver);
1.923 raeburn 1259: } else {
1260: $response=&reply('instuserrules:'.&escape($udom),
1261: $homeserver);
1262: }
1.912 raeburn 1263: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1264: ($response ne 'unknown_cmd') &&
1.912 raeburn 1265: ($response ne 'no_such_host')) {
1266: my ($hashitems,$orderitems) = split(/:/,$response);
1267: my @pairs=split(/\&/,$hashitems);
1268: foreach my $item (@pairs) {
1269: my ($key,$value)=split(/=/,$item,2);
1270: $key = &unescape($key);
1271: next if ($key =~ /^error: 2 /);
1272: $ruleshash{$key}=&thaw_unescape($value);
1273: }
1274: my @esc_order = split(/\&/,$orderitems);
1275: foreach my $item (@esc_order) {
1276: push(@ruleorder,&unescape($item));
1277: }
1278: }
1279: }
1280: }
1281: return (\%ruleshash,\@ruleorder);
1282: }
1283:
1.976 raeburn 1284: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1285:
1286: sub get_domain_defaults {
1287: my ($domain) = @_;
1288: my $cachetime = 60*60*24;
1289: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1290: if (defined($cached)) {
1291: if (ref($result) eq 'HASH') {
1292: return %{$result};
1293: }
1294: }
1295: my %domdefaults;
1296: my %domconfig =
1.989 raeburn 1297: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1298: 'requestcourses','inststatus'],$domain);
1.943 raeburn 1299: if (ref($domconfig{'defaults'}) eq 'HASH') {
1300: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1301: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1302: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1303: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1304: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1305: } else {
1306: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1307: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1308: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1309: }
1.976 raeburn 1310: if (ref($domconfig{'quotas'}) eq 'HASH') {
1311: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1312: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1313: } else {
1314: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1315: }
1316: my @usertools = ('aboutme','blog','portfolio');
1317: foreach my $item (@usertools) {
1318: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1319: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1320: }
1321: }
1322: }
1.985 raeburn 1323: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1324: foreach my $item ('official','unofficial') {
1325: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1326: }
1327: }
1.989 raeburn 1328: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1329: foreach my $item ('inststatustypes','inststatusorder') {
1330: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1331: }
1332: }
1.943 raeburn 1333: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1334: $cachetime);
1335: return %domdefaults;
1336: }
1337:
1.344 www 1338: # --------------------------------------------------- Assign a key to a student
1339:
1340: sub assign_access_key {
1.364 www 1341: #
1342: # a valid key looks like uname:udom#comments
1343: # comments are being appended
1344: #
1.498 www 1345: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1346: $kdom=
1.620 albertel 1347: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1348: $knum=
1.620 albertel 1349: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1350: $cdom=
1.620 albertel 1351: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1352: $cnum=
1.620 albertel 1353: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1354: $udom=$env{'user.name'} unless (defined($udom));
1355: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1356: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1357: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1358: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1359: # assigned to this person
1360: # - this should not happen,
1.345 www 1361: # unless something went wrong
1362: # the first time around
1363: # ready to assign
1.364 www 1364: $logentry=$1.'; '.$logentry;
1.496 www 1365: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1366: $kdom,$knum) eq 'ok') {
1.345 www 1367: # key now belongs to user
1.346 www 1368: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1369: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1370: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1371: return 'ok';
1372: } else {
1373: return
1374: 'error: Count not permanently assign key, will need to be re-entered later.';
1375: }
1376: } else {
1377: return 'error: Could not assign key, try again later.';
1378: }
1.364 www 1379: } elsif (!$existing{$ckey}) {
1.345 www 1380: # the key does not exist
1381: return 'error: The key does not exist';
1382: } else {
1383: # the key is somebody else's
1384: return 'error: The key is already in use';
1385: }
1.344 www 1386: }
1387:
1.364 www 1388: # ------------------------------------------ put an additional comment on a key
1389:
1390: sub comment_access_key {
1391: #
1392: # a valid key looks like uname:udom#comments
1393: # comments are being appended
1394: #
1395: my ($ckey,$cdom,$cnum,$logentry)=@_;
1396: $cdom=
1.620 albertel 1397: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1398: $cnum=
1.620 albertel 1399: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1400: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1401: if ($existing{$ckey}) {
1402: $existing{$ckey}.='; '.$logentry;
1403: # ready to assign
1.367 www 1404: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1405: $cdom,$cnum) eq 'ok') {
1406: return 'ok';
1407: } else {
1408: return 'error: Count not store comment.';
1409: }
1410: } else {
1411: # the key does not exist
1412: return 'error: The key does not exist';
1413: }
1414: }
1415:
1.344 www 1416: # ------------------------------------------------------ Generate a set of keys
1417:
1418: sub generate_access_keys {
1.364 www 1419: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1420: $cdom=
1.620 albertel 1421: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1422: $cnum=
1.620 albertel 1423: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1424: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1425: unless (($cdom) && ($cnum)) { return 0; }
1426: if ($number>10000) { return 0; }
1427: sleep(2); # make sure don't get same seed twice
1428: srand(time()^($$+($$<<15))); # from "Programming Perl"
1429: my $total=0;
1430: for (my $i=1;$i<=$number;$i++) {
1431: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1432: sprintf("%lx",int(100000*rand)).'-'.
1433: sprintf("%lx",int(100000*rand));
1434: $newkey=~s/1/g/g; # folks mix up 1 and l
1435: $newkey=~s/0/h/g; # and also 0 and O
1436: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1437: if ($existing{$newkey}) {
1438: $i--;
1439: } else {
1.364 www 1440: if (&put('accesskeys',
1441: { $newkey => '# generated '.localtime().
1.620 albertel 1442: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1443: '; '.$logentry },
1444: $cdom,$cnum) eq 'ok') {
1.344 www 1445: $total++;
1446: }
1447: }
1448: }
1.620 albertel 1449: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1450: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1451: return $total;
1452: }
1453:
1454: # ------------------------------------------------------- Validate an accesskey
1455:
1456: sub validate_access_key {
1457: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1462: $udom=$env{'user.domain'} unless (defined($udom));
1463: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1464: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1465: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1466: }
1467:
1468: # ------------------------------------- Find the section of student in a course
1.652 albertel 1469: sub devalidate_getsection_cache {
1470: my ($udom,$unam,$courseid)=@_;
1471: my $hashid="$udom:$unam:$courseid";
1472: &devalidate_cache_new('getsection',$hashid);
1473: }
1.298 matthew 1474:
1.815 albertel 1475: sub courseid_to_courseurl {
1476: my ($courseid) = @_;
1477: #already url style courseid
1478: return $courseid if ($courseid =~ m{^/});
1479:
1480: if (exists($env{'course.'.$courseid.'.num'})) {
1481: my $cnum = $env{'course.'.$courseid.'.num'};
1482: my $cdom = $env{'course.'.$courseid.'.domain'};
1483: return "/$cdom/$cnum";
1484: }
1485:
1486: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1487: if (exists($courseinfo{'num'})) {
1488: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1489: }
1490:
1491: return undef;
1492: }
1493:
1.298 matthew 1494: sub getsection {
1495: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1496: my $cachetime=1800;
1.551 albertel 1497:
1498: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1499: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1500: if (defined($cached)) { return $result; }
1501:
1.298 matthew 1502: my %Pending;
1503: my %Expired;
1504: #
1505: # Each role can either have not started yet (pending), be active,
1506: # or have expired.
1507: #
1508: # If there is an active role, we are done.
1509: #
1510: # If there is more than one role which has not started yet,
1511: # choose the one which will start sooner
1512: # If there is one role which has not started yet, return it.
1513: #
1514: # If there is more than one expired role, choose the one which ended last.
1515: # If there is a role which has expired, return it.
1516: #
1.815 albertel 1517: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1518: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1519: foreach my $key (keys(%roleshash)) {
1.479 albertel 1520: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1521: my $section=$1;
1522: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1523: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1524: my $now=time;
1.548 albertel 1525: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1526: $Expired{$end}=$section;
1527: next;
1528: }
1.548 albertel 1529: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1530: $Pending{$start}=$section;
1531: next;
1532: }
1.599 albertel 1533: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1534: }
1535: #
1536: # Presumedly there will be few matching roles from the above
1537: # loop and the sorting time will be negligible.
1538: if (scalar(keys(%Pending))) {
1539: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1540: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1541: }
1542: if (scalar(keys(%Expired))) {
1543: my @sorted = sort {$a <=> $b} keys(%Expired);
1544: my $time = pop(@sorted);
1.599 albertel 1545: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1546: }
1.599 albertel 1547: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1548: }
1.70 www 1549:
1.599 albertel 1550: sub save_cache {
1551: &purge_remembered();
1.722 albertel 1552: #&Apache::loncommon::validate_page();
1.620 albertel 1553: undef(%env);
1.780 albertel 1554: undef($env_loaded);
1.599 albertel 1555: }
1.452 albertel 1556:
1.599 albertel 1557: my $to_remember=-1;
1558: my %remembered;
1559: my %accessed;
1560: my $kicks=0;
1561: my $hits=0;
1.849 albertel 1562: sub make_key {
1563: my ($name,$id) = @_;
1.872 albertel 1564: if (length($id) > 65
1565: && length(&escape($id)) > 200) {
1566: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1567: }
1.849 albertel 1568: return &escape($name.':'.$id);
1569: }
1570:
1.599 albertel 1571: sub devalidate_cache_new {
1572: my ($name,$id,$debug) = @_;
1573: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1574: $id=&make_key($name,$id);
1.599 albertel 1575: $memcache->delete($id);
1576: delete($remembered{$id});
1577: delete($accessed{$id});
1578: }
1579:
1580: sub is_cached_new {
1581: my ($name,$id,$debug) = @_;
1.849 albertel 1582: $id=&make_key($name,$id);
1.599 albertel 1583: if (exists($remembered{$id})) {
1584: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1585: $accessed{$id}=[&gettimeofday()];
1586: $hits++;
1587: return ($remembered{$id},1);
1588: }
1589: my $value = $memcache->get($id);
1590: if (!(defined($value))) {
1591: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1592: return (undef,undef);
1.416 albertel 1593: }
1.599 albertel 1594: if ($value eq '__undef__') {
1595: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1596: $value=undef;
1597: }
1598: &make_room($id,$value,$debug);
1599: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1600: return ($value,1);
1601: }
1602:
1603: sub do_cache_new {
1604: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1605: $id=&make_key($name,$id);
1.599 albertel 1606: my $setvalue=$value;
1607: if (!defined($setvalue)) {
1608: $setvalue='__undef__';
1609: }
1.623 albertel 1610: if (!defined($time) ) {
1611: $time=600;
1612: }
1.599 albertel 1613: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1614: my $result = $memcache->set($id,$setvalue,$time);
1615: if (! $result) {
1.872 albertel 1616: &logthis("caching of id -> $id failed");
1.910 albertel 1617: $memcache->disconnect_all();
1.872 albertel 1618: }
1.600 albertel 1619: # need to make a copy of $value
1.919 albertel 1620: &make_room($id,$value,$debug);
1.599 albertel 1621: return $value;
1622: }
1623:
1624: sub make_room {
1625: my ($id,$value,$debug)=@_;
1.919 albertel 1626:
1627: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1628: : $value;
1.599 albertel 1629: if ($to_remember<0) { return; }
1630: $accessed{$id}=[&gettimeofday()];
1631: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1632: my $to_kick;
1633: my $max_time=0;
1634: foreach my $other (keys(%accessed)) {
1635: if (&tv_interval($accessed{$other}) > $max_time) {
1636: $to_kick=$other;
1637: $max_time=&tv_interval($accessed{$other});
1638: }
1639: }
1640: delete($remembered{$to_kick});
1641: delete($accessed{$to_kick});
1642: $kicks++;
1643: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1644: return;
1645: }
1646:
1.599 albertel 1647: sub purge_remembered {
1.604 albertel 1648: #&logthis("Tossing ".scalar(keys(%remembered)));
1649: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1650: undef(%remembered);
1651: undef(%accessed);
1.428 albertel 1652: }
1.70 www 1653: # ------------------------------------- Read an entry from a user's environment
1654:
1655: sub userenvironment {
1656: my ($udom,$unam,@what)=@_;
1.976 raeburn 1657: my $items;
1658: foreach my $item (@what) {
1659: $items.=&escape($item).'&';
1660: }
1661: $items=~s/\&$//;
1.70 www 1662: my %returnhash=();
1663: my @answer=split(/\&/,
1.976 raeburn 1664: &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70 www 1665: &homeserver($unam,$udom)));
1666: my $i;
1667: for ($i=0;$i<=$#what;$i++) {
1668: $returnhash{$what[$i]}=&unescape($answer[$i]);
1669: }
1670: return %returnhash;
1.1 albertel 1671: }
1672:
1.617 albertel 1673: # ---------------------------------------------------------- Get a studentphoto
1674: sub studentphoto {
1675: my ($udom,$unam,$ext) = @_;
1676: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1677: if (defined($env{'request.course.id'})) {
1.708 raeburn 1678: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1679: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1680: return(&retrievestudentphoto($udom,$unam,$ext));
1681: } else {
1682: my ($result,$perm_reqd)=
1.707 albertel 1683: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1684: if ($result eq 'ok') {
1685: if (!($perm_reqd eq 'yes')) {
1686: return(&retrievestudentphoto($udom,$unam,$ext));
1687: }
1688: }
1689: }
1690: }
1691: } else {
1692: my ($result,$perm_reqd) =
1.707 albertel 1693: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1694: if ($result eq 'ok') {
1695: if (!($perm_reqd eq 'yes')) {
1696: return(&retrievestudentphoto($udom,$unam,$ext));
1697: }
1698: }
1699: }
1700: return '/adm/lonKaputt/lonlogo_broken.gif';
1701: }
1702:
1703: sub retrievestudentphoto {
1704: my ($udom,$unam,$ext,$type) = @_;
1705: my $home=&Apache::lonnet::homeserver($unam,$udom);
1706: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1707: if ($ret eq 'ok') {
1708: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1709: if ($type eq 'thumbnail') {
1710: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1711: }
1712: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1713: return $tokenurl;
1714: } else {
1715: if ($type eq 'thumbnail') {
1716: return '/adm/lonKaputt/genericstudent_tn.gif';
1717: } else {
1718: return '/adm/lonKaputt/lonlogo_broken.gif';
1719: }
1.617 albertel 1720: }
1721: }
1722:
1.263 www 1723: # -------------------------------------------------------------------- New chat
1724:
1725: sub chatsend {
1.724 raeburn 1726: my ($newentry,$anon,$group)=@_;
1.620 albertel 1727: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1728: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1729: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1730: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1731: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1732: &escape($newentry)).':'.$group,$chome);
1.292 www 1733: }
1734:
1735: # ------------------------------------------ Find current version of a resource
1736:
1737: sub getversion {
1738: my $fname=&clutter(shift);
1739: unless ($fname=~/^\/res\//) { return -1; }
1740: return ¤tversion(&filelocation('',$fname));
1741: }
1742:
1743: sub currentversion {
1744: my $fname=shift;
1.599 albertel 1745: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1746: if (defined($cached)) { return $result; }
1.292 www 1747: my $author=$fname;
1748: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1749: my ($udom,$uname)=split(/\//,$author);
1750: my $home=homeserver($uname,$udom);
1751: if ($home eq 'no_host') {
1752: return -1;
1753: }
1754: my $answer=reply("currentversion:$fname",$home);
1755: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1756: return -1;
1757: }
1.599 albertel 1758: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1759: }
1760:
1.1 albertel 1761: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1762:
1.1 albertel 1763: sub subscribe {
1764: my $fname=shift;
1.761 raeburn 1765: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1766: $fname=~s/[\n\r]//g;
1.1 albertel 1767: my $author=$fname;
1768: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1769: my ($udom,$uname)=split(/\//,$author);
1770: my $home=homeserver($uname,$udom);
1.335 albertel 1771: if ($home eq 'no_host') {
1772: return 'not_found';
1.1 albertel 1773: }
1774: my $answer=reply("sub:$fname",$home);
1.64 www 1775: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1776: $answer.=' by '.$home;
1777: }
1.1 albertel 1778: return $answer;
1779: }
1780:
1.8 www 1781: # -------------------------------------------------------------- Replicate file
1782:
1783: sub repcopy {
1784: my $filename=shift;
1.23 www 1785: $filename=~s/\/+/\//g;
1.607 raeburn 1786: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1787: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1788: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1789: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1790: return &repcopy_userfile($filename);
1791: }
1.532 albertel 1792: $filename=~s/[\n\r]//g;
1.8 www 1793: my $transname="$filename.in.transfer";
1.828 www 1794: # FIXME: this should flock
1.607 raeburn 1795: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1796: my $remoteurl=subscribe($filename);
1.64 www 1797: if ($remoteurl =~ /^con_lost by/) {
1798: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1799: return 'unavailable';
1.8 www 1800: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1801: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1802: return 'not_found';
1.64 www 1803: } elsif ($remoteurl =~ /^rejected by/) {
1804: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1805: return 'forbidden';
1.20 www 1806: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1807: return 'ok';
1.8 www 1808: } else {
1.290 www 1809: my $author=$filename;
1810: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1811: my ($udom,$uname)=split(/\//,$author);
1812: my $home=homeserver($uname,$udom);
1813: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1814: my @parts=split(/\//,$filename);
1815: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1816: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1817: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1818: return 'bad_request';
1.8 www 1819: }
1820: my $count;
1821: for ($count=5;$count<$#parts;$count++) {
1822: $path.="/$parts[$count]";
1823: if ((-e $path)!=1) {
1824: mkdir($path,0777);
1825: }
1826: }
1827: my $ua=new LWP::UserAgent;
1828: my $request=new HTTP::Request('GET',"$remoteurl");
1829: my $response=$ua->request($request,$transname);
1830: if ($response->is_error()) {
1831: unlink($transname);
1832: my $message=$response->status_line;
1.672 albertel 1833: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1834: ." LWP get: $message: $filename</font>");
1.607 raeburn 1835: return 'unavailable';
1.8 www 1836: } else {
1.16 www 1837: if ($remoteurl!~/\.meta$/) {
1838: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1839: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1840: if ($mresponse->is_error()) {
1841: unlink($filename.'.meta');
1842: &logthis(
1.672 albertel 1843: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1844: }
1845: }
1.8 www 1846: rename($transname,$filename);
1.607 raeburn 1847: return 'ok';
1.8 www 1848: }
1.290 www 1849: }
1.8 www 1850: }
1.330 www 1851: }
1852:
1853: # ------------------------------------------------ Get server side include body
1854: sub ssi_body {
1.381 albertel 1855: my ($filelink,%form)=@_;
1.606 matthew 1856: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1857: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1858: }
1.953 www 1859: my $output='';
1860: my $response;
1.980 raeburn 1861: if ($filelink=~/^https?\:/) {
1.954 raeburn 1862: ($output,$response)=&externalssi($filelink);
1.953 www 1863: } else {
1864: ($output,$response)=&ssi($filelink,%form);
1865: }
1.778 albertel 1866: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1867: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1868: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1869: if (wantarray) {
1870: return ($output, $response);
1871: } else {
1872: return $output;
1873: }
1.8 www 1874: }
1875:
1.15 www 1876: # --------------------------------------------------------- Server Side Include
1877:
1.782 albertel 1878: sub absolute_url {
1879: my ($host_name) = @_;
1880: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1881: if ($host_name eq '') {
1882: $host_name = $ENV{'SERVER_NAME'};
1883: }
1884: return $protocol.$host_name;
1885: }
1886:
1.942 foxr 1887: #
1888: # Server side include.
1889: # Parameters:
1890: # fn Possibly encrypted resource name/id.
1891: # form Hash that describes how the rendering should be done
1892: # and other things.
1.944 foxr 1893: # Returns:
1.950 raeburn 1894: # Scalar context: The content of the response.
1895: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1896: #
1.15 www 1897: sub ssi {
1898:
1.944 foxr 1899: my ($fn,%form)=@_;
1.15 www 1900: my $ua=new LWP::UserAgent;
1.23 www 1901: my $request;
1.711 albertel 1902:
1903: $form{'no_update_last_known'}=1;
1.895 albertel 1904: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1905: if (%form) {
1.782 albertel 1906: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1907: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1908: } else {
1.782 albertel 1909: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1910: }
1911:
1.15 www 1912: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1913: my $response=$ua->request($request);
1914:
1.944 foxr 1915: if (wantarray) {
1916: return ($response->content, $response);
1917: } else {
1918: return $response->content;
1.942 foxr 1919: }
1.324 www 1920: }
1921:
1922: sub externalssi {
1923: my ($url)=@_;
1924: my $ua=new LWP::UserAgent;
1925: my $request=new HTTP::Request('GET',$url);
1926: my $response=$ua->request($request);
1.954 raeburn 1927: if (wantarray) {
1928: return ($response->content, $response);
1929: } else {
1930: return $response->content;
1931: }
1.15 www 1932: }
1.254 www 1933:
1.492 albertel 1934: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1935:
1936: sub allowuploaded {
1937: my ($srcurl,$url)=@_;
1938: $url=&clutter(&declutter($url));
1939: my $dir=$url;
1940: $dir=~s/\/[^\/]+$//;
1941: my %httpref=();
1942: my $httpurl=&hreflocation('',$url);
1943: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1944: &Apache::lonnet::appenv(\%httpref);
1.254 www 1945: }
1.477 raeburn 1946:
1.478 albertel 1947: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1948: # input: action, courseID, current domain, intended
1.637 raeburn 1949: # path to file, source of file, instruction to parse file for objects,
1950: # ref to hash for embedded objects,
1951: # ref to hash for codebase of java objects.
1952: #
1.485 raeburn 1953: # output: url to file (if action was uploaddoc),
1954: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1955: #
1.478 albertel 1956: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1957: # course.
1.477 raeburn 1958: #
1.478 albertel 1959: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1960: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1961: # course's home server.
1.477 raeburn 1962: #
1.478 albertel 1963: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1964: # be copied from $source (current location) to
1965: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1966: # and will then be copied to
1967: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1968: # course's home server.
1.485 raeburn 1969: #
1.481 raeburn 1970: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1971: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1972: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1973: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1974: # in course's home server.
1.637 raeburn 1975: #
1.477 raeburn 1976:
1977: sub process_coursefile {
1.638 albertel 1978: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1979: my $fetchresult;
1.638 albertel 1980: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1981: if ($action eq 'propagate') {
1.638 albertel 1982: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1983: $home);
1.481 raeburn 1984: } else {
1.477 raeburn 1985: my $fpath = '';
1986: my $fname = $file;
1.478 albertel 1987: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1988: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1989: my $filepath = &build_filepath($fpath);
1.481 raeburn 1990: if ($action eq 'copy') {
1991: if ($source eq '') {
1992: $fetchresult = 'no source file';
1993: return $fetchresult;
1994: } else {
1995: my $destination = $filepath.'/'.$fname;
1996: rename($source,$destination);
1997: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1998: $home);
1.481 raeburn 1999: }
2000: } elsif ($action eq 'uploaddoc') {
2001: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2002: print $fh $env{'form.'.$source};
1.481 raeburn 2003: close($fh);
1.637 raeburn 2004: if ($parser eq 'parse') {
1.961 raeburn 2005: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 2006: unless ($parse_result eq 'ok') {
2007: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2008: }
2009: }
1.477 raeburn 2010: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2011: $home);
1.481 raeburn 2012: if ($fetchresult eq 'ok') {
2013: return '/uploaded/'.$fpath.'/'.$fname;
2014: } else {
2015: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2016: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2017: return '/adm/notfound.html';
2018: }
1.477 raeburn 2019: }
2020: }
1.485 raeburn 2021: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2022: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2023: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2024: }
2025: return $fetchresult;
2026: }
2027:
1.637 raeburn 2028: sub build_filepath {
2029: my ($fpath) = @_;
2030: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2031: unless ($fpath eq '') {
2032: my @parts=split('/',$fpath);
2033: foreach my $part (@parts) {
2034: $filepath.= '/'.$part;
2035: if ((-e $filepath)!=1) {
2036: mkdir($filepath,0777);
2037: }
2038: }
2039: }
2040: return $filepath;
2041: }
2042:
2043: sub store_edited_file {
1.638 albertel 2044: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2045: my $file = $primary_url;
2046: $file =~ s#^/uploaded/$docudom/$docuname/##;
2047: my $fpath = '';
2048: my $fname = $file;
2049: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2050: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2051: my $filepath = &build_filepath($fpath);
2052: open(my $fh,'>'.$filepath.'/'.$fname);
2053: print $fh $content;
2054: close($fh);
1.638 albertel 2055: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2056: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2057: $home);
1.637 raeburn 2058: if ($$fetchresult eq 'ok') {
2059: return '/uploaded/'.$fpath.'/'.$fname;
2060: } else {
1.638 albertel 2061: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2062: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2063: return '/adm/notfound.html';
2064: }
2065: }
2066:
1.531 albertel 2067: sub clean_filename {
1.831 albertel 2068: my ($fname,$args)=@_;
1.315 www 2069: # Replace Windows backslashes by forward slashes
1.257 www 2070: $fname=~s/\\/\//g;
1.831 albertel 2071: if (!$args->{'keep_path'}) {
2072: # Get rid of everything but the actual filename
2073: $fname=~s/^.*\/([^\/]+)$/$1/;
2074: }
1.315 www 2075: # Replace spaces by underscores
2076: $fname=~s/\s+/\_/g;
2077: # Replace all other weird characters by nothing
1.831 albertel 2078: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2079: # Replace all .\d. sequences with _\d. so they no longer look like version
2080: # numbers
2081: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2082: return $fname;
2083: }
1.984 neumanie 2084: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2085: sub resizeImage {
2086: my($img_url) = @_;
2087: my $ima = Image::Magick->new;
2088: $ima->Read($img_url);
2089: if($ima->Get('width') > 400)
2090: {
2091: my $factor = $ima->Get('width')/400;
2092: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2093: }
2094: if($ima->Get('height') > 500)
2095: {
2096: my $factor = $ima->Get('height')/500;
2097: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2098: }
2099:
2100: $ima->Write($img_url);
2101: }
1.531 albertel 2102:
1.977 amueller 2103: #Wrapper function for userphotoupload
2104: sub userphotoupload
2105: {
2106: my($formname,$subdir) = @_;
2107: $upload_photo_form = 1;
2108: return &userfileupload($formname,undef,$subdir);
2109: }
2110:
1.608 albertel 2111: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2112: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2113: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2114: # $coursedoc - if true up to the current course
2115: # if false
2116: # $subdir - directory in userfile to store the file into
1.858 raeburn 2117: # $parser - instruction to parse file for objects ($parser = parse)
2118: # $allfiles - reference to hash for embedded objects
2119: # $codebase - reference to hash for codebase of java objects
2120: # $desuname - username for permanent storage of uploaded file
2121: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2122: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2123: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2124: #
1.686 albertel 2125: # output: url of file in userspace, or error: <message>
2126: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2127:
2128:
1.531 albertel 2129: sub userfileupload {
1.860 raeburn 2130: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2131: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2132: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2133: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2134: $fname=&clean_filename($fname);
1.315 www 2135: # See if there is anything left
1.257 www 2136: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2137: chop($env{'form.'.$formname});
1.523 raeburn 2138: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2139: my $now = time;
2140: my $filepath = 'tmp/helprequests/'.$now;
2141: my @parts=split(/\//,$filepath);
2142: my $fullpath = $perlvar{'lonDaemons'};
2143: for (my $i=0;$i<@parts;$i++) {
2144: $fullpath .= '/'.$parts[$i];
2145: if ((-e $fullpath)!=1) {
2146: mkdir($fullpath,0777);
2147: }
2148: }
2149: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2150: print $fh $env{'form.'.$formname};
1.523 raeburn 2151: close($fh);
1.741 raeburn 2152: return $fullpath.'/'.$fname;
2153: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2154: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2155: '_'.$env{'user.domain'}.'/pending';
2156: my @parts=split(/\//,$filepath);
2157: my $fullpath = $perlvar{'lonDaemons'};
2158: for (my $i=0;$i<@parts;$i++) {
2159: $fullpath .= '/'.$parts[$i];
2160: if ((-e $fullpath)!=1) {
2161: mkdir($fullpath,0777);
2162: }
2163: }
2164: open(my $fh,'>'.$fullpath.'/'.$fname);
2165: print $fh $env{'form.'.$formname};
2166: close($fh);
2167: return $fullpath.'/'.$fname;
1.523 raeburn 2168: }
1.995 raeburn 2169: if ($subdir eq 'scantron') {
2170: $fname = 'scantron_orig_'.$fname;
2171: } else {
1.258 www 2172: # Create the directory if not present
1.995 raeburn 2173: $fname="$subdir/$fname";
2174: }
1.259 www 2175: if ($coursedoc) {
1.638 albertel 2176: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2177: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2178: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2179: return &finishuserfileupload($docuname,$docudom,
2180: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2181: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2182: } else {
1.620 albertel 2183: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2184: return &process_coursefile('uploaddoc',$docuname,$docudom,
2185: $fname,$formname,$parser,
2186: $allfiles,$codebase);
1.481 raeburn 2187: }
1.719 banghart 2188: } elsif (defined($destuname)) {
2189: my $docuname=$destuname;
2190: my $docudom=$destudom;
1.860 raeburn 2191: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2192: $parser,$allfiles,$codebase,
2193: $thumbwidth,$thumbheight);
1.719 banghart 2194:
1.259 www 2195: } else {
1.638 albertel 2196: my $docuname=$env{'user.name'};
2197: my $docudom=$env{'user.domain'};
1.714 raeburn 2198: if (exists($env{'form.group'})) {
2199: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2200: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2201: }
1.860 raeburn 2202: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2203: $parser,$allfiles,$codebase,
2204: $thumbwidth,$thumbheight);
1.259 www 2205: }
1.271 www 2206: }
2207:
2208: sub finishuserfileupload {
1.860 raeburn 2209: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2210: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2211: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2212: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2213:
1.860 raeburn 2214: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2215: $file=$fname;
2216: if ($fname=~m|/|) {
2217: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2218: $path.=$fnamepath.'/';
2219: }
1.259 www 2220: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2221: my $count;
2222: for ($count=4;$count<=$#parts;$count++) {
2223: $filepath.="/$parts[$count]";
2224: if ((-e $filepath)!=1) {
2225: mkdir($filepath,0777);
2226: }
2227: }
1.984 neumanie 2228:
1.258 www 2229: # Save the file
2230: {
1.701 albertel 2231: if (!open(FH,'>'.$filepath.'/'.$file)) {
2232: &logthis('Failed to create '.$filepath.'/'.$file);
2233: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2234: return '/adm/notfound.html';
2235: }
2236: if (!print FH ($env{'form.'.$formname})) {
2237: &logthis('Failed to write to '.$filepath.'/'.$file);
2238: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2239: return '/adm/notfound.html';
2240: }
1.570 albertel 2241: close(FH);
1.977 amueller 2242: if($upload_photo_form==1)
2243: {
1.984 neumanie 2244: resizeImage($filepath.'/'.$file);
1.977 amueller 2245: $upload_photo_form = 0;
2246: }
1.258 www 2247: }
1.637 raeburn 2248: if ($parser eq 'parse') {
1.961 raeburn 2249: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2250: $codebase);
1.637 raeburn 2251: unless ($parse_result eq 'ok') {
1.638 albertel 2252: &logthis('Failed to parse '.$filepath.$file.
2253: ' for embedded media: '.$parse_result);
1.637 raeburn 2254: }
2255: }
1.860 raeburn 2256: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2257: my $input = $filepath.'/'.$file;
2258: my $output = $filepath.'/'.'tn-'.$file;
2259: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2260: system("convert -sample $thumbsize $input $output");
2261: if (-e $filepath.'/'.'tn-'.$file) {
2262: $fetchthumb = 1;
2263: }
2264: }
1.858 raeburn 2265:
1.259 www 2266: # Notify homeserver to grep it
2267: #
1.984 neumanie 2268: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2269: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2270: if ($fetchresult eq 'ok') {
1.860 raeburn 2271: if ($fetchthumb) {
2272: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2273: if ($thumbresult ne 'ok') {
2274: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2275: $docuhome.': '.$thumbresult);
2276: }
2277: }
1.259 www 2278: #
1.258 www 2279: # Return the URL to it
1.494 albertel 2280: return '/uploaded/'.$path.$file;
1.263 www 2281: } else {
1.494 albertel 2282: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2283: ': '.$fetchresult);
1.263 www 2284: return '/adm/notfound.html';
1.858 raeburn 2285: }
1.493 albertel 2286: }
2287:
1.637 raeburn 2288: sub extract_embedded_items {
1.961 raeburn 2289: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2290: my @state = ();
2291: my %javafiles = (
2292: codebase => '',
2293: code => '',
2294: archive => ''
2295: );
2296: my %mediafiles = (
2297: src => '',
2298: movie => '',
2299: );
1.648 raeburn 2300: my $p;
2301: if ($content) {
2302: $p = HTML::LCParser->new($content);
2303: } else {
1.961 raeburn 2304: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2305: }
1.641 albertel 2306: while (my $t=$p->get_token()) {
1.640 albertel 2307: if ($t->[0] eq 'S') {
2308: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2309: push(@state, $tagname);
1.648 raeburn 2310: if (lc($tagname) eq 'allow') {
2311: &add_filetype($allfiles,$attr->{'src'},'src');
2312: }
1.640 albertel 2313: if (lc($tagname) eq 'img') {
2314: &add_filetype($allfiles,$attr->{'src'},'src');
2315: }
1.886 albertel 2316: if (lc($tagname) eq 'a') {
2317: &add_filetype($allfiles,$attr->{'href'},'href');
2318: }
1.645 raeburn 2319: if (lc($tagname) eq 'script') {
2320: if ($attr->{'archive'} =~ /\.jar$/i) {
2321: &add_filetype($allfiles,$attr->{'archive'},'archive');
2322: } else {
2323: &add_filetype($allfiles,$attr->{'src'},'src');
2324: }
2325: }
2326: if (lc($tagname) eq 'link') {
2327: if (lc($attr->{'rel'}) eq 'stylesheet') {
2328: &add_filetype($allfiles,$attr->{'href'},'href');
2329: }
2330: }
1.640 albertel 2331: if (lc($tagname) eq 'object' ||
2332: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2333: foreach my $item (keys(%javafiles)) {
2334: $javafiles{$item} = '';
2335: }
2336: }
2337: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2338: my $name = lc($attr->{'name'});
2339: foreach my $item (keys(%javafiles)) {
2340: if ($name eq $item) {
2341: $javafiles{$item} = $attr->{'value'};
2342: last;
2343: }
2344: }
2345: foreach my $item (keys(%mediafiles)) {
2346: if ($name eq $item) {
2347: &add_filetype($allfiles, $attr->{'value'}, 'value');
2348: last;
2349: }
2350: }
2351: }
2352: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2353: foreach my $item (keys(%javafiles)) {
2354: if ($attr->{$item}) {
2355: $javafiles{$item} = $attr->{$item};
2356: last;
2357: }
2358: }
2359: foreach my $item (keys(%mediafiles)) {
2360: if ($attr->{$item}) {
2361: &add_filetype($allfiles,$attr->{$item},$item);
2362: last;
2363: }
2364: }
2365: }
2366: } elsif ($t->[0] eq 'E') {
2367: my ($tagname) = ($t->[1]);
2368: if ($javafiles{'codebase'} ne '') {
2369: $javafiles{'codebase'} .= '/';
2370: }
2371: if (lc($tagname) eq 'applet' ||
2372: lc($tagname) eq 'object' ||
2373: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2374: ) {
2375: foreach my $item (keys(%javafiles)) {
2376: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2377: my $file=$javafiles{'codebase'}.$javafiles{$item};
2378: &add_filetype($allfiles,$file,$item);
2379: }
2380: }
2381: }
2382: pop @state;
2383: }
2384: }
1.637 raeburn 2385: return 'ok';
2386: }
2387:
1.639 albertel 2388: sub add_filetype {
2389: my ($allfiles,$file,$type)=@_;
2390: if (exists($allfiles->{$file})) {
2391: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2392: push(@{$allfiles->{$file}}, &escape($type));
2393: }
2394: } else {
2395: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2396: }
2397: }
2398:
1.493 albertel 2399: sub removeuploadedurl {
1.984 neumanie 2400: my ($url)=@_;
2401: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2402: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2403: }
2404:
2405: sub removeuserfile {
2406: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2407: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2408: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2409: if ($result eq 'ok') {
1.798 raeburn 2410: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2411: my $metafile = $fname.'.meta';
2412: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2413: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2414: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2415: my $sqlresult =
1.823 albertel 2416: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2417: 'portfolio_metadata',$group,
2418: 'delete');
1.798 raeburn 2419: }
2420: }
2421: return $result;
1.257 www 2422: }
1.15 www 2423:
1.530 albertel 2424: sub mkdiruserfile {
2425: my ($docuname,$docudom,$dir)=@_;
2426: my $home=&homeserver($docuname,$docudom);
2427: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2428: }
2429:
1.531 albertel 2430: sub renameuserfile {
2431: my ($docuname,$docudom,$old,$new)=@_;
2432: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2433: my $result = &reply("renameuserfile:$docudom:$docuname:".
2434: &escape("$old").':'.&escape("$new"),$home);
2435: if ($result eq 'ok') {
2436: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2437: my $oldmeta = $old.'.meta';
2438: my $newmeta = $new.'.meta';
2439: my $metaresult =
2440: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2441: my $url = "/uploaded/$docudom/$docuname/$old";
2442: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2443: my $sqlresult =
1.823 albertel 2444: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2445: 'portfolio_metadata',$group,
2446: 'delete');
1.798 raeburn 2447: }
2448: }
2449: return $result;
1.531 albertel 2450: }
2451:
1.14 www 2452: # ------------------------------------------------------------------------- Log
2453:
2454: sub log {
2455: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2456: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2457: }
2458:
2459: # ------------------------------------------------------------------ Course Log
1.352 www 2460: #
2461: # This routine flushes several buffers of non-mission-critical nature
2462: #
1.157 www 2463:
2464: sub flushcourselogs {
1.352 www 2465: &logthis('Flushing log buffers');
2466: #
2467: # course logs
2468: # This is a log of all transactions in a course, which can be used
2469: # for data mining purposes
2470: #
2471: # It also collects the courseid database, which lists last transaction
2472: # times and course titles for all courseids
2473: #
2474: my %courseidbuffer=();
1.921 raeburn 2475: foreach my $crsid (keys(%courselogs)) {
1.352 www 2476: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2477: &escape($courselogs{$crsid}),
2478: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2479: delete $courselogs{$crsid};
2480: } else {
2481: &logthis('Failed to flush log buffer for '.$crsid);
2482: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2483: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2484: " exceeded maximum size, deleting.</font>");
2485: delete $courselogs{$crsid};
2486: }
1.352 www 2487: }
1.920 raeburn 2488: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2489: 'description' => $coursedescrbuf{$crsid},
2490: 'inst_code' => $courseinstcodebuf{$crsid},
2491: 'type' => $coursetypebuf{$crsid},
2492: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2493: };
1.191 harris41 2494: }
1.352 www 2495: #
2496: # Write course id database (reverse lookup) to homeserver of courses
2497: # Is used in pickcourse
2498: #
1.840 albertel 2499: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2500: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2501: $courseidbuffer{$crs_home},
2502: $crs_home,'timeonly');
1.352 www 2503: }
2504: #
2505: # File accesses
2506: # Writes to the dynamic metadata of resources to get hit counts, etc.
2507: #
1.449 matthew 2508: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2509: if ($entry =~ /___count$/) {
2510: my ($dom,$name);
1.807 albertel 2511: ($dom,$name,undef)=
1.811 albertel 2512: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2513: if (! defined($dom) || $dom eq '' ||
2514: ! defined($name) || $name eq '') {
1.620 albertel 2515: my $cid = $env{'request.course.id'};
2516: $dom = $env{'request.'.$cid.'.domain'};
2517: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2518: }
1.450 matthew 2519: my $value = $accesshash{$entry};
2520: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2521: my %temphash=($url => $value);
1.449 matthew 2522: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2523: if ($result eq 'ok') {
2524: delete $accesshash{$entry};
2525: } elsif ($result eq 'unknown_cmd') {
2526: # Target server has old code running on it.
1.450 matthew 2527: my %temphash=($entry => $value);
1.449 matthew 2528: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2529: delete $accesshash{$entry};
2530: }
2531: }
2532: } else {
1.811 albertel 2533: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2534: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2535: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2536: delete $accesshash{$entry};
2537: }
1.185 www 2538: }
1.191 harris41 2539: }
1.352 www 2540: #
2541: # Roles
2542: # Reverse lookup of user roles for course faculty/staff and co-authorship
2543: #
1.800 albertel 2544: foreach my $entry (keys(%userrolehash)) {
1.351 www 2545: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2546: split(/\:/,$entry);
2547: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2548: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2549: $rudom,$runame) eq 'ok') {
2550: delete $userrolehash{$entry};
2551: }
2552: }
1.662 raeburn 2553: #
2554: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2555: #
2556: my %domrolebuffer = ();
2557: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2558: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2559: if ($domrolebuffer{$rudom}) {
2560: $domrolebuffer{$rudom}.='&'.&escape($entry).
2561: '='.&escape($domainrolehash{$entry});
2562: } else {
2563: $domrolebuffer{$rudom}.=&escape($entry).
2564: '='.&escape($domainrolehash{$entry});
2565: }
2566: delete $domainrolehash{$entry};
2567: }
2568: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2569: my %servers = &get_servers($dom,'library');
2570: foreach my $tryserver (keys(%servers)) {
2571: unless (&reply('domroleput:'.$dom.':'.
2572: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2573: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2574: }
1.662 raeburn 2575: }
2576: }
1.186 www 2577: $dumpcount++;
1.157 www 2578: }
2579:
2580: sub courselog {
2581: my $what=shift;
1.158 www 2582: $what=time.':'.$what;
1.620 albertel 2583: unless ($env{'request.course.id'}) { return ''; }
2584: $coursedombuf{$env{'request.course.id'}}=
2585: $env{'course.'.$env{'request.course.id'}.'.domain'};
2586: $coursenumbuf{$env{'request.course.id'}}=
2587: $env{'course.'.$env{'request.course.id'}.'.num'};
2588: $coursehombuf{$env{'request.course.id'}}=
2589: $env{'course.'.$env{'request.course.id'}.'.home'};
2590: $coursedescrbuf{$env{'request.course.id'}}=
2591: $env{'course.'.$env{'request.course.id'}.'.description'};
2592: $courseinstcodebuf{$env{'request.course.id'}}=
2593: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2594: $courseownerbuf{$env{'request.course.id'}}=
2595: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2596: $coursetypebuf{$env{'request.course.id'}}=
2597: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2598: if (defined $courselogs{$env{'request.course.id'}}) {
2599: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2600: } else {
1.620 albertel 2601: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2602: }
1.620 albertel 2603: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2604: &flushcourselogs();
2605: }
1.158 www 2606: }
2607:
2608: sub courseacclog {
2609: my $fnsymb=shift;
1.620 albertel 2610: unless ($env{'request.course.id'}) { return ''; }
2611: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2612: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2613: $what.=':POST';
1.583 matthew 2614: # FIXME: Probably ought to escape things....
1.800 albertel 2615: foreach my $key (keys(%env)) {
2616: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2617: my $formitem = $1;
2618: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2619: $what.=':'.$formitem.'='.$env{$key};
2620: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2621: $what.=':'.$formitem.'='.$env{$key};
2622: }
1.158 www 2623: }
1.191 harris41 2624: }
1.583 matthew 2625: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2626: # FIXME: We should not be depending on a form parameter that someone
2627: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2628: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2629: $what.= ':POST';
2630: # FIXME: Probably ought to escape things....
2631: foreach my $element ('courseexp','crsfulltext','crsrelated',
2632: 'crsdiscuss') {
1.620 albertel 2633: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2634: }
2635: }
1.158 www 2636: }
2637: &courselog($what);
1.149 www 2638: }
2639:
1.185 www 2640: sub countacc {
2641: my $url=&declutter(shift);
1.458 matthew 2642: return if (! defined($url) || $url eq '');
1.620 albertel 2643: unless ($env{'request.course.id'}) { return ''; }
2644: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2645: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2646: $accesshash{$key}++;
1.185 www 2647: }
1.349 www 2648:
1.361 www 2649: sub linklog {
2650: my ($from,$to)=@_;
2651: $from=&declutter($from);
2652: $to=&declutter($to);
2653: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2654: $accesshash{$to.'___'.$from.'___goto'}=1;
2655: }
2656:
1.349 www 2657: sub userrolelog {
2658: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2659: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2660: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2661: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2662: ($trole=~/^ta/)) {
1.350 www 2663: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2664: $userrolehash
2665: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2666: =$tend.':'.$tstart;
1.662 raeburn 2667: }
1.898 albertel 2668: if (($env{'request.role'} =~ /dc\./) &&
2669: (($trole=~/^au/) || ($trole=~/^in/) ||
2670: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2671: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2672: $userrolehash
2673: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2674: =$tend.':'.$tstart;
2675: }
1.662 raeburn 2676: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2677: ($trole=~/^li/) || ($trole=~/^li/) ||
2678: ($trole=~/^au/) || ($trole=~/^dg/) ||
2679: ($trole=~/^sc/)) {
2680: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2681: $domainrolehash
2682: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2683: = $tend.':'.$tstart;
2684: }
1.351 www 2685: }
2686:
1.957 raeburn 2687: sub courserolelog {
2688: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2689: if (($trole eq 'cc') || ($trole eq 'in') ||
2690: ($trole eq 'ep') || ($trole eq 'ad') ||
2691: ($trole eq 'ta') || ($trole eq 'st') ||
2692: ($trole=~/^cr/) || ($trole eq 'gr')) {
2693: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2694: my $cdom = $1;
2695: my $cnum = $2;
2696: my $sec = $3;
2697: my $namespace = 'rolelog';
2698: my %storehash = (
2699: role => $trole,
2700: start => $tstart,
2701: end => $tend,
2702: selfenroll => $selfenroll,
2703: context => $context,
2704: );
2705: if ($trole eq 'gr') {
2706: $namespace = 'groupslog';
2707: $storehash{'group'} = $sec;
2708: } else {
2709: $storehash{'section'} = $sec;
2710: }
2711: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2712: if (($trole ne 'st') || ($sec ne '')) {
2713: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2714: }
1.957 raeburn 2715: }
2716: }
2717: return;
2718: }
2719:
1.351 www 2720: sub get_course_adv_roles {
1.948 raeburn 2721: my ($cid,$codes) = @_;
1.620 albertel 2722: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2723: my %coursehash=&coursedescription($cid);
1.988 raeburn 2724: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2725: my %nothide=();
1.800 albertel 2726: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2727: if ($user !~ /:/) {
2728: $nothide{join(':',split(/[\@]/,$user))}=1;
2729: } else {
2730: $nothide{$user}=1;
2731: }
1.470 www 2732: }
1.351 www 2733: my %returnhash=();
2734: my %dumphash=
2735: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2736: my $now=time;
1.997 raeburn 2737: my %privileged;
1.800 albertel 2738: foreach my $entry (keys %dumphash) {
2739: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2740: if (($tstart) && ($tstart<0)) { next; }
2741: if (($tend) && ($tend<$now)) { next; }
2742: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2743: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2744: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2745: unless (ref($privileged{$domain}) eq 'HASH') {
2746: my %dompersonnel =
1.998 raeburn 2747: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2748: $privileged{$domain} = {};
2749: foreach my $server (keys(%dompersonnel)) {
1.999 ! raeburn 2750: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2751: foreach my $user (keys(%{$dompersonnel{$server}})) {
2752: my ($trole,$uname,$udom) = split(/:/,$user);
2753: $privileged{$udom}{$uname} = 1;
2754: }
2755: }
2756: }
2757: }
2758: if ((exists($privileged{$domain}{$username})) &&
2759: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2760: if ($role eq 'cr') { next; }
1.948 raeburn 2761: if ($codes) {
2762: if ($section) { $role .= ':'.$section; }
2763: if ($returnhash{$role}) {
2764: $returnhash{$role}.=','.$username.':'.$domain;
2765: } else {
2766: $returnhash{$role}=$username.':'.$domain;
2767: }
1.351 www 2768: } else {
1.988 raeburn 2769: my $key=&plaintext($role,$crstype);
1.973 bisitz 2770: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2771: if ($returnhash{$key}) {
2772: $returnhash{$key}.=','.$username.':'.$domain;
2773: } else {
2774: $returnhash{$key}=$username.':'.$domain;
2775: }
1.351 www 2776: }
1.948 raeburn 2777: }
1.400 www 2778: return %returnhash;
2779: }
2780:
2781: sub get_my_roles {
1.937 raeburn 2782: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2783: unless (defined($uname)) { $uname=$env{'user.name'}; }
2784: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2785: my (%dumphash,%nothide);
1.858 raeburn 2786: if ($context eq 'userroles') {
2787: %dumphash = &dump('roles',$udom,$uname);
2788: } else {
2789: %dumphash=
1.400 www 2790: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2791: if ($hidepriv) {
2792: my %coursehash=&coursedescription($udom.'_'.$uname);
2793: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2794: if ($user !~ /:/) {
2795: $nothide{join(':',split(/[\@]/,$user))} = 1;
2796: } else {
2797: $nothide{$user} = 1;
2798: }
2799: }
2800: }
1.858 raeburn 2801: }
1.400 www 2802: my %returnhash=();
2803: my $now=time;
1.999 ! raeburn 2804: my %privileged;
1.800 albertel 2805: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2806: my ($role,$tend,$tstart);
2807: if ($context eq 'userroles') {
2808: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2809: } else {
2810: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2811: }
1.400 www 2812: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2813: my $status = 'active';
1.939 raeburn 2814: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2815: $status = 'previous';
2816: }
2817: if (($tstart) && ($now<$tstart)) {
2818: $status = 'future';
2819: }
2820: if (ref($types) eq 'ARRAY') {
2821: if (!grep(/^\Q$status\E$/,@{$types})) {
2822: next;
2823: }
2824: } else {
2825: if ($status ne 'active') {
2826: next;
2827: }
2828: }
1.867 raeburn 2829: my ($rolecode,$username,$domain,$section,$area);
2830: if ($context eq 'userroles') {
2831: ($area,$rolecode) = split(/_/,$entry);
2832: (undef,$domain,$username,$section) = split(/\//,$area);
2833: } else {
2834: ($role,$username,$domain,$section) = split(/\:/,$entry);
2835: }
1.832 raeburn 2836: if (ref($roledoms) eq 'ARRAY') {
2837: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2838: next;
2839: }
2840: }
2841: if (ref($roles) eq 'ARRAY') {
2842: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2843: if ($role =~ /^cr\//) {
2844: if (!grep(/^cr$/,@{$roles})) {
2845: next;
2846: }
2847: } else {
2848: next;
2849: }
1.832 raeburn 2850: }
1.867 raeburn 2851: }
1.937 raeburn 2852: if ($hidepriv) {
1.999 ! raeburn 2853: if ($context eq 'userroles') {
! 2854: if ((&privileged($username,$domain)) &&
! 2855: (!$nothide{$username.':'.$domain})) {
! 2856: next;
! 2857: }
! 2858: } else {
! 2859: unless (ref($privileged{$domain}) eq 'HASH') {
! 2860: my %dompersonnel =
! 2861: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
! 2862: $privileged{$domain} = {};
! 2863: if (keys(%dompersonnel)) {
! 2864: foreach my $server (keys(%dompersonnel)) {
! 2865: if (ref($dompersonnel{$server}) eq 'HASH') {
! 2866: foreach my $user (keys(%{$dompersonnel{$server}})) {
! 2867: my ($trole,$uname,$udom) = split(/:/,$user);
! 2868: $privileged{$udom}{$uname} = $trole;
! 2869: }
! 2870: }
! 2871: }
! 2872: }
! 2873: }
! 2874: if (exists($privileged{$domain}{$username})) {
! 2875: if (!$nothide{$username.':'.$domain}) {
! 2876: next;
! 2877: }
! 2878: }
1.937 raeburn 2879: }
2880: }
1.933 raeburn 2881: if ($withsec) {
2882: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2883: $tstart.':'.$tend;
2884: } else {
2885: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2886: }
1.832 raeburn 2887: }
1.373 www 2888: return %returnhash;
1.399 www 2889: }
2890:
2891: # ----------------------------------------------------- Frontpage Announcements
2892: #
2893: #
2894:
2895: sub postannounce {
2896: my ($server,$text)=@_;
1.844 albertel 2897: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2898: unless ($text=~/\w/) { $text=''; }
2899: return &reply('setannounce:'.&escape($text),$server);
2900: }
2901:
2902: sub getannounce {
1.448 albertel 2903:
2904: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2905: my $announcement='';
1.800 albertel 2906: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2907: close($fh);
1.399 www 2908: if ($announcement=~/\w/) {
2909: return
2910: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2911: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2912: } else {
2913: return '';
2914: }
2915: } else {
2916: return '';
2917: }
1.351 www 2918: }
1.353 www 2919:
2920: # ---------------------------------------------------------- Course ID routines
2921: # Deal with domain's nohist_courseid.db files
2922: #
2923:
2924: sub courseidput {
1.921 raeburn 2925: my ($domain,$storehash,$coursehome,$caller) = @_;
2926: my $outcome;
2927: if ($caller eq 'timeonly') {
2928: my $cids = '';
2929: foreach my $item (keys(%$storehash)) {
2930: $cids.=&escape($item).'&';
2931: }
2932: $cids=~s/\&$//;
2933: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2934: $coursehome);
2935: } else {
2936: my $items = '';
2937: foreach my $item (keys(%$storehash)) {
2938: $items.= &escape($item).'='.
2939: &freeze_escape($$storehash{$item}).'&';
2940: }
2941: $items=~s/\&$//;
2942: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2943: $coursehome);
1.918 raeburn 2944: }
2945: if ($outcome eq 'unknown_cmd') {
2946: my $what;
2947: foreach my $cid (keys(%$storehash)) {
2948: $what .= &escape($cid).'=';
1.921 raeburn 2949: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2950: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2951: }
2952: $what =~ s/\:$/&/;
2953: }
2954: $what =~ s/\&$//;
2955: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2956: } else {
2957: return $outcome;
2958: }
1.353 www 2959: }
2960:
2961: sub courseiddump {
1.921 raeburn 2962: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2963: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 raeburn 2964: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2965: my $as_hash = 1;
2966: my %returnhash;
2967: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2968: my %libserv = &all_library();
2969: foreach my $tryserver (keys(%libserv)) {
2970: if ( ( $hostidflag == 1
2971: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2972: || (!defined($hostidflag)) ) {
2973:
1.918 raeburn 2974: if (($domfilter eq '') ||
2975: (&host_domain($tryserver) eq $domfilter)) {
2976: my $rep =
2977: &reply('courseiddump:'.&host_domain($tryserver).':'.
2978: $sincefilter.':'.&escape($descfilter).':'.
2979: &escape($instcodefilter).':'.&escape($ownerfilter).
2980: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2981: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2982: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2983: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2984: my @pairs=split(/\&/,$rep);
2985: foreach my $item (@pairs) {
2986: my ($key,$value)=split(/\=/,$item,2);
2987: $key = &unescape($key);
2988: next if ($key =~ /^error: 2 /);
2989: my $result = &thaw_unescape($value);
2990: if (ref($result) eq 'HASH') {
2991: $returnhash{$key}=$result;
2992: } else {
1.921 raeburn 2993: my @responses = split(/:/,$value);
2994: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2995: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2996: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2997: }
2998: }
1.353 www 2999: }
3000: }
3001: }
3002: }
3003: return %returnhash;
3004: }
3005:
1.658 raeburn 3006: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3007:
3008: sub dcmailput {
1.685 raeburn 3009: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3010: my $status = &Apache::lonnet::critical(
1.740 www 3011: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3012: &escape($message),$server);
1.662 raeburn 3013: return $status;
3014: }
3015:
1.658 raeburn 3016: sub dcmaildump {
3017: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3018: my %returnhash=();
1.846 albertel 3019:
3020: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3021: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3022: &escape($enddate).':';
3023: my @esc_senders=map { &escape($_)} @$senders;
3024: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3025: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3026: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3027: if (($key) && ($value)) {
3028: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3029: }
3030: }
3031: }
3032: return %returnhash;
3033: }
1.662 raeburn 3034: # ---------------------------------------------------------- Domain roles
3035:
3036: sub get_domain_roles {
3037: my ($dom,$roles,$startdate,$enddate)=@_;
3038: if (undef($startdate) || $startdate eq '') {
3039: $startdate = '.';
3040: }
3041: if (undef($enddate) || $enddate eq '') {
3042: $enddate = '.';
3043: }
1.922 raeburn 3044: my $rolelist;
3045: if (ref($roles) eq 'ARRAY') {
3046: $rolelist = join(':',@{$roles});
3047: }
1.662 raeburn 3048: my %personnel = ();
1.841 albertel 3049:
3050: my %servers = &get_servers($dom,'library');
3051: foreach my $tryserver (keys(%servers)) {
3052: %{$personnel{$tryserver}}=();
3053: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3054: &escape($startdate).':'.
3055: &escape($enddate).':'.
3056: &escape($rolelist), $tryserver))) {
3057: my ($key,$value) = split(/\=/,$line,2);
3058: if (($key) && ($value)) {
3059: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3060: }
3061: }
1.662 raeburn 3062: }
3063: return %personnel;
3064: }
1.658 raeburn 3065:
1.149 www 3066: # ----------------------------------------------------------- Check out an item
3067:
1.504 albertel 3068: sub get_first_access {
3069: my ($type,$argsymb)=@_;
1.790 albertel 3070: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3071: if ($argsymb) { $symb=$argsymb; }
3072: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3073: if ($type eq 'course') {
3074: $res='course';
3075: } elsif ($type eq 'map') {
1.588 albertel 3076: $res=&symbread($map);
3077: } else {
3078: $res=$symb;
3079: }
3080: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3081: return $times{"$courseid\0$res"};
1.504 albertel 3082: }
3083:
3084: sub set_first_access {
3085: my ($type)=@_;
1.790 albertel 3086: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3087: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3088: if ($type eq 'course') {
3089: $res='course';
3090: } elsif ($type eq 'map') {
1.588 albertel 3091: $res=&symbread($map);
3092: } else {
3093: $res=$symb;
3094: }
3095: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3096: if (!$firstaccess) {
1.588 albertel 3097: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3098: }
3099: return 'already_set';
1.504 albertel 3100: }
3101:
1.149 www 3102: sub checkout {
3103: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3104: my $now=time;
3105: my $lonhost=$perlvar{'lonHostID'};
3106: my $infostr=&escape(
1.234 www 3107: 'CHECKOUTTOKEN&'.
1.149 www 3108: $tuname.'&'.
3109: $tudom.'&'.
3110: $tcrsid.'&'.
3111: $symb.'&'.
3112: $now.'&'.$ENV{'REMOTE_ADDR'});
3113: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3114: if ($token=~/^error\:/) {
1.672 albertel 3115: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3116: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3117: "</font>");
3118: return '';
3119: }
3120:
1.149 www 3121: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3122: $token=~tr/a-z/A-Z/;
3123:
1.153 www 3124: my %infohash=('resource.0.outtoken' => $token,
3125: 'resource.0.checkouttime' => $now,
3126: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3127:
3128: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3129: return '';
1.151 www 3130: } else {
1.672 albertel 3131: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3132: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3133: "</font>");
1.149 www 3134: }
3135:
3136: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3137: &escape('Checkout '.$infostr.' - '.
3138: $token)) ne 'ok') {
3139: return '';
1.151 www 3140: } else {
1.672 albertel 3141: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3142: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3143: "</font>");
1.149 www 3144: }
1.151 www 3145: return $token;
1.149 www 3146: }
3147:
3148: # ------------------------------------------------------------ Check in an item
3149:
3150: sub checkin {
3151: my $token=shift;
1.150 www 3152: my $now=time;
3153: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3154: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3155: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3156: $dtoken=~s/\W/\_/g;
1.234 www 3157: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3158: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3159:
1.154 www 3160: unless (($tuname) && ($tudom)) {
3161: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3162: return '';
3163: }
3164:
3165: unless (&allowed('mgr',$tcrsid)) {
3166: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3167: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3168: return '';
3169: }
3170:
1.153 www 3171: my %infohash=('resource.0.intoken' => $token,
3172: 'resource.0.checkintime' => $now,
3173: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3174:
3175: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3176: return '';
3177: }
3178:
3179: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3180: &escape('Checkin - '.$token)) ne 'ok') {
3181: return '';
3182: }
3183:
3184: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3185: }
3186:
3187: # --------------------------------------------- Set Expire Date for Spreadsheet
3188:
3189: sub expirespread {
3190: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3191: my $cid=$env{'request.course.id'};
1.110 www 3192: if ($cid) {
3193: my $now=time;
3194: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3195: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3196: $env{'course.'.$cid.'.num'}.
1.110 www 3197: ':nohist_expirationdates:'.
3198: &escape($key).'='.$now,
1.620 albertel 3199: $env{'course.'.$cid.'.home'})
1.110 www 3200: }
3201: return 'ok';
1.14 www 3202: }
3203:
1.109 www 3204: # ----------------------------------------------------- Devalidate Spreadsheets
3205:
3206: sub devalidate {
1.325 www 3207: my ($symb,$uname,$udom)=@_;
1.620 albertel 3208: my $cid=$env{'request.course.id'};
1.109 www 3209: if ($cid) {
1.391 matthew 3210: # delete the stored spreadsheets for
3211: # - the student level sheet of this user in course's homespace
3212: # - the assessment level sheet for this resource
3213: # for this user in user's homespace
1.553 albertel 3214: # - current conditional state info
1.325 www 3215: my $key=$uname.':'.$udom.':';
1.109 www 3216: my $status=
1.299 matthew 3217: &del('nohist_calculatedsheets',
1.391 matthew 3218: [$key.'studentcalc:'],
1.620 albertel 3219: $env{'course.'.$cid.'.domain'},
3220: $env{'course.'.$cid.'.num'})
1.133 albertel 3221: .' '.
3222: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3223: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3224: unless ($status eq 'ok ok') {
3225: &logthis('Could not devalidate spreadsheet '.
1.325 www 3226: $uname.' at '.$udom.' for '.
1.109 www 3227: $symb.': '.$status);
1.133 albertel 3228: }
1.553 albertel 3229: &delenv('user.state.'.$cid);
1.109 www 3230: }
3231: }
3232:
1.265 albertel 3233: sub get_scalar {
3234: my ($string,$end) = @_;
3235: my $value;
3236: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3237: $value = $1;
3238: } elsif ($$string =~ s/^([^&]*?)&//) {
3239: $value = $1;
3240: }
3241: return &unescape($value);
3242: }
3243:
3244: sub array2str {
3245: my (@array) = @_;
3246: my $result=&arrayref2str(\@array);
3247: $result=~s/^__ARRAY_REF__//;
3248: $result=~s/__END_ARRAY_REF__$//;
3249: return $result;
3250: }
3251:
1.204 albertel 3252: sub arrayref2str {
3253: my ($arrayref) = @_;
1.265 albertel 3254: my $result='__ARRAY_REF__';
1.204 albertel 3255: foreach my $elem (@$arrayref) {
1.265 albertel 3256: if(ref($elem) eq 'ARRAY') {
3257: $result.=&arrayref2str($elem).'&';
3258: } elsif(ref($elem) eq 'HASH') {
3259: $result.=&hashref2str($elem).'&';
3260: } elsif(ref($elem)) {
3261: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3262: } else {
3263: $result.=&escape($elem).'&';
3264: }
3265: }
3266: $result=~s/\&$//;
1.265 albertel 3267: $result .= '__END_ARRAY_REF__';
1.204 albertel 3268: return $result;
3269: }
3270:
1.168 albertel 3271: sub hash2str {
1.204 albertel 3272: my (%hash) = @_;
3273: my $result=&hashref2str(\%hash);
1.265 albertel 3274: $result=~s/^__HASH_REF__//;
3275: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3276: return $result;
3277: }
3278:
3279: sub hashref2str {
3280: my ($hashref)=@_;
1.265 albertel 3281: my $result='__HASH_REF__';
1.800 albertel 3282: foreach my $key (sort(keys(%$hashref))) {
3283: if (ref($key) eq 'ARRAY') {
3284: $result.=&arrayref2str($key).'=';
3285: } elsif (ref($key) eq 'HASH') {
3286: $result.=&hashref2str($key).'=';
3287: } elsif (ref($key)) {
1.265 albertel 3288: $result.='=';
1.800 albertel 3289: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3290: } else {
1.800 albertel 3291: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3292: }
3293:
1.800 albertel 3294: if(ref($hashref->{$key}) eq 'ARRAY') {
3295: $result.=&arrayref2str($hashref->{$key}).'&';
3296: } elsif(ref($hashref->{$key}) eq 'HASH') {
3297: $result.=&hashref2str($hashref->{$key}).'&';
3298: } elsif(ref($hashref->{$key})) {
1.265 albertel 3299: $result.='&';
1.800 albertel 3300: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3301: } else {
1.800 albertel 3302: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3303: }
3304: }
1.168 albertel 3305: $result=~s/\&$//;
1.265 albertel 3306: $result .= '__END_HASH_REF__';
1.168 albertel 3307: return $result;
3308: }
3309:
3310: sub str2hash {
1.265 albertel 3311: my ($string)=@_;
3312: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3313: return %$hash;
3314: }
3315:
3316: sub str2hashref {
1.168 albertel 3317: my ($string) = @_;
1.265 albertel 3318:
3319: my %hash;
3320:
3321: if($string !~ /^__HASH_REF__/) {
3322: if (! ($string eq '' || !defined($string))) {
3323: $hash{'error'}='Not hash reference';
3324: }
3325: return (\%hash, $string);
3326: }
3327:
3328: $string =~ s/^__HASH_REF__//;
3329:
3330: while($string !~ /^__END_HASH_REF__/) {
3331: #key
3332: my $key='';
3333: if($string =~ /^__HASH_REF__/) {
3334: ($key, $string)=&str2hashref($string);
3335: if(defined($key->{'error'})) {
3336: $hash{'error'}='Bad data';
3337: return (\%hash, $string);
3338: }
3339: } elsif($string =~ /^__ARRAY_REF__/) {
3340: ($key, $string)=&str2arrayref($string);
3341: if($key->[0] eq 'Array reference error') {
3342: $hash{'error'}='Bad data';
3343: return (\%hash, $string);
3344: }
3345: } else {
3346: $string =~ s/^(.*?)=//;
1.267 albertel 3347: $key=&unescape($1);
1.265 albertel 3348: }
3349: $string =~ s/^=//;
3350:
3351: #value
3352: my $value='';
3353: if($string =~ /^__HASH_REF__/) {
3354: ($value, $string)=&str2hashref($string);
3355: if(defined($value->{'error'})) {
3356: $hash{'error'}='Bad data';
3357: return (\%hash, $string);
3358: }
3359: } elsif($string =~ /^__ARRAY_REF__/) {
3360: ($value, $string)=&str2arrayref($string);
3361: if($value->[0] eq 'Array reference error') {
3362: $hash{'error'}='Bad data';
3363: return (\%hash, $string);
3364: }
3365: } else {
3366: $value=&get_scalar(\$string,'__END_HASH_REF__');
3367: }
3368: $string =~ s/^&//;
3369:
3370: $hash{$key}=$value;
1.204 albertel 3371: }
1.265 albertel 3372:
3373: $string =~ s/^__END_HASH_REF__//;
3374:
3375: return (\%hash, $string);
1.204 albertel 3376: }
3377:
3378: sub str2array {
1.265 albertel 3379: my ($string)=@_;
3380: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3381: return @$array;
3382: }
3383:
3384: sub str2arrayref {
1.204 albertel 3385: my ($string) = @_;
1.265 albertel 3386: my @array;
3387:
3388: if($string !~ /^__ARRAY_REF__/) {
3389: if (! ($string eq '' || !defined($string))) {
3390: $array[0]='Array reference error';
3391: }
3392: return (\@array, $string);
3393: }
3394:
3395: $string =~ s/^__ARRAY_REF__//;
3396:
3397: while($string !~ /^__END_ARRAY_REF__/) {
3398: my $value='';
3399: if($string =~ /^__HASH_REF__/) {
3400: ($value, $string)=&str2hashref($string);
3401: if(defined($value->{'error'})) {
3402: $array[0] ='Array reference error';
3403: return (\@array, $string);
3404: }
3405: } elsif($string =~ /^__ARRAY_REF__/) {
3406: ($value, $string)=&str2arrayref($string);
3407: if($value->[0] eq 'Array reference error') {
3408: $array[0] ='Array reference error';
3409: return (\@array, $string);
3410: }
3411: } else {
3412: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3413: }
3414: $string =~ s/^&//;
3415:
3416: push(@array, $value);
1.191 harris41 3417: }
1.265 albertel 3418:
3419: $string =~ s/^__END_ARRAY_REF__//;
3420:
3421: return (\@array, $string);
1.168 albertel 3422: }
3423:
1.167 albertel 3424: # -------------------------------------------------------------------Temp Store
3425:
1.168 albertel 3426: sub tmpreset {
3427: my ($symb,$namespace,$domain,$stuname) = @_;
3428: if (!$symb) {
3429: $symb=&symbread();
1.620 albertel 3430: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3431: }
3432: $symb=escape($symb);
3433:
1.620 albertel 3434: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3435: $namespace=~s/\//\_/g;
3436: $namespace=~s/\W//g;
3437:
1.620 albertel 3438: if (!$domain) { $domain=$env{'user.domain'}; }
3439: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3440: if ($domain eq 'public' && $stuname eq 'public') {
3441: $stuname=$ENV{'REMOTE_ADDR'};
3442: }
1.168 albertel 3443: my $path=$perlvar{'lonDaemons'}.'/tmp';
3444: my %hash;
3445: if (tie(%hash,'GDBM_File',
3446: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3447: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3448: foreach my $key (keys %hash) {
1.180 albertel 3449: if ($key=~ /:$symb/) {
1.168 albertel 3450: delete($hash{$key});
3451: }
3452: }
3453: }
3454: }
3455:
1.167 albertel 3456: sub tmpstore {
1.168 albertel 3457: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3458:
3459: if (!$symb) {
3460: $symb=&symbread();
1.620 albertel 3461: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3462: }
3463: $symb=escape($symb);
3464:
3465: if (!$namespace) {
3466: # I don't think we would ever want to store this for a course.
3467: # it seems this will only be used if we don't have a course.
1.620 albertel 3468: #$namespace=$env{'request.course.id'};
1.168 albertel 3469: #if (!$namespace) {
1.620 albertel 3470: $namespace=$env{'request.state'};
1.168 albertel 3471: #}
3472: }
3473: $namespace=~s/\//\_/g;
3474: $namespace=~s/\W//g;
1.620 albertel 3475: if (!$domain) { $domain=$env{'user.domain'}; }
3476: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3477: if ($domain eq 'public' && $stuname eq 'public') {
3478: $stuname=$ENV{'REMOTE_ADDR'};
3479: }
1.168 albertel 3480: my $now=time;
3481: my %hash;
3482: my $path=$perlvar{'lonDaemons'}.'/tmp';
3483: if (tie(%hash,'GDBM_File',
3484: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3485: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3486: $hash{"version:$symb"}++;
3487: my $version=$hash{"version:$symb"};
3488: my $allkeys='';
3489: foreach my $key (keys(%$storehash)) {
3490: $allkeys.=$key.':';
1.591 albertel 3491: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3492: }
3493: $hash{"$version:$symb:timestamp"}=$now;
3494: $allkeys.='timestamp';
3495: $hash{"$version:keys:$symb"}=$allkeys;
3496: if (untie(%hash)) {
3497: return 'ok';
3498: } else {
3499: return "error:$!";
3500: }
3501: } else {
3502: return "error:$!";
3503: }
3504: }
1.167 albertel 3505:
1.168 albertel 3506: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3507:
1.168 albertel 3508: sub tmprestore {
3509: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3510:
1.168 albertel 3511: if (!$symb) {
3512: $symb=&symbread();
1.620 albertel 3513: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3514: }
3515: $symb=escape($symb);
3516:
1.620 albertel 3517: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3518:
1.620 albertel 3519: if (!$domain) { $domain=$env{'user.domain'}; }
3520: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3521: if ($domain eq 'public' && $stuname eq 'public') {
3522: $stuname=$ENV{'REMOTE_ADDR'};
3523: }
1.168 albertel 3524: my %returnhash;
3525: $namespace=~s/\//\_/g;
3526: $namespace=~s/\W//g;
3527: my %hash;
3528: my $path=$perlvar{'lonDaemons'}.'/tmp';
3529: if (tie(%hash,'GDBM_File',
3530: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3531: &GDBM_READER(),0640)) {
1.168 albertel 3532: my $version=$hash{"version:$symb"};
3533: $returnhash{'version'}=$version;
3534: my $scope;
3535: for ($scope=1;$scope<=$version;$scope++) {
3536: my $vkeys=$hash{"$scope:keys:$symb"};
3537: my @keys=split(/:/,$vkeys);
3538: my $key;
3539: $returnhash{"$scope:keys"}=$vkeys;
3540: foreach $key (@keys) {
1.591 albertel 3541: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3542: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3543: }
3544: }
1.168 albertel 3545: if (!(untie(%hash))) {
3546: return "error:$!";
3547: }
3548: } else {
3549: return "error:$!";
3550: }
3551: return %returnhash;
1.167 albertel 3552: }
3553:
1.9 www 3554: # ----------------------------------------------------------------------- Store
3555:
3556: sub store {
1.124 www 3557: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3558: my $home='';
3559:
1.168 albertel 3560: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3561:
1.213 www 3562: $symb=&symbclean($symb);
1.122 albertel 3563: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3564:
1.620 albertel 3565: if (!$domain) { $domain=$env{'user.domain'}; }
3566: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3567:
3568: &devalidate($symb,$stuname,$domain);
1.109 www 3569:
3570: $symb=escape($symb);
1.187 www 3571: if (!$namespace) {
1.620 albertel 3572: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3573: return '';
3574: }
3575: }
1.620 albertel 3576: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3577:
3578: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3579: $$storehash{'host'}=$perlvar{'lonHostID'};
3580:
1.12 www 3581: my $namevalue='';
1.800 albertel 3582: foreach my $key (keys(%$storehash)) {
3583: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3584: }
1.12 www 3585: $namevalue=~s/\&$//;
1.187 www 3586: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3587: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3588: }
3589:
1.47 www 3590: # -------------------------------------------------------------- Critical Store
3591:
3592: sub cstore {
1.124 www 3593: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3594: my $home='';
3595:
1.168 albertel 3596: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3597:
1.213 www 3598: $symb=&symbclean($symb);
1.122 albertel 3599: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3600:
1.620 albertel 3601: if (!$domain) { $domain=$env{'user.domain'}; }
3602: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3603:
3604: &devalidate($symb,$stuname,$domain);
1.109 www 3605:
3606: $symb=escape($symb);
1.187 www 3607: if (!$namespace) {
1.620 albertel 3608: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3609: return '';
3610: }
3611: }
1.620 albertel 3612: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3613:
3614: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3615: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3616:
1.47 www 3617: my $namevalue='';
1.800 albertel 3618: foreach my $key (keys(%$storehash)) {
3619: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3620: }
1.47 www 3621: $namevalue=~s/\&$//;
1.187 www 3622: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3623: return critical
3624: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3625: }
3626:
1.9 www 3627: # --------------------------------------------------------------------- Restore
3628:
3629: sub restore {
1.124 www 3630: my ($symb,$namespace,$domain,$stuname) = @_;
3631: my $home='';
3632:
1.168 albertel 3633: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3634:
1.122 albertel 3635: if (!$symb) {
3636: unless ($symb=escape(&symbread())) { return ''; }
3637: } else {
1.213 www 3638: $symb=&escape(&symbclean($symb));
1.122 albertel 3639: }
1.188 www 3640: if (!$namespace) {
1.620 albertel 3641: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3642: return '';
3643: }
3644: }
1.620 albertel 3645: if (!$domain) { $domain=$env{'user.domain'}; }
3646: if (!$stuname) { $stuname=$env{'user.name'}; }
3647: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3648: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3649:
1.12 www 3650: my %returnhash=();
1.800 albertel 3651: foreach my $line (split(/\&/,$answer)) {
3652: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3653: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3654: }
1.75 www 3655: my $version;
3656: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3657: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3658: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3659: }
1.75 www 3660: }
1.13 www 3661: return %returnhash;
1.34 www 3662: }
3663:
3664: # ---------------------------------------------------------- Course Description
3665:
3666: sub coursedescription {
1.731 albertel 3667: my ($courseid,$args)=@_;
1.34 www 3668: $courseid=~s/^\///;
1.49 www 3669: $courseid=~s/\_/\//g;
1.34 www 3670: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3671: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3672: my $normalid=$cdomain.'_'.$cnum;
3673: # need to always cache even if we get errors otherwise we keep
3674: # trying and trying and trying to get the course description.
3675: my %envhash=();
3676: my %returnhash=();
1.731 albertel 3677:
3678: my $expiretime=600;
3679: if ($env{'request.course.id'} eq $normalid) {
3680: $expiretime=120;
3681: }
3682:
3683: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3684: if (!$args->{'freshen_cache'}
3685: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3686: foreach my $key (keys(%env)) {
3687: next if ($key !~ /^\Q$prefix\E(.*)/);
3688: my ($setting) = $1;
3689: $returnhash{$setting} = $env{$key};
3690: }
3691: return %returnhash;
3692: }
3693:
3694: # get the data agin
3695: if (!$args->{'one_time'}) {
3696: $envhash{'course.'.$normalid.'.last_cache'}=time;
3697: }
1.811 albertel 3698:
1.34 www 3699: if ($chome ne 'no_host') {
1.302 albertel 3700: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3701: if (!exists($returnhash{'con_lost'})) {
3702: $returnhash{'home'}= $chome;
3703: $returnhash{'domain'} = $cdomain;
3704: $returnhash{'num'} = $cnum;
1.741 raeburn 3705: if (!defined($returnhash{'type'})) {
3706: $returnhash{'type'} = 'Course';
3707: }
1.130 albertel 3708: while (my ($name,$value) = each %returnhash) {
1.53 www 3709: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3710: }
1.270 www 3711: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3712: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3713: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3714: $envhash{'course.'.$normalid.'.home'}=$chome;
3715: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3716: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3717: }
3718: }
1.731 albertel 3719: if (!$args->{'one_time'}) {
1.949 raeburn 3720: &appenv(\%envhash);
1.731 albertel 3721: }
1.302 albertel 3722: return %returnhash;
1.461 www 3723: }
3724:
3725: # -------------------------------------------------See if a user is privileged
3726:
3727: sub privileged {
3728: my ($username,$domain)=@_;
3729: my $rolesdump=&reply("dump:$domain:$username:roles",
3730: &homeserver($username,$domain));
3731: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3732: my $now=time;
3733: if ($rolesdump ne '') {
1.800 albertel 3734: foreach my $entry (split(/&/,$rolesdump)) {
3735: if ($entry!~/^rolesdef_/) {
3736: my ($area,$role)=split(/=/,$entry);
1.461 www 3737: $area=~s/\_\w\w$//;
3738: my ($trole,$tend,$tstart)=split(/_/,$role);
3739: if (($trole eq 'dc') || ($trole eq 'su')) {
3740: my $active=1;
3741: if ($tend) {
3742: if ($tend<$now) { $active=0; }
3743: }
3744: if ($tstart) {
3745: if ($tstart>$now) { $active=0; }
3746: }
3747: if ($active) { return 1; }
3748: }
3749: }
3750: }
3751: }
3752: return 0;
1.9 www 3753: }
1.1 albertel 3754:
1.103 harris41 3755: # -------------------------------------------------------- Get user privileges
1.11 www 3756:
3757: sub rolesinit {
3758: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3759: my %userroles;
1.11 www 3760: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3761: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3762: my %allroles=();
1.678 raeburn 3763: my %allgroups=();
1.11 www 3764: my $now=time;
1.966 raeburn 3765: %userroles = ('user.login.time' => $now);
1.678 raeburn 3766: my $group_privs;
1.11 www 3767:
3768: if ($rolesdump ne '') {
1.800 albertel 3769: foreach my $entry (split(/&/,$rolesdump)) {
3770: if ($entry!~/^rolesdef_/) {
3771: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3772: $area=~s/\_\w\w$//;
1.678 raeburn 3773: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3774: if ($role=~/^cr/) {
1.807 albertel 3775: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3776: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3777: ($tend,$tstart)=split('_',$trest);
3778: } else {
3779: $trole=$role;
3780: }
1.678 raeburn 3781: } elsif ($role =~ m|^gr/|) {
3782: ($trole,$tend,$tstart) = split(/_/,$role);
3783: ($trole,$group_privs) = split(/\//,$trole);
3784: $group_privs = &unescape($group_privs);
1.587 albertel 3785: } else {
3786: ($trole,$tend,$tstart)=split(/_/,$role);
3787: }
1.743 albertel 3788: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3789: $username);
3790: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3791: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3792: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3793: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3794: my $spec=$trole.'.'.$area;
3795: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3796: if ($trole =~ /^cr\//) {
1.567 raeburn 3797: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3798: } elsif ($trole eq 'gr') {
3799: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3800: } else {
1.567 raeburn 3801: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3802: }
1.12 www 3803: }
1.662 raeburn 3804: }
1.191 harris41 3805: }
1.743 albertel 3806: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3807: $userroles{'user.adv'} = $adv;
3808: $userroles{'user.author'} = $author;
1.620 albertel 3809: $env{'user.adv'}=$adv;
1.11 www 3810: }
1.743 albertel 3811: return \%userroles;
1.11 www 3812: }
3813:
1.567 raeburn 3814: sub set_arearole {
3815: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3816: # log the associated role with the area
3817: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3818: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3819: }
3820:
3821: sub custom_roleprivs {
3822: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3823: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3824: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3825: if (&hostname($homsvr) ne '') {
1.567 raeburn 3826: my ($rdummy,$roledef)=
3827: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3828: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3829: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3830: if (defined($syspriv)) {
3831: $$allroles{'cm./'}.=':'.$syspriv;
3832: $$allroles{$spec.'./'}.=':'.$syspriv;
3833: }
3834: if ($tdomain ne '') {
3835: if (defined($dompriv)) {
3836: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3837: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3838: }
3839: if (($trest ne '') && (defined($coursepriv))) {
3840: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3841: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3842: }
3843: }
3844: }
3845: }
3846: }
3847:
1.678 raeburn 3848: sub group_roleprivs {
3849: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3850: my $access = 1;
3851: my $now = time;
3852: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3853: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3854: if ($access) {
1.811 albertel 3855: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3856: $$allgroups{$course}{$group} .=':'.$group_privs;
3857: }
3858: }
1.567 raeburn 3859:
3860: sub standard_roleprivs {
3861: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3862: if (defined($pr{$trole.':s'})) {
3863: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3864: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3865: }
3866: if ($tdomain ne '') {
3867: if (defined($pr{$trole.':d'})) {
3868: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3869: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3870: }
3871: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3872: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3873: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3874: }
3875: }
3876: }
3877:
3878: sub set_userprivs {
1.678 raeburn 3879: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3880: my $author=0;
3881: my $adv=0;
1.678 raeburn 3882: my %grouproles = ();
3883: if (keys(%{$allgroups}) > 0) {
3884: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3885: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3886: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3887: $trole = $1;
3888: $area = $2;
1.681 raeburn 3889: $sec = $3;
3890: $extendedarea = $area.$sec;
3891: if (exists($$allgroups{$area})) {
3892: foreach my $group (keys(%{$$allgroups{$area}})) {
3893: my $spec = $trole.'.'.$extendedarea;
3894: $grouproles{$spec.'.'.$area.'/'.$group} =
3895: $$allgroups{$area}{$group};
1.678 raeburn 3896: }
3897: }
3898: }
3899: }
3900: }
1.800 albertel 3901: foreach my $group (keys(%grouproles)) {
3902: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3903: }
1.800 albertel 3904: foreach my $role (keys(%{$allroles})) {
3905: my %thesepriv;
1.941 raeburn 3906: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3907: foreach my $item (split(/:/,$$allroles{$role})) {
3908: if ($item ne '') {
3909: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3910: if ($restrictions eq '') {
3911: $thesepriv{$privilege}='F';
3912: } elsif ($thesepriv{$privilege} ne 'F') {
3913: $thesepriv{$privilege}.=$restrictions;
3914: }
3915: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3916: }
3917: }
3918: my $thesestr='';
1.800 albertel 3919: foreach my $priv (keys(%thesepriv)) {
3920: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3921: }
3922: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3923: }
3924: return ($author,$adv);
3925: }
3926:
1.994 raeburn 3927: sub role_status {
3928: my ($rolekey,$then,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
3929: my @pwhere = ();
3930: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
3931: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
3932: unless (!defined($$role) || $$role eq '') {
3933: $$where=join('.',@pwhere);
3934: $$trolecode=$$role.'.'.$$where;
3935: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
3936: $$tstatus='is';
3937: if ($$tstart && $$tstart>$then) {
3938: $$tstatus='future';
3939: if ($$tstart<$now) { $$tstatus='will'; }
3940: }
3941: if ($$tend) {
3942: if ($$tend<$then) {
3943: $$tstatus='expired';
3944: } elsif ($$tend<$now) {
3945: $$tstatus='will_not';
3946: }
3947: }
3948: }
3949: }
3950: }
3951:
3952: sub check_adhoc_privs {
3953: my ($cdom,$cnum,$then,$now,$checkrole) = @_;
3954: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
3955: if ($env{$cckey}) {
3956: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
3957: &role_status($cckey,$then,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
3958: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
3959: &set_adhoc_privileges($cdom,$cnum,$checkrole);
3960: }
3961: } else {
3962: &set_adhoc_privileges($cdom,$cnum,$checkrole);
3963: }
3964: }
3965:
3966: sub set_adhoc_privileges {
3967: # role can be cc or ca
3968: my ($dcdom,$pickedcourse,$role) = @_;
3969: my $area = '/'.$dcdom.'/'.$pickedcourse;
3970: my $spec = $role.'.'.$area;
3971: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
3972: $env{'user.name'});
3973: my %ccrole = ();
3974: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
3975: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
3976: &appenv(\%userroles,[$role,'cm']);
3977: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
3978: &appenv( {'request.role' => $spec,
3979: 'request.role.domain' => $dcdom,
3980: 'request.course.sec' => ''
3981: }
3982: );
3983: my $tadv=0;
3984: if (&allowed('adv') eq 'F') { $tadv=1; }
3985: &appenv({'request.role.adv' => $tadv});
3986: }
3987:
1.12 www 3988: # --------------------------------------------------------------- get interface
3989:
3990: sub get {
1.131 albertel 3991: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3992: my $items='';
1.800 albertel 3993: foreach my $item (@$storearr) {
3994: $items.=&escape($item).'&';
1.191 harris41 3995: }
1.12 www 3996: $items=~s/\&$//;
1.620 albertel 3997: if (!$udomain) { $udomain=$env{'user.domain'}; }
3998: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3999: my $uhome=&homeserver($uname,$udomain);
4000:
1.133 albertel 4001: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4002: my @pairs=split(/\&/,$rep);
1.273 albertel 4003: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4004: return @pairs;
4005: }
1.15 www 4006: my %returnhash=();
1.42 www 4007: my $i=0;
1.800 albertel 4008: foreach my $item (@$storearr) {
4009: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4010: $i++;
1.191 harris41 4011: }
1.15 www 4012: return %returnhash;
1.27 www 4013: }
4014:
4015: # --------------------------------------------------------------- del interface
4016:
4017: sub del {
1.133 albertel 4018: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4019: my $items='';
1.800 albertel 4020: foreach my $item (@$storearr) {
4021: $items.=&escape($item).'&';
1.191 harris41 4022: }
1.984 neumanie 4023:
1.27 www 4024: $items=~s/\&$//;
1.620 albertel 4025: if (!$udomain) { $udomain=$env{'user.domain'}; }
4026: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4027: my $uhome=&homeserver($uname,$udomain);
4028: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4029: }
4030:
4031: # -------------------------------------------------------------- dump interface
4032:
4033: sub dump {
1.755 albertel 4034: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4035: if (!$udomain) { $udomain=$env{'user.domain'}; }
4036: if (!$uname) { $uname=$env{'user.name'}; }
4037: my $uhome=&homeserver($uname,$udomain);
4038: if ($regexp) {
4039: $regexp=&escape($regexp);
4040: } else {
4041: $regexp='.';
4042: }
4043: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4044: my @pairs=split(/\&/,$rep);
4045: my %returnhash=();
4046: foreach my $item (@pairs) {
4047: my ($key,$value)=split(/=/,$item,2);
4048: $key = &unescape($key);
4049: next if ($key =~ /^error: 2 /);
4050: $returnhash{$key}=&thaw_unescape($value);
4051: }
4052: return %returnhash;
1.407 www 4053: }
4054:
1.717 albertel 4055: # --------------------------------------------------------- dumpstore interface
4056:
4057: sub dumpstore {
4058: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4059: if (!$udomain) { $udomain=$env{'user.domain'}; }
4060: if (!$uname) { $uname=$env{'user.name'}; }
4061: my $uhome=&homeserver($uname,$udomain);
4062: if ($regexp) {
4063: $regexp=&escape($regexp);
4064: } else {
4065: $regexp='.';
4066: }
4067: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4068: my @pairs=split(/\&/,$rep);
4069: my %returnhash=();
4070: foreach my $item (@pairs) {
4071: my ($key,$value)=split(/=/,$item,2);
4072: next if ($key =~ /^error: 2 /);
4073: $returnhash{$key}=&thaw_unescape($value);
4074: }
4075: return %returnhash;
1.717 albertel 4076: }
4077:
1.407 www 4078: # -------------------------------------------------------------- keys interface
4079:
4080: sub getkeys {
4081: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4082: if (!$udomain) { $udomain=$env{'user.domain'}; }
4083: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4084: my $uhome=&homeserver($uname,$udomain);
4085: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4086: my @keyarray=();
1.800 albertel 4087: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4088: next if ($key =~ /^error: 2 /);
1.800 albertel 4089: push(@keyarray,&unescape($key));
1.407 www 4090: }
4091: return @keyarray;
1.318 matthew 4092: }
4093:
1.319 matthew 4094: # --------------------------------------------------------------- currentdump
4095: sub currentdump {
1.328 matthew 4096: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4097: $courseid = $env{'request.course.id'} if (! defined($courseid));
4098: $sdom = $env{'user.domain'} if (! defined($sdom));
4099: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4100: my $uhome = &homeserver($sname,$sdom);
4101: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4102: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4103: #
1.318 matthew 4104: my %returnhash=();
1.319 matthew 4105: #
4106: if ($rep eq "unknown_cmd") {
4107: # an old lond will not know currentdump
4108: # Do a dump and make it look like a currentdump
1.822 albertel 4109: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4110: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4111: my %hash = @tmp;
4112: @tmp=();
1.424 matthew 4113: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4114: } else {
4115: my @pairs=split(/\&/,$rep);
1.800 albertel 4116: foreach my $pair (@pairs) {
4117: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4118: my ($symb,$param) = split(/:/,$key);
4119: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4120: &thaw_unescape($value);
1.319 matthew 4121: }
1.191 harris41 4122: }
1.12 www 4123: return %returnhash;
1.424 matthew 4124: }
4125:
4126: sub convert_dump_to_currentdump{
4127: my %hash = %{shift()};
4128: my %returnhash;
4129: # Code ripped from lond, essentially. The only difference
4130: # here is the unescaping done by lonnet::dump(). Conceivably
4131: # we might run in to problems with parameter names =~ /^v\./
4132: while (my ($key,$value) = each(%hash)) {
4133: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4134: $symb = &unescape($symb);
4135: $param = &unescape($param);
1.424 matthew 4136: next if ($v eq 'version' || $symb eq 'keys');
4137: next if (exists($returnhash{$symb}) &&
4138: exists($returnhash{$symb}->{$param}) &&
4139: $returnhash{$symb}->{'v.'.$param} > $v);
4140: $returnhash{$symb}->{$param}=$value;
4141: $returnhash{$symb}->{'v.'.$param}=$v;
4142: }
4143: #
4144: # Remove all of the keys in the hashes which keep track of
4145: # the version of the parameter.
4146: while (my ($symb,$param_hash) = each(%returnhash)) {
4147: # use a foreach because we are going to delete from the hash.
4148: foreach my $key (keys(%$param_hash)) {
4149: delete($param_hash->{$key}) if ($key =~ /^v\./);
4150: }
4151: }
4152: return \%returnhash;
1.12 www 4153: }
4154:
1.627 albertel 4155: # ------------------------------------------------------ critical inc interface
4156:
4157: sub cinc {
4158: return &inc(@_,'critical');
4159: }
4160:
1.449 matthew 4161: # --------------------------------------------------------------- inc interface
4162:
4163: sub inc {
1.627 albertel 4164: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4165: if (!$udomain) { $udomain=$env{'user.domain'}; }
4166: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4167: my $uhome=&homeserver($uname,$udomain);
4168: my $items='';
4169: if (! ref($store)) {
4170: # got a single value, so use that instead
4171: $items = &escape($store).'=&';
4172: } elsif (ref($store) eq 'SCALAR') {
4173: $items = &escape($$store).'=&';
4174: } elsif (ref($store) eq 'ARRAY') {
4175: $items = join('=&',map {&escape($_);} @{$store});
4176: } elsif (ref($store) eq 'HASH') {
4177: while (my($key,$value) = each(%{$store})) {
4178: $items.= &escape($key).'='.&escape($value).'&';
4179: }
4180: }
4181: $items=~s/\&$//;
1.627 albertel 4182: if ($critical) {
4183: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4184: } else {
4185: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4186: }
1.449 matthew 4187: }
4188:
1.12 www 4189: # --------------------------------------------------------------- put interface
4190:
4191: sub put {
1.134 albertel 4192: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4193: if (!$udomain) { $udomain=$env{'user.domain'}; }
4194: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4195: my $uhome=&homeserver($uname,$udomain);
1.12 www 4196: my $items='';
1.800 albertel 4197: foreach my $item (keys(%$storehash)) {
4198: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4199: }
1.12 www 4200: $items=~s/\&$//;
1.134 albertel 4201: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4202: }
4203:
1.631 albertel 4204: # ------------------------------------------------------------ newput interface
4205:
4206: sub newput {
4207: my ($namespace,$storehash,$udomain,$uname)=@_;
4208: if (!$udomain) { $udomain=$env{'user.domain'}; }
4209: if (!$uname) { $uname=$env{'user.name'}; }
4210: my $uhome=&homeserver($uname,$udomain);
4211: my $items='';
4212: foreach my $key (keys(%$storehash)) {
4213: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4214: }
4215: $items=~s/\&$//;
4216: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4217: }
4218:
4219: # --------------------------------------------------------- putstore interface
4220:
1.524 raeburn 4221: sub putstore {
1.715 albertel 4222: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4223: if (!$udomain) { $udomain=$env{'user.domain'}; }
4224: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4225: my $uhome=&homeserver($uname,$udomain);
4226: my $items='';
1.715 albertel 4227: foreach my $key (keys(%$storehash)) {
4228: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4229: }
1.715 albertel 4230: $items=~s/\&$//;
1.716 albertel 4231: my $esc_symb=&escape($symb);
4232: my $esc_v=&escape($version);
1.715 albertel 4233: my $reply =
1.716 albertel 4234: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4235: $uhome);
4236: if ($reply eq 'unknown_cmd') {
1.716 albertel 4237: # gfall back to way things use to be done
1.715 albertel 4238: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4239: $uname);
1.524 raeburn 4240: }
1.715 albertel 4241: return $reply;
4242: }
4243:
4244: sub old_putstore {
1.716 albertel 4245: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4246: if (!$udomain) { $udomain=$env{'user.domain'}; }
4247: if (!$uname) { $uname=$env{'user.name'}; }
4248: my $uhome=&homeserver($uname,$udomain);
4249: my %newstorehash;
1.800 albertel 4250: foreach my $item (keys(%$storehash)) {
4251: my $key = $version.':'.&escape($symb).':'.$item;
4252: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4253: }
4254: my $items='';
4255: my %allitems = ();
1.800 albertel 4256: foreach my $item (keys(%newstorehash)) {
4257: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4258: my $key = $1.':keys:'.$2;
4259: $allitems{$key} .= $3.':';
4260: }
1.800 albertel 4261: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4262: }
1.800 albertel 4263: foreach my $item (keys(%allitems)) {
4264: $allitems{$item} =~ s/\:$//;
4265: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4266: }
4267: $items=~s/\&$//;
4268: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4269: }
4270:
1.47 www 4271: # ------------------------------------------------------ critical put interface
4272:
4273: sub cput {
1.134 albertel 4274: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4275: if (!$udomain) { $udomain=$env{'user.domain'}; }
4276: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4277: my $uhome=&homeserver($uname,$udomain);
1.47 www 4278: my $items='';
1.800 albertel 4279: foreach my $item (keys(%$storehash)) {
4280: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4281: }
1.47 www 4282: $items=~s/\&$//;
1.134 albertel 4283: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4284: }
4285:
4286: # -------------------------------------------------------------- eget interface
4287:
4288: sub eget {
1.133 albertel 4289: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4290: my $items='';
1.800 albertel 4291: foreach my $item (@$storearr) {
4292: $items.=&escape($item).'&';
1.191 harris41 4293: }
1.12 www 4294: $items=~s/\&$//;
1.620 albertel 4295: if (!$udomain) { $udomain=$env{'user.domain'}; }
4296: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4297: my $uhome=&homeserver($uname,$udomain);
4298: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4299: my @pairs=split(/\&/,$rep);
4300: my %returnhash=();
1.42 www 4301: my $i=0;
1.800 albertel 4302: foreach my $item (@$storearr) {
4303: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4304: $i++;
1.191 harris41 4305: }
1.12 www 4306: return %returnhash;
4307: }
4308:
1.667 albertel 4309: # ------------------------------------------------------------ tmpput interface
4310: sub tmpput {
1.802 raeburn 4311: my ($storehash,$server,$context)=@_;
1.667 albertel 4312: my $items='';
1.800 albertel 4313: foreach my $item (keys(%$storehash)) {
4314: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4315: }
4316: $items=~s/\&$//;
1.802 raeburn 4317: if (defined($context)) {
4318: $items .= ':'.&escape($context);
4319: }
1.667 albertel 4320: return &reply("tmpput:$items",$server);
4321: }
4322:
4323: # ------------------------------------------------------------ tmpget interface
4324: sub tmpget {
1.688 albertel 4325: my ($token,$server)=@_;
4326: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4327: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4328: my %returnhash;
4329: foreach my $item (split(/\&/,$rep)) {
4330: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4331: next if ($key =~ /^error: 2 /);
1.667 albertel 4332: $returnhash{&unescape($key)}=&thaw_unescape($value);
4333: }
4334: return %returnhash;
4335: }
4336:
1.688 albertel 4337: # ------------------------------------------------------------ tmpget interface
4338: sub tmpdel {
4339: my ($token,$server)=@_;
4340: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4341: return &reply("tmpdel:$token",$server);
4342: }
4343:
1.765 albertel 4344: # -------------------------------------------------- portfolio access checking
4345:
4346: sub portfolio_access {
1.766 albertel 4347: my ($requrl) = @_;
1.765 albertel 4348: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4349: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4350: if ($result) {
4351: my %setters;
4352: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4353: my ($startblock,$endblock) =
4354: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4355: if ($startblock && $endblock) {
4356: return 'B';
4357: }
4358: } else {
4359: my ($startblock,$endblock) =
4360: &Apache::loncommon::blockcheck(\%setters,'port');
4361: if ($startblock && $endblock) {
4362: return 'B';
4363: }
4364: }
4365: }
1.765 albertel 4366: if ($result eq 'ok') {
1.766 albertel 4367: return 'F';
1.765 albertel 4368: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4369: return 'A';
1.765 albertel 4370: }
1.766 albertel 4371: return '';
1.765 albertel 4372: }
4373:
4374: sub get_portfolio_access {
1.767 albertel 4375: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4376:
4377: if (!ref($access_hash)) {
4378: my $current_perms = &get_portfile_permissions($udom,$unum);
4379: my %access_controls = &get_access_controls($current_perms,$group,
4380: $file_name);
4381: $access_hash = $access_controls{$file_name};
4382: }
4383:
1.765 albertel 4384: my ($public,$guest,@domains,@users,@courses,@groups);
4385: my $now = time;
4386: if (ref($access_hash) eq 'HASH') {
4387: foreach my $key (keys(%{$access_hash})) {
4388: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4389: if ($start > $now) {
4390: next;
4391: }
4392: if ($end && $end<$now) {
4393: next;
4394: }
4395: if ($scope eq 'public') {
4396: $public = $key;
4397: last;
4398: } elsif ($scope eq 'guest') {
4399: $guest = $key;
4400: } elsif ($scope eq 'domains') {
4401: push(@domains,$key);
4402: } elsif ($scope eq 'users') {
4403: push(@users,$key);
4404: } elsif ($scope eq 'course') {
4405: push(@courses,$key);
4406: } elsif ($scope eq 'group') {
4407: push(@groups,$key);
4408: }
4409: }
4410: if ($public) {
4411: return 'ok';
4412: }
4413: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4414: if ($guest) {
4415: return $guest;
4416: }
4417: } else {
4418: if (@domains > 0) {
4419: foreach my $domkey (@domains) {
4420: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4421: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4422: return 'ok';
4423: }
4424: }
4425: }
4426: }
4427: if (@users > 0) {
4428: foreach my $userkey (@users) {
1.865 raeburn 4429: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4430: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4431: if (ref($item) eq 'HASH') {
4432: if (($item->{'uname'} eq $env{'user.name'}) &&
4433: ($item->{'udom'} eq $env{'user.domain'})) {
4434: return 'ok';
4435: }
4436: }
4437: }
4438: }
1.765 albertel 4439: }
4440: }
4441: my %roleshash;
4442: my @courses_and_groups = @courses;
4443: push(@courses_and_groups,@groups);
4444: if (@courses_and_groups > 0) {
4445: my (%allgroups,%allroles);
4446: my ($start,$end,$role,$sec,$group);
4447: foreach my $envkey (%env) {
1.811 albertel 4448: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4449: my $cid = $2.'_'.$3;
4450: if ($1 eq 'gr') {
4451: $group = $4;
4452: $allgroups{$cid}{$group} = $env{$envkey};
4453: } else {
4454: if ($4 eq '') {
4455: $sec = 'none';
4456: } else {
4457: $sec = $4;
4458: }
4459: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4460: }
1.811 albertel 4461: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4462: my $cid = $2.'_'.$3;
4463: if ($4 eq '') {
4464: $sec = 'none';
4465: } else {
4466: $sec = $4;
4467: }
4468: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4469: }
4470: }
4471: if (keys(%allroles) == 0) {
4472: return;
4473: }
4474: foreach my $key (@courses_and_groups) {
4475: my %content = %{$$access_hash{$key}};
4476: my $cnum = $content{'number'};
4477: my $cdom = $content{'domain'};
4478: my $cid = $cdom.'_'.$cnum;
4479: if (!exists($allroles{$cid})) {
4480: next;
4481: }
4482: foreach my $role_id (keys(%{$content{'roles'}})) {
4483: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4484: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4485: my @status = @{$content{'roles'}{$role_id}{'access'}};
4486: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4487: foreach my $role (keys(%{$allroles{$cid}})) {
4488: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4489: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4490: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4491: if (grep/^all$/,@sections) {
4492: return 'ok';
4493: } else {
4494: if (grep/^$sec$/,@sections) {
4495: return 'ok';
4496: }
4497: }
4498: }
4499: }
4500: if (keys(%{$allgroups{$cid}}) == 0) {
4501: if (grep/^none$/,@groups) {
4502: return 'ok';
4503: }
4504: } else {
4505: if (grep/^all$/,@groups) {
4506: return 'ok';
4507: }
4508: foreach my $group (keys(%{$allgroups{$cid}})) {
4509: if (grep/^$group$/,@groups) {
4510: return 'ok';
4511: }
4512: }
4513: }
4514: }
4515: }
4516: }
4517: }
4518: }
4519: if ($guest) {
4520: return $guest;
4521: }
4522: }
4523: }
4524: return;
4525: }
4526:
4527: sub course_group_datechecker {
4528: my ($dates,$now,$status) = @_;
4529: my ($start,$end) = split(/\./,$dates);
4530: if (!$start && !$end) {
4531: return 'ok';
4532: }
4533: if (grep/^active$/,@{$status}) {
4534: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4535: return 'ok';
4536: }
4537: }
4538: if (grep/^previous$/,@{$status}) {
4539: if ($end > $now ) {
4540: return 'ok';
4541: }
4542: }
4543: if (grep/^future$/,@{$status}) {
4544: if ($start > $now) {
4545: return 'ok';
4546: }
4547: }
4548: return;
4549: }
4550:
4551: sub parse_portfolio_url {
4552: my ($url) = @_;
4553:
4554: my ($type,$udom,$unum,$group,$file_name);
4555:
1.823 albertel 4556: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4557: $type = 1;
4558: $udom = $1;
4559: $unum = $2;
4560: $file_name = $3;
1.823 albertel 4561: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4562: $type = 2;
4563: $udom = $1;
4564: $unum = $2;
4565: $group = $3;
4566: $file_name = $3.'/'.$4;
4567: }
4568: if (wantarray) {
4569: return ($type,$udom,$unum,$file_name,$group);
4570: }
4571: return $type;
4572: }
4573:
4574: sub is_portfolio_url {
4575: my ($url) = @_;
4576: return scalar(&parse_portfolio_url($url));
4577: }
4578:
1.798 raeburn 4579: sub is_portfolio_file {
4580: my ($file) = @_;
1.820 raeburn 4581: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4582: return 1;
4583: }
4584: return;
4585: }
4586:
1.976 raeburn 4587: sub usertools_access {
1.985 raeburn 4588: my ($uname,$udom,$tool,$action,$context) = @_;
4589: my ($access,%tools);
4590: if ($context eq '') {
4591: $context = 'tools';
4592: }
4593: if ($context eq 'requestcourses') {
4594: %tools = (
4595: official => 1,
4596: unofficial => 1,
4597: );
4598: } else {
4599: %tools = (
4600: aboutme => 1,
4601: blog => 1,
4602: portfolio => 1,
4603: );
4604: }
1.976 raeburn 4605: return if (!defined($tools{$tool}));
4606:
4607: if ((!defined($udom)) || (!defined($uname))) {
4608: $udom = $env{'user.domain'};
4609: $uname = $env{'user.name'};
4610: }
4611:
1.978 raeburn 4612: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4613: if ($action ne 'reload') {
1.985 raeburn 4614: if ($context eq 'requestcourses') {
4615: return $env{'environment.canrequest.'.$tool};
4616: } else {
4617: return $env{'environment.availabletools.'.$tool};
4618: }
4619: }
1.976 raeburn 4620: }
4621:
4622: my ($toolstatus,$inststatus);
4623:
1.985 raeburn 4624: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4625: ($action ne 'reload')) {
4626: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4627: $inststatus = $env{'environment.inststatus'};
4628: } else {
1.985 raeburn 4629: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
4630: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4631: $inststatus = $userenv{'inststatus'};
4632: }
4633:
4634: if ($toolstatus ne '') {
4635: if ($toolstatus) {
4636: $access = 1;
4637: } else {
4638: $access = 0;
4639: }
4640: return $access;
4641: }
4642:
4643: my $is_adv = &is_advanced_user($udom,$uname);
4644: my %domdef = &get_domain_defaults($udom);
4645: if (ref($domdef{$tool}) eq 'HASH') {
4646: if ($is_adv) {
4647: if ($domdef{$tool}{'_LC_adv'} ne '') {
4648: if ($domdef{$tool}{'_LC_adv'}) {
4649: $access = 1;
4650: } else {
4651: $access = 0;
4652: }
4653: return $access;
4654: }
4655: }
4656: if ($inststatus ne '') {
4657: my ($hasaccess,$hasnoaccess);
4658: foreach my $affiliation (split(/:/,$inststatus)) {
4659: if ($domdef{$tool}{$affiliation} ne '') {
4660: if ($domdef{$tool}{$affiliation}) {
4661: $hasaccess = 1;
4662: } else {
4663: $hasnoaccess = 1;
4664: }
4665: }
4666: }
4667: if ($hasaccess || $hasnoaccess) {
4668: if ($hasaccess) {
4669: $access = 1;
4670: } elsif ($hasnoaccess) {
4671: $access = 0;
4672: }
4673: return $access;
4674: }
4675: } else {
4676: if ($domdef{$tool}{'default'} ne '') {
4677: if ($domdef{$tool}{'default'}) {
4678: $access = 1;
4679: } elsif ($domdef{$tool}{'default'} == 0) {
4680: $access = 0;
4681: }
4682: return $access;
4683: }
4684: }
4685: } else {
1.985 raeburn 4686: if ($context eq 'tools') {
4687: $access = 1;
4688: } else {
4689: $access = 0;
4690: }
1.976 raeburn 4691: return $access;
4692: }
4693: }
4694:
4695: sub is_advanced_user {
4696: my ($udom,$uname) = @_;
4697: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4698: my %allroles;
4699: my $is_adv;
4700: foreach my $role (keys(%roleshash)) {
4701: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4702: my $area = '/'.$tdomain.'/'.$trest;
4703: if ($sec ne '') {
4704: $area .= '/'.$sec;
4705: }
4706: if (($area ne '') && ($trole ne '')) {
4707: my $spec=$trole.'.'.$area;
4708: if ($trole =~ /^cr\//) {
4709: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4710: } elsif ($trole ne 'gr') {
4711: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4712: }
4713: }
4714: }
4715: foreach my $role (keys(%allroles)) {
4716: last if ($is_adv);
4717: foreach my $item (split(/:/,$allroles{$role})) {
4718: if ($item ne '') {
4719: my ($privilege,$restrictions)=split(/&/,$item);
4720: if ($privilege eq 'adv') {
4721: $is_adv = 1;
4722: last;
4723: }
4724: }
4725: }
4726: }
4727: return $is_adv;
4728: }
1.798 raeburn 4729:
1.341 www 4730: # ---------------------------------------------- Custom access rule evaluation
4731:
4732: sub customaccess {
4733: my ($priv,$uri)=@_;
1.807 albertel 4734: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4735: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4736: $udom = &LONCAPA::clean_domain($udom);
4737: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4738: my $access=0;
1.800 albertel 4739: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4740: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4741: if ($type eq 'user') {
4742: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4743: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4744: if ($tdom) {
4745: if ($tdom ne $env{'user.domain'}) { next; }
4746: }
1.896 albertel 4747: if ($tuname) {
4748: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4749: }
4750: $access=($effect eq 'allow');
4751: last;
4752: }
4753: } else {
4754: if ($role) {
4755: if ($role ne $urole) { next; }
4756: }
4757: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4758: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4759: if ($tdom) {
4760: if ($tdom ne $udom) { next; }
4761: }
4762: if ($tcrs) {
4763: if ($tcrs ne $ucrs) { next; }
4764: }
4765: if ($tsec) {
4766: if ($tsec ne $usec) { next; }
4767: }
4768: $access=($effect eq 'allow');
4769: last;
4770: }
4771: if ($realm eq '' && $role eq '') {
4772: $access=($effect eq 'allow');
4773: }
1.402 bowersj2 4774: }
1.341 www 4775: }
4776: return $access;
4777: }
4778:
1.103 harris41 4779: # ------------------------------------------------- Check for a user privilege
1.12 www 4780:
4781: sub allowed {
1.810 raeburn 4782: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4783: my $ver_orguri=$uri;
1.439 www 4784: $uri=&deversion($uri);
1.152 www 4785: my $orguri=$uri;
1.52 www 4786: $uri=&declutter($uri);
1.809 raeburn 4787:
1.810 raeburn 4788: if ($priv eq 'evb') {
4789: # Evade communication block restrictions for specified role in a course
4790: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4791: return $1;
4792: } else {
4793: return;
4794: }
4795: }
4796:
1.620 albertel 4797: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4798: # Free bre access to adm and meta resources
1.775 albertel 4799: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4800: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4801: && ($priv eq 'bre')) {
1.14 www 4802: return 'F';
1.159 www 4803: }
4804:
1.545 banghart 4805: # Free bre access to user's own portfolio contents
1.714 raeburn 4806: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4807: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4808: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4809: my %setters;
4810: my ($startblock,$endblock) =
4811: &Apache::loncommon::blockcheck(\%setters,'port');
4812: if ($startblock && $endblock) {
4813: return 'B';
4814: } else {
4815: return 'F';
4816: }
1.545 banghart 4817: }
4818:
1.762 raeburn 4819: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4820: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4821: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4822: if (exists($env{'request.course.id'})) {
4823: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4824: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4825: if (($domain eq $cdom) && ($name eq $cnum)) {
4826: my $courseprivid=$env{'request.course.id'};
4827: $courseprivid=~s/\_/\//;
4828: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4829: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4830: return $1;
1.762 raeburn 4831: } else {
4832: if ($env{'request.course.sec'}) {
4833: $courseprivid.='/'.$env{'request.course.sec'};
4834: }
4835: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4836: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4837: return $2;
4838: }
1.714 raeburn 4839: }
4840: }
4841: }
4842: }
4843:
1.159 www 4844: # Free bre to public access
4845:
4846: if ($priv eq 'bre') {
1.238 www 4847: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4848: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4849: return 'F';
4850: }
1.238 www 4851: if ($copyright eq 'priv') {
4852: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4853: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4854: return '';
4855: }
4856: }
4857: if ($copyright eq 'domain') {
4858: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4859: unless (($env{'user.domain'} eq $1) ||
4860: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4861: return '';
4862: }
1.262 matthew 4863: }
1.620 albertel 4864: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4865: # Library role, so allow browsing of resources in this domain.
4866: return 'F';
1.238 www 4867: }
1.341 www 4868: if ($copyright eq 'custom') {
4869: unless (&customaccess($priv,$uri)) { return ''; }
4870: }
1.14 www 4871: }
1.264 matthew 4872: # Domain coordinator is trying to create a course
1.620 albertel 4873: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4874: # uri is the requested domain in this case.
4875: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4876: # a role of dc for the domain in question.
1.620 albertel 4877: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4878: }
1.29 www 4879:
1.52 www 4880: my $thisallowed='';
4881: my $statecond=0;
4882: my $courseprivid='';
4883:
4884: # Course
4885:
1.620 albertel 4886: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4887: $thisallowed.=$1;
4888: }
1.29 www 4889:
1.52 www 4890: # Domain
4891:
1.620 albertel 4892: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4893: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4894: $thisallowed.=$1;
4895: }
1.52 www 4896:
4897: # Course: uri itself is a course
1.66 www 4898: my $courseuri=$uri;
4899: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4900: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4901:
1.620 albertel 4902: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4903: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4904: $thisallowed.=$1;
4905: }
1.29 www 4906:
1.665 albertel 4907: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4908: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4909: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4910: $thisallowed='';
1.671 raeburn 4911: my ($match)=&is_on_map($uri);
4912: if ($match) {
4913: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4914: =~/\Q$priv\E\&([^\:]*)/) {
4915: $thisallowed.=$1;
4916: }
4917: } else {
1.705 albertel 4918: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4919: if ($refuri) {
4920: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4921: $thisallowed='F';
1.671 raeburn 4922: } else {
4923: $refuri=&declutter($refuri);
4924: my ($match) = &is_on_map($refuri);
4925: if ($match) {
4926: $thisallowed='F';
4927: }
1.669 raeburn 4928: }
1.671 raeburn 4929: }
4930: }
1.314 www 4931: }
1.492 albertel 4932:
1.766 albertel 4933: if ($priv eq 'bre'
4934: && $thisallowed ne 'F'
4935: && $thisallowed ne '2'
4936: && &is_portfolio_url($uri)) {
4937: $thisallowed = &portfolio_access($uri);
4938: }
4939:
1.52 www 4940: # Full access at system, domain or course-wide level? Exit.
1.29 www 4941: if ($thisallowed=~/F/) {
4942: return 'F';
4943: }
4944:
1.52 www 4945: # If this is generating or modifying users, exit with special codes
1.29 www 4946:
1.643 www 4947: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4948: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4949: my ($audom,$auname)=split('/',$uri);
1.643 www 4950: # no author name given, so this just checks on the general right to make a co-author in this domain
4951: unless ($auname) { return $thisallowed; }
4952: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4953: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4954: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4955: ($audom ne $env{'request.role.domain'}))) { return ''; }
4956: }
1.52 www 4957: return $thisallowed;
4958: }
4959: #
1.103 harris41 4960: # Gathered so far: system, domain and course wide privileges
1.52 www 4961: #
4962: # Course: See if uri or referer is an individual resource that is part of
4963: # the course
4964:
1.620 albertel 4965: if ($env{'request.course.id'}) {
1.232 www 4966:
1.620 albertel 4967: $courseprivid=$env{'request.course.id'};
4968: if ($env{'request.course.sec'}) {
4969: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4970: }
4971: $courseprivid=~s/\_/\//;
4972: my $checkreferer=1;
1.232 www 4973: my ($match,$cond)=&is_on_map($uri);
4974: if ($match) {
4975: $statecond=$cond;
1.620 albertel 4976: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4977: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4978: $thisallowed.=$1;
4979: $checkreferer=0;
4980: }
1.29 www 4981: }
1.83 www 4982:
1.148 www 4983: if ($checkreferer) {
1.620 albertel 4984: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4985: unless ($refuri) {
1.800 albertel 4986: foreach my $key (keys(%env)) {
4987: if ($key=~/^httpref\..*\*/) {
4988: my $pattern=$key;
1.156 www 4989: $pattern=~s/^httpref\.\/res\///;
1.148 www 4990: $pattern=~s/\*/\[\^\/\]\+/g;
4991: $pattern=~s/\//\\\//g;
1.152 www 4992: if ($orguri=~/$pattern/) {
1.800 albertel 4993: $refuri=$env{$key};
1.148 www 4994: }
4995: }
1.191 harris41 4996: }
1.148 www 4997: }
1.232 www 4998:
1.148 www 4999: if ($refuri) {
1.152 www 5000: $refuri=&declutter($refuri);
1.232 www 5001: my ($match,$cond)=&is_on_map($refuri);
5002: if ($match) {
5003: my $refstatecond=$cond;
1.620 albertel 5004: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5005: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5006: $thisallowed.=$1;
1.53 www 5007: $uri=$refuri;
5008: $statecond=$refstatecond;
1.52 www 5009: }
5010: }
1.148 www 5011: }
1.29 www 5012: }
1.52 www 5013: }
1.29 www 5014:
1.52 www 5015: #
1.103 harris41 5016: # Gathered now: all privileges that could apply, and condition number
1.52 www 5017: #
5018: #
5019: # Full or no access?
5020: #
1.29 www 5021:
1.52 www 5022: if ($thisallowed=~/F/) {
5023: return 'F';
5024: }
1.29 www 5025:
1.52 www 5026: unless ($thisallowed) {
5027: return '';
5028: }
1.29 www 5029:
1.52 www 5030: # Restrictions exist, deal with them
5031: #
5032: # C:according to course preferences
5033: # R:according to resource settings
5034: # L:unless locked
5035: # X:according to user session state
5036: #
5037:
5038: # Possibly locked functionality, check all courses
1.54 www 5039: # Locks might take effect only after 10 minutes cache expiration for other
5040: # courses, and 2 minutes for current course
1.52 www 5041:
5042: my $envkey;
5043: if ($thisallowed=~/L/) {
1.620 albertel 5044: foreach $envkey (keys %env) {
1.54 www 5045: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5046: my $courseid=$2;
5047: my $roleid=$1.'.'.$2;
1.92 www 5048: $courseid=~s/^\///;
1.54 www 5049: my $expiretime=600;
1.620 albertel 5050: if ($env{'request.role'} eq $roleid) {
1.54 www 5051: $expiretime=120;
5052: }
5053: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5054: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5055: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5056: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5057: }
1.620 albertel 5058: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5059: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5060: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5061: &log($env{'user.domain'},$env{'user.name'},
5062: $env{'user.home'},
1.57 www 5063: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5064: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5065: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5066: return '';
5067: }
5068: }
1.620 albertel 5069: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5070: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5071: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5072: &log($env{'user.domain'},$env{'user.name'},
5073: $env{'user.home'},
1.57 www 5074: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5075: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5076: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5077: return '';
5078: }
5079: }
5080: }
1.29 www 5081: }
1.52 www 5082: }
5083:
5084: #
5085: # Rest of the restrictions depend on selected course
5086: #
5087:
1.620 albertel 5088: unless ($env{'request.course.id'}) {
1.766 albertel 5089: if ($thisallowed eq 'A') {
5090: return 'A';
1.814 raeburn 5091: } elsif ($thisallowed eq 'B') {
5092: return 'B';
1.766 albertel 5093: } else {
5094: return '1';
5095: }
1.52 www 5096: }
1.29 www 5097:
1.52 www 5098: #
5099: # Now user is definitely in a course
5100: #
1.53 www 5101:
5102:
5103: # Course preferences
5104:
5105: if ($thisallowed=~/C/) {
1.620 albertel 5106: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5107: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5108: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5109: =~/\Q$rolecode\E/) {
1.689 albertel 5110: if ($priv ne 'pch') {
5111: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5112: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5113: $env{'request.course.id'});
5114: }
1.237 www 5115: return '';
5116: }
5117:
1.620 albertel 5118: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5119: =~/\Q$unamedom\E/) {
1.689 albertel 5120: if ($priv ne 'pch') {
5121: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5122: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5123: $env{'request.course.id'});
5124: }
1.54 www 5125: return '';
5126: }
1.53 www 5127: }
5128:
5129: # Resource preferences
5130:
5131: if ($thisallowed=~/R/) {
1.620 albertel 5132: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5133: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5134: if ($priv ne 'pch') {
5135: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5136: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5137: }
5138: return '';
1.54 www 5139: }
1.53 www 5140: }
1.30 www 5141:
1.246 www 5142: # Restricted by state or randomout?
1.30 www 5143:
1.52 www 5144: if ($thisallowed=~/X/) {
1.620 albertel 5145: if ($env{'acc.randomout'}) {
1.579 albertel 5146: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5147: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5148: return '';
5149: }
1.247 www 5150: }
5151: if (&condval($statecond)) {
1.52 www 5152: return '2';
5153: } else {
5154: return '';
5155: }
5156: }
1.30 www 5157:
1.766 albertel 5158: if ($thisallowed eq 'A') {
5159: return 'A';
1.814 raeburn 5160: } elsif ($thisallowed eq 'B') {
5161: return 'B';
1.766 albertel 5162: }
1.52 www 5163: return 'F';
1.232 www 5164: }
5165:
1.710 albertel 5166: sub split_uri_for_cond {
5167: my $uri=&deversion(&declutter(shift));
5168: my @uriparts=split(/\//,$uri);
5169: my $filename=pop(@uriparts);
5170: my $pathname=join('/',@uriparts);
5171: return ($pathname,$filename);
5172: }
1.232 www 5173: # --------------------------------------------------- Is a resource on the map?
5174:
5175: sub is_on_map {
1.710 albertel 5176: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5177: #Trying to find the conditional for the file
1.620 albertel 5178: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5179: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5180: if ($match) {
1.289 bowersj2 5181: return (1,$1);
5182: } else {
1.434 www 5183: return (0,0);
1.289 bowersj2 5184: }
1.12 www 5185: }
5186:
1.427 www 5187: # --------------------------------------------------------- Get symb from alias
5188:
5189: sub get_symb_from_alias {
5190: my $symb=shift;
5191: my ($map,$resid,$url)=&decode_symb($symb);
5192: # Already is a symb
5193: if ($url) { return $symb; }
5194: # Must be an alias
5195: my $aliassymb='';
5196: my %bighash;
1.620 albertel 5197: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5198: &GDBM_READER(),0640)) {
5199: my $rid=$bighash{'mapalias_'.$symb};
5200: if ($rid) {
5201: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5202: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5203: $resid,$bighash{'src_'.$rid});
1.427 www 5204: }
5205: untie %bighash;
5206: }
5207: return $aliassymb;
5208: }
5209:
1.12 www 5210: # ----------------------------------------------------------------- Define Role
5211:
5212: sub definerole {
5213: if (allowed('mcr','/')) {
5214: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5215: foreach my $role (split(':',$sysrole)) {
5216: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5217: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5218: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5219: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5220: return "refused:s:$crole&$cqual";
5221: }
5222: }
1.191 harris41 5223: }
1.800 albertel 5224: foreach my $role (split(':',$domrole)) {
5225: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5226: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5227: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5228: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5229: return "refused:d:$crole&$cqual";
5230: }
5231: }
1.191 harris41 5232: }
1.800 albertel 5233: foreach my $role (split(':',$courole)) {
5234: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5235: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5236: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5237: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5238: return "refused:c:$crole&$cqual";
5239: }
5240: }
1.191 harris41 5241: }
1.620 albertel 5242: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5243: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5244: "rolesdef_$rolename=".
5245: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5246: return reply($command,$env{'user.home'});
1.12 www 5247: } else {
5248: return 'refused';
5249: }
1.105 harris41 5250: }
5251:
5252: # ---------------- Make a metadata query against the network of library servers
5253:
5254: sub metadata_query {
1.244 matthew 5255: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5256: my %rhash;
1.845 albertel 5257: my %libserv = &all_library();
1.244 matthew 5258: my @server_list = (defined($server_array) ? @$server_array
5259: : keys(%libserv) );
5260: for my $server (@server_list) {
1.118 harris41 5261: unless ($custom or $customshow) {
5262: my $reply=&reply("querysend:".&escape($query),$server);
5263: $rhash{$server}=$reply;
5264: }
5265: else {
5266: my $reply=&reply("querysend:".&escape($query).':'.
5267: &escape($custom).':'.&escape($customshow),
5268: $server);
5269: $rhash{$server}=$reply;
5270: }
1.112 harris41 5271: }
1.118 harris41 5272: return \%rhash;
1.240 www 5273: }
5274:
5275: # ----------------------------------------- Send log queries and wait for reply
5276:
5277: sub log_query {
5278: my ($uname,$udom,$query,%filters)=@_;
5279: my $uhome=&homeserver($uname,$udom);
5280: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5281: my $uhost=&hostname($uhome);
1.800 albertel 5282: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5283: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5284: $uhome);
1.479 albertel 5285: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5286: return get_query_reply($queryid);
5287: }
5288:
1.818 raeburn 5289: # -------------------------- Update MySQL table for portfolio file
5290:
5291: sub update_portfolio_table {
1.821 raeburn 5292: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5293: if ($group ne '') {
5294: $file_name =~s /^\Q$group\E//;
5295: }
1.818 raeburn 5296: my $homeserver = &homeserver($uname,$udom);
5297: my $queryid=
1.821 raeburn 5298: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5299: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5300: my $reply = &get_query_reply($queryid);
5301: return $reply;
5302: }
5303:
1.899 raeburn 5304: # -------------------------- Update MySQL allusers table
5305:
5306: sub update_allusers_table {
5307: my ($uname,$udom,$names) = @_;
5308: my $homeserver = &homeserver($uname,$udom);
5309: my $queryid=
5310: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5311: 'lastname='.&escape($names->{'lastname'}).'%%'.
5312: 'firstname='.&escape($names->{'firstname'}).'%%'.
5313: 'middlename='.&escape($names->{'middlename'}).'%%'.
5314: 'generation='.&escape($names->{'generation'}).'%%'.
5315: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5316: 'id='.&escape($names->{'id'}),$homeserver);
5317: my $reply = &get_query_reply($queryid);
5318: return $reply;
5319: }
5320:
1.508 raeburn 5321: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5322:
5323: sub fetch_enrollment_query {
1.511 raeburn 5324: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5325: my $homeserver;
1.547 raeburn 5326: my $maxtries = 1;
1.508 raeburn 5327: if ($context eq 'automated') {
5328: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5329: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5330: } else {
5331: $homeserver = &homeserver($cnum,$dom);
5332: }
1.838 albertel 5333: my $host=&hostname($homeserver);
1.506 raeburn 5334: my $cmd = '';
1.800 albertel 5335: foreach my $affiliate (keys %{$affiliatesref}) {
5336: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5337: }
5338: $cmd =~ s/%%$//;
5339: $cmd = &escape($cmd);
5340: my $query = 'fetchenrollment';
1.620 albertel 5341: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5342: unless ($queryid=~/^\Q$host\E\_/) {
5343: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5344: return 'error: '.$queryid;
5345: }
1.506 raeburn 5346: my $reply = &get_query_reply($queryid);
1.547 raeburn 5347: my $tries = 1;
5348: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5349: $reply = &get_query_reply($queryid);
5350: $tries ++;
5351: }
1.526 raeburn 5352: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5353: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5354: } else {
1.901 albertel 5355: my @responses = split(/:/,$reply);
1.515 raeburn 5356: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5357: foreach my $line (@responses) {
5358: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5359: $$replyref{$key} = $value;
5360: }
5361: } else {
1.506 raeburn 5362: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5363: foreach my $line (@responses) {
5364: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5365: $$replyref{$key} = $value;
5366: if ($value > 0) {
1.800 albertel 5367: foreach my $item (@{$$affiliatesref{$key}}) {
5368: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5369: my $destname = $pathname.'/'.$filename;
5370: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5371: if ($xml_classlist =~ /^error/) {
5372: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5373: } else {
1.506 raeburn 5374: if ( open(FILE,">$destname") ) {
5375: print FILE &unescape($xml_classlist);
5376: close(FILE);
1.526 raeburn 5377: } else {
5378: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5379: }
5380: }
5381: }
5382: }
5383: }
5384: }
5385: return 'ok';
5386: }
5387: return 'error';
5388: }
5389:
1.242 www 5390: sub get_query_reply {
5391: my $queryid=shift;
1.240 www 5392: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5393: my $reply='';
5394: for (1..100) {
5395: sleep 2;
5396: if (-e $replyfile.'.end') {
1.448 albertel 5397: if (open(my $fh,$replyfile)) {
1.904 albertel 5398: $reply = join('',<$fh>);
5399: close($fh);
1.240 www 5400: } else { return 'error: reply_file_error'; }
1.242 www 5401: return &unescape($reply);
5402: }
1.240 www 5403: }
1.242 www 5404: return 'timeout:'.$queryid;
1.240 www 5405: }
5406:
5407: sub courselog_query {
1.241 www 5408: #
5409: # possible filters:
5410: # url: url or symb
5411: # username
5412: # domain
5413: # action: view, submit, grade
5414: # start: timestamp
5415: # end: timestamp
5416: #
1.240 www 5417: my (%filters)=@_;
1.620 albertel 5418: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5419: if ($filters{'url'}) {
5420: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5421: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5422: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5423: }
1.620 albertel 5424: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5425: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5426: return &log_query($cname,$cdom,'courselog',%filters);
5427: }
5428:
5429: sub userlog_query {
1.858 raeburn 5430: #
5431: # possible filters:
5432: # action: log check role
5433: # start: timestamp
5434: # end: timestamp
5435: #
1.240 www 5436: my ($uname,$udom,%filters)=@_;
5437: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5438: }
5439:
1.506 raeburn 5440: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5441:
5442: sub auto_run {
1.508 raeburn 5443: my ($cnum,$cdom) = @_;
1.876 raeburn 5444: my $response = 0;
5445: my $settings;
5446: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5447: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5448: $settings = $domconfig{'autoenroll'};
5449: if ($settings->{'run'} eq '1') {
5450: $response = 1;
5451: }
5452: } else {
1.934 raeburn 5453: my $homeserver;
5454: if (&is_course($cdom,$cnum)) {
5455: $homeserver = &homeserver($cnum,$cdom);
5456: } else {
5457: $homeserver = &domain($cdom,'primary');
5458: }
5459: if ($homeserver ne 'no_host') {
5460: $response = &reply('autorun:'.$cdom,$homeserver);
5461: }
1.876 raeburn 5462: }
1.506 raeburn 5463: return $response;
5464: }
1.776 albertel 5465:
1.506 raeburn 5466: sub auto_get_sections {
1.508 raeburn 5467: my ($cnum,$cdom,$inst_coursecode) = @_;
5468: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5469: my @secs = ();
1.511 raeburn 5470: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5471: unless ($response eq 'refused') {
1.901 albertel 5472: @secs = split(/:/,$response);
1.506 raeburn 5473: }
5474: return @secs;
5475: }
1.776 albertel 5476:
1.506 raeburn 5477: sub auto_new_course {
1.508 raeburn 5478: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5479: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5480: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5481: return $response;
5482: }
1.776 albertel 5483:
1.506 raeburn 5484: sub auto_validate_courseID {
1.508 raeburn 5485: my ($cnum,$cdom,$inst_course_id) = @_;
5486: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5487: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5488: return $response;
5489: }
1.776 albertel 5490:
1.506 raeburn 5491: sub auto_create_password {
1.873 raeburn 5492: my ($cnum,$cdom,$authparam,$udom) = @_;
5493: my ($homeserver,$response);
1.506 raeburn 5494: my $create_passwd = 0;
5495: my $authchk = '';
1.873 raeburn 5496: if ($udom =~ /^$match_domain$/) {
5497: $homeserver = &domain($udom,'primary');
5498: }
5499: if ($homeserver eq '') {
5500: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5501: $homeserver = &homeserver($cnum,$cdom);
5502: }
5503: }
5504: if ($homeserver eq '') {
5505: $authchk = 'nodomain';
1.506 raeburn 5506: } else {
1.873 raeburn 5507: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5508: if ($response eq 'refused') {
5509: $authchk = 'refused';
5510: } else {
1.901 albertel 5511: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5512: }
1.506 raeburn 5513: }
5514: return ($authparam,$create_passwd,$authchk);
5515: }
5516:
1.706 raeburn 5517: sub auto_photo_permission {
5518: my ($cnum,$cdom,$students) = @_;
5519: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5520: my ($outcome,$perm_reqd,$conditions) =
5521: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5522: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5523: return (undef,undef);
5524: }
1.706 raeburn 5525: return ($outcome,$perm_reqd,$conditions);
5526: }
5527:
5528: sub auto_checkphotos {
5529: my ($uname,$udom,$pid) = @_;
5530: my $homeserver = &homeserver($uname,$udom);
5531: my ($result,$resulttype);
5532: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5533: &escape($uname).':'.&escape($pid),
5534: $homeserver));
1.709 albertel 5535: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5536: return (undef,undef);
5537: }
1.706 raeburn 5538: if ($outcome) {
5539: ($result,$resulttype) = split(/:/,$outcome);
5540: }
5541: return ($result,$resulttype);
5542: }
5543:
5544: sub auto_photochoice {
5545: my ($cnum,$cdom) = @_;
5546: my $homeserver = &homeserver($cnum,$cdom);
5547: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5548: &escape($cdom),
5549: $homeserver)));
1.709 albertel 5550: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5551: return (undef,undef);
5552: }
1.706 raeburn 5553: return ($update,$comment);
5554: }
5555:
5556: sub auto_photoupdate {
5557: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5558: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5559: my $host=&hostname($homeserver);
1.706 raeburn 5560: my $cmd = '';
5561: my $maxtries = 1;
1.800 albertel 5562: foreach my $affiliate (keys(%{$affiliatesref})) {
5563: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5564: }
5565: $cmd =~ s/%%$//;
5566: $cmd = &escape($cmd);
5567: my $query = 'institutionalphotos';
5568: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5569: unless ($queryid=~/^\Q$host\E\_/) {
5570: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5571: return 'error: '.$queryid;
5572: }
5573: my $reply = &get_query_reply($queryid);
5574: my $tries = 1;
5575: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5576: $reply = &get_query_reply($queryid);
5577: $tries ++;
5578: }
5579: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5580: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5581: } else {
5582: my @responses = split(/:/,$reply);
5583: my $outcome = shift(@responses);
5584: foreach my $item (@responses) {
5585: my ($key,$value) = split(/=/,$item);
5586: $$photo{$key} = $value;
5587: }
5588: return $outcome;
5589: }
5590: return 'error';
5591: }
5592:
1.521 raeburn 5593: sub auto_instcode_format {
1.793 albertel 5594: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5595: $cat_order) = @_;
1.521 raeburn 5596: my $courses = '';
1.772 raeburn 5597: my @homeservers;
1.521 raeburn 5598: if ($caller eq 'global') {
1.841 albertel 5599: my %servers = &get_servers($codedom,'library');
5600: foreach my $tryserver (keys(%servers)) {
5601: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5602: push(@homeservers,$tryserver);
5603: }
1.584 raeburn 5604: }
1.521 raeburn 5605: } else {
1.772 raeburn 5606: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5607: }
1.793 albertel 5608: foreach my $code (keys(%{$instcodes})) {
5609: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5610: }
5611: chop($courses);
1.772 raeburn 5612: my $ok_response = 0;
5613: my $response;
5614: while (@homeservers > 0 && $ok_response == 0) {
5615: my $server = shift(@homeservers);
5616: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5617: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5618: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5619: split(/:/,$response);
1.772 raeburn 5620: %{$codes} = (%{$codes},&str2hash($codes_str));
5621: push(@{$codetitles},&str2array($codetitles_str));
5622: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5623: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5624: $ok_response = 1;
5625: }
5626: }
5627: if ($ok_response) {
1.521 raeburn 5628: return 'ok';
1.772 raeburn 5629: } else {
5630: return $response;
1.521 raeburn 5631: }
5632: }
5633:
1.792 raeburn 5634: sub auto_instcode_defaults {
5635: my ($domain,$returnhash,$code_order) = @_;
5636: my @homeservers;
1.841 albertel 5637:
5638: my %servers = &get_servers($domain,'library');
5639: foreach my $tryserver (keys(%servers)) {
5640: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5641: push(@homeservers,$tryserver);
5642: }
1.792 raeburn 5643: }
1.841 albertel 5644:
1.792 raeburn 5645: my $response;
1.841 albertel 5646: foreach my $server (@homeservers) {
1.792 raeburn 5647: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5648: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5649:
5650: foreach my $pair (split(/\&/,$response)) {
5651: my ($name,$value)=split(/\=/,$pair);
5652: if ($name eq 'code_order') {
5653: @{$code_order} = split(/\&/,&unescape($value));
5654: } else {
5655: $returnhash->{&unescape($name)}=&unescape($value);
5656: }
5657: }
5658: return 'ok';
1.792 raeburn 5659: }
1.841 albertel 5660:
5661: return $response;
1.792 raeburn 5662: }
5663:
1.777 albertel 5664: sub auto_validate_class_sec {
1.918 raeburn 5665: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5666: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5667: my $ownerlist;
5668: if (ref($owners) eq 'ARRAY') {
5669: $ownerlist = join(',',@{$owners});
5670: } else {
5671: $ownerlist = $owners;
5672: }
1.773 raeburn 5673: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5674: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5675: return $response;
5676: }
5677:
1.679 raeburn 5678: # ------------------------------------------------------- Course Group routines
5679:
5680: sub get_coursegroups {
1.809 raeburn 5681: my ($cdom,$cnum,$group,$namespace) = @_;
5682: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5683: }
5684:
1.679 raeburn 5685: sub modify_coursegroup {
5686: my ($cdom,$cnum,$groupsettings) = @_;
5687: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5688: }
5689:
1.809 raeburn 5690: sub toggle_coursegroup_status {
5691: my ($cdom,$cnum,$group,$action) = @_;
5692: my ($from_namespace,$to_namespace);
5693: if ($action eq 'delete') {
5694: $from_namespace = 'coursegroups';
5695: $to_namespace = 'deleted_groups';
5696: } else {
5697: $from_namespace = 'deleted_groups';
5698: $to_namespace = 'coursegroups';
5699: }
5700: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5701: if (my $tmp = &error(%curr_group)) {
5702: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5703: return ('read error',$tmp);
5704: } else {
5705: my %savedsettings = %curr_group;
1.809 raeburn 5706: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5707: my $deloutcome;
5708: if ($result eq 'ok') {
1.809 raeburn 5709: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5710: } else {
5711: return ('write error',$result);
5712: }
5713: if ($deloutcome eq 'ok') {
5714: return 'ok';
5715: } else {
5716: return ('delete error',$deloutcome);
5717: }
5718: }
5719: }
5720:
1.679 raeburn 5721: sub modify_group_roles {
1.957 raeburn 5722: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5723: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5724: my $role = 'gr/'.&escape($userprivs);
5725: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5726: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5727: if ($result eq 'ok') {
5728: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5729: }
1.679 raeburn 5730: return $result;
5731: }
5732:
5733: sub modify_coursegroup_membership {
5734: my ($cdom,$cnum,$membership) = @_;
5735: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5736: return $result;
5737: }
5738:
1.682 raeburn 5739: sub get_active_groups {
5740: my ($udom,$uname,$cdom,$cnum) = @_;
5741: my $now = time;
5742: my %groups = ();
5743: foreach my $key (keys(%env)) {
1.811 albertel 5744: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5745: my ($start,$end) = split(/\./,$env{$key});
5746: if (($end!=0) && ($end<$now)) { next; }
5747: if (($start!=0) && ($start>$now)) { next; }
5748: if ($1 eq $cdom && $2 eq $cnum) {
5749: $groups{$3} = $env{$key} ;
5750: }
5751: }
5752: }
5753: return %groups;
5754: }
5755:
1.683 raeburn 5756: sub get_group_membership {
5757: my ($cdom,$cnum,$group) = @_;
5758: return(&dump('groupmembership',$cdom,$cnum,$group));
5759: }
5760:
5761: sub get_users_groups {
5762: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5763: my @usersgroups;
1.683 raeburn 5764: my $cachetime=1800;
5765:
5766: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5767: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5768: if (defined($cached)) {
1.734 albertel 5769: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5770: } else {
5771: $grouplist = '';
1.816 raeburn 5772: my $courseurl = &courseid_to_courseurl($courseid);
5773: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5774: my $access_end = $env{'course.'.$courseid.
5775: '.default_enrollment_end_date'};
5776: my $now = time;
5777: foreach my $key (keys(%roleshash)) {
5778: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5779: my $group = $1;
5780: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5781: my $start = $2;
5782: my $end = $1;
5783: if ($start == -1) { next; } # deleted from group
5784: if (($start!=0) && ($start>$now)) { next; }
5785: if (($end!=0) && ($end<$now)) {
5786: if ($access_end && $access_end < $now) {
5787: if ($access_end - $end < 86400) {
5788: push(@usersgroups,$group);
1.733 raeburn 5789: }
5790: }
1.817 raeburn 5791: next;
1.733 raeburn 5792: }
1.817 raeburn 5793: push(@usersgroups,$group);
1.683 raeburn 5794: }
5795: }
5796: }
1.817 raeburn 5797: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5798: $grouplist = join(':',@usersgroups);
5799: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5800: }
1.733 raeburn 5801: return @usersgroups;
1.683 raeburn 5802: }
5803:
5804: sub devalidate_getgroups_cache {
5805: my ($udom,$uname,$cdom,$cnum)=@_;
5806: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5807:
1.683 raeburn 5808: my $hashid="$udom:$uname:$courseid";
5809: &devalidate_cache_new('getgroups',$hashid);
5810: }
5811:
1.12 www 5812: # ------------------------------------------------------------------ Plain Text
5813:
5814: sub plaintext {
1.988 raeburn 5815: my ($short,$type,$cid,$forcedefault) = @_;
1.758 albertel 5816: if ($short =~ /^cr/) {
5817: return (split('/',$short))[-1];
5818: }
1.742 raeburn 5819: if (!defined($cid)) {
5820: $cid = $env{'request.course.id'};
5821: }
1.988 raeburn 5822: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
5823: unless ($forcedefault) {
5824: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
5825: &Apache::lonlocal::mt_escape(\$roletext);
5826: return &Apache::lonlocal::mt($roletext);
5827: }
1.742 raeburn 5828: }
5829: my %rolenames = (
5830: Course => 'std',
5831: Group => 'alt1',
5832: );
5833: if (defined($type) &&
5834: defined($rolenames{$type}) &&
5835: defined($prp{$short}{$rolenames{$type}})) {
5836: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5837: } else {
5838: return &Apache::lonlocal::mt($prp{$short}{'std'});
5839: }
1.12 www 5840: }
5841:
5842: # ----------------------------------------------------------------- Assign Role
5843:
5844: sub assignrole {
1.957 raeburn 5845: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5846: $context)=@_;
1.21 www 5847: my $mrole;
5848: if ($role =~ /^cr\//) {
1.393 www 5849: my $cwosec=$url;
1.811 albertel 5850: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5851: unless (&allowed('ccr',$cwosec)) {
1.104 www 5852: &logthis('Refused custom assignrole: '.
5853: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5854: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5855: return 'refused';
5856: }
1.21 www 5857: $mrole='cr';
1.678 raeburn 5858: } elsif ($role =~ /^gr\//) {
5859: my $cwogrp=$url;
1.811 albertel 5860: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5861: unless (&allowed('mdg',$cwogrp)) {
5862: &logthis('Refused group assignrole: '.
5863: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5864: $env{'user.name'}.' at '.$env{'user.domain'});
5865: return 'refused';
5866: }
5867: $mrole='gr';
1.21 www 5868: } else {
1.82 www 5869: my $cwosec=$url;
1.811 albertel 5870: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5871: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5872: my $refused;
5873: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5874: if (!(&allowed('c'.$role,$url))) {
5875: $refused = 1;
5876: }
5877: } else {
5878: $refused = 1;
5879: }
1.947 raeburn 5880: if ($refused) {
5881: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5882: $refused = '';
5883: } else {
5884: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5885: ' '.$role.' '.$end.' '.$start.' by '.
5886: $env{'user.name'}.' at '.$env{'user.domain'});
5887: return 'refused';
5888: }
1.932 raeburn 5889: }
1.104 www 5890: }
1.21 www 5891: $mrole=$role;
5892: }
1.620 albertel 5893: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5894: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5895: if ($end) { $command.='_'.$end; }
1.21 www 5896: if ($start) {
5897: if ($end) {
1.81 www 5898: $command.='_'.$start;
1.21 www 5899: } else {
1.81 www 5900: $command.='_0_'.$start;
1.21 www 5901: }
5902: }
1.739 raeburn 5903: my $origstart = $start;
5904: my $origend = $end;
1.957 raeburn 5905: my $delflag;
1.357 www 5906: # actually delete
5907: if ($deleteflag) {
1.373 www 5908: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5909: # modify command to delete the role
1.620 albertel 5910: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5911: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5912: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5913: # set start and finish to negative values for userrolelog
5914: $start=-1;
5915: $end=-1;
1.957 raeburn 5916: $delflag = 1;
1.357 www 5917: }
5918: }
5919: # send command
1.349 www 5920: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5921: # log new user role if status is ok
1.349 www 5922: if ($answer eq 'ok') {
1.663 raeburn 5923: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5924: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5925: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5926: unless ($role =~ /^gr/) {
5927: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5928: $origstart,$selfenroll,$context);
1.739 raeburn 5929: }
1.349 www 5930: }
5931: return $answer;
1.169 harris41 5932: }
5933:
5934: # -------------------------------------------------- Modify user authentication
1.197 www 5935: # Overrides without validation
5936:
1.169 harris41 5937: sub modifyuserauth {
5938: my ($udom,$uname,$umode,$upass)=@_;
5939: my $uhome=&homeserver($uname,$udom);
1.197 www 5940: unless (&allowed('mau',$udom)) { return 'refused'; }
5941: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5942: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5943: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5944: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5945: &escape($upass),$uhome);
1.620 albertel 5946: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5947: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5948: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5949: &log($udom,,$uname,$uhome,
1.620 albertel 5950: 'Authentication changed by '.$env{'user.domain'}.', '.
5951: $env{'user.name'}.', '.$umode.
1.197 www 5952: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5953: unless ($reply eq 'ok') {
1.197 www 5954: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5955: return 'error: '.$reply;
5956: }
1.170 harris41 5957: return 'ok';
1.80 www 5958: }
5959:
1.81 www 5960: # --------------------------------------------------------------- Modify a user
1.80 www 5961:
1.81 www 5962: sub modifyuser {
1.206 matthew 5963: my ($udom, $uname, $uid,
5964: $umode, $upass, $first,
5965: $middle, $last, $gene,
1.963 raeburn 5966: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 5967: $udom= &LONCAPA::clean_domain($udom);
5968: $uname=&LONCAPA::clean_username($uname);
1.81 www 5969: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5970: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5971: $last.', '.$gene.'(forceid: '.$forceid.')'.
5972: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5973: ' desiredhome not specified').
1.620 albertel 5974: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5975: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5976: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5977: # ----------------------------------------------------------------- Create User
1.406 albertel 5978: if (($uhome eq 'no_host') &&
5979: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5980: my $unhome='';
1.844 albertel 5981: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5982: $unhome = $desiredhome;
1.620 albertel 5983: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5984: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5985: } else { # load balancing routine for determining $unhome
1.81 www 5986: my $loadm=10000000;
1.841 albertel 5987: my %servers = &get_servers($udom,'library');
5988: foreach my $tryserver (keys(%servers)) {
5989: my $answer=reply('load',$tryserver);
5990: if (($answer=~/\d+/) && ($answer<$loadm)) {
5991: $loadm=$answer;
5992: $unhome=$tryserver;
5993: }
1.80 www 5994: }
5995: }
5996: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5997: return 'error: unable to find a home server for '.$uname.
5998: ' in domain '.$udom;
1.80 www 5999: }
6000: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6001: &escape($upass),$unhome);
6002: unless ($reply eq 'ok') {
6003: return 'error: '.$reply;
6004: }
1.230 stredwic 6005: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6006: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6007: return 'error: unable verify users home machine.';
1.80 www 6008: }
1.209 matthew 6009: } # End of creation of new user
1.80 www 6010: # ---------------------------------------------------------------------- Add ID
6011: if ($uid) {
6012: $uid=~tr/A-Z/a-z/;
6013: my %uidhash=&idrget($udom,$uname);
1.196 www 6014: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6015: && (!$forceid)) {
1.80 www 6016: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6017: return 'error: user id "'.$uid.'" does not match '.
6018: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6019: }
6020: } else {
6021: &idput($udom,($uname => $uid));
6022: }
6023: }
6024: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6025: my @tmp=&get('environment',
1.899 raeburn 6026: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6027: 'permanentemail','inststatus'],
1.134 albertel 6028: $udom,$uname);
1.313 matthew 6029: my %names;
6030: if ($tmp[0] =~ m/^error:.*/) {
6031: %names=();
6032: } else {
6033: %names = @tmp;
6034: }
1.388 www 6035: #
6036: # Make sure to not trash student environment if instructor does not bother
6037: # to supply name and email information
6038: #
6039: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6040: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6041: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6042: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6043: if ($email) {
6044: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6045: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6046: }
1.899 raeburn 6047: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6048: if (defined($inststatus)) {
6049: $names{'inststatus'} = '';
6050: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6051: if (ref($usertypes) eq 'HASH') {
6052: my @okstatuses;
6053: foreach my $item (split(/:/,$inststatus)) {
6054: if (defined($usertypes->{$item})) {
6055: push(@okstatuses,$item);
6056: }
6057: }
6058: if (@okstatuses) {
6059: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6060: }
6061: }
6062: }
1.134 albertel 6063: my $reply = &put('environment', \%names, $udom,$uname);
6064: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6065: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6066: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6067: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6068: $umode.', '.$first.', '.$middle.', '.
6069: $last.', '.$gene.', '.$email.', '.$inststatus;
6070: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6071: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6072: } else {
6073: $logmsg .= ' during self creation';
6074: }
6075: &logthis($logmsg);
1.134 albertel 6076: return 'ok';
1.80 www 6077: }
6078:
1.81 www 6079: # -------------------------------------------------------------- Modify student
1.80 www 6080:
1.81 www 6081: sub modifystudent {
6082: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6083: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6084: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6085: if (!$cid) {
1.620 albertel 6086: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6087: return 'not_in_class';
6088: }
1.80 www 6089: }
6090: # --------------------------------------------------------------- Make the user
1.81 www 6091: my $reply=&modifyuser
1.209 matthew 6092: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6093: $desiredhome,$email,$inststatus);
1.80 www 6094: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6095: # This will cause &modify_student_enrollment to get the uid from the
6096: # students environment
6097: $uid = undef if (!$forceid);
1.455 albertel 6098: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6099: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6100: return $reply;
6101: }
6102:
6103: sub modify_student_enrollment {
1.957 raeburn 6104: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6105: my ($cdom,$cnum,$chome);
6106: if (!$cid) {
1.620 albertel 6107: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6108: return 'not_in_class';
6109: }
1.620 albertel 6110: $cdom=$env{'course.'.$cid.'.domain'};
6111: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6112: } else {
6113: ($cdom,$cnum)=split(/_/,$cid);
6114: }
1.620 albertel 6115: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6116: if (!$chome) {
1.457 raeburn 6117: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6118: }
1.455 albertel 6119: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6120: # Make sure the user exists
1.81 www 6121: my $uhome=&homeserver($uname,$udom);
6122: if (($uhome eq '') || ($uhome eq 'no_host')) {
6123: return 'error: no such user';
6124: }
1.297 matthew 6125: # Get student data if we were not given enough information
6126: if (!defined($first) || $first eq '' ||
6127: !defined($last) || $last eq '' ||
6128: !defined($uid) || $uid eq '' ||
6129: !defined($middle) || $middle eq '' ||
6130: !defined($gene) || $gene eq '') {
1.294 matthew 6131: # They did not supply us with enough data to enroll the student, so
6132: # we need to pick up more information.
1.297 matthew 6133: my %tmp = &get('environment',
1.294 matthew 6134: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6135: ,$udom,$uname);
6136:
1.800 albertel 6137: #foreach my $key (keys(%tmp)) {
6138: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6139: #}
1.294 matthew 6140: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6141: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6142: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6143: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6144: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6145: }
1.556 albertel 6146: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6147: my $reply=cput('classlist',
6148: {"$uname:$udom" =>
1.515 raeburn 6149: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6150: $cdom,$cnum);
1.81 www 6151: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6152: return 'error: '.$reply;
1.652 albertel 6153: } else {
6154: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6155: }
1.297 matthew 6156: # Add student role to user
1.83 www 6157: my $uurl='/'.$cid;
1.81 www 6158: $uurl=~s/\_/\//g;
6159: if ($usec) {
6160: $uurl.='/'.$usec;
6161: }
1.957 raeburn 6162: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6163: }
6164:
1.556 albertel 6165: sub format_name {
6166: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6167: my $name;
6168: if ($first ne 'lastname') {
6169: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6170: } else {
6171: if ($lastname=~/\S/) {
6172: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6173: $name=~s/\s+,/,/;
6174: } else {
6175: $name.= $firstname.' '.$middlename.' '.$generation;
6176: }
6177: }
6178: $name=~s/^\s+//;
6179: $name=~s/\s+$//;
6180: $name=~s/\s+/ /g;
6181: return $name;
6182: }
6183:
1.84 www 6184: # ------------------------------------------------- Write to course preferences
6185:
6186: sub writecoursepref {
6187: my ($courseid,%prefs)=@_;
6188: $courseid=~s/^\///;
6189: $courseid=~s/\_/\//g;
6190: my ($cdomain,$cnum)=split(/\//,$courseid);
6191: my $chome=homeserver($cnum,$cdomain);
6192: if (($chome eq '') || ($chome eq 'no_host')) {
6193: return 'error: no such course';
6194: }
6195: my $cstring='';
1.800 albertel 6196: foreach my $pref (keys(%prefs)) {
6197: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6198: }
1.84 www 6199: $cstring=~s/\&$//;
6200: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6201: }
6202:
6203: # ---------------------------------------------------------- Make/modify course
6204:
6205: sub createcourse {
1.741 raeburn 6206: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6207: $course_owner,$crstype)=@_;
1.84 www 6208: $url=&declutter($url);
6209: my $cid='';
1.264 matthew 6210: unless (&allowed('ccc',$udom)) {
1.84 www 6211: return 'refused';
6212: }
6213: # ------------------------------------------------------------------- Create ID
1.674 www 6214: my $uname=int(1+rand(9)).
6215: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6216: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 6217: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6218: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 6219: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6220: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6221: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
6222: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 6223: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6224: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6225: return 'error: unable to generate unique course-ID';
6226: }
6227: }
1.264 matthew 6228: # ------------------------------------------------ Check supplied server name
1.620 albertel 6229: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6230: if (! &is_library($course_server)) {
1.264 matthew 6231: return 'error:bad server name '.$course_server;
6232: }
1.84 www 6233: # ------------------------------------------------------------- Make the course
6234: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6235: $course_server);
1.84 www 6236: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 6237: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6238: if (($uhome eq '') || ($uhome eq 'no_host')) {
6239: return 'error: no such course';
6240: }
1.271 www 6241: # ----------------------------------------------------------------- Course made
1.516 raeburn 6242: # log existence
1.918 raeburn 6243: my $newcourse = {
6244: $udom.'_'.$uname => {
1.921 raeburn 6245: description => $description,
6246: inst_code => $inst_code,
6247: owner => $course_owner,
6248: type => $crstype,
1.918 raeburn 6249: },
6250: };
1.921 raeburn 6251: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6252: # set toplevel url
1.271 www 6253: my $topurl=$url;
6254: unless ($nonstandard) {
6255: # ------------------------------------------ For standard courses, make top url
6256: my $mapurl=&clutter($url);
1.278 www 6257: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6258: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6259: <map>
6260: <resource id="1" type="start"></resource>
6261: <resource id="2" src="$mapurl"></resource>
6262: <resource id="3" type="finish"></resource>
6263: <link index="1" from="1" to="2"></link>
6264: <link index="2" from="2" to="3"></link>
6265: </map>
6266: ENDINITMAP
6267: $topurl=&declutter(
1.638 albertel 6268: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6269: );
6270: }
6271: # ----------------------------------------------------------- Write preferences
1.84 www 6272: &writecoursepref($udom.'_'.$uname,
6273: ('description' => $description,
1.271 www 6274: 'url' => $topurl));
1.84 www 6275: return '/'.$udom.'/'.$uname;
6276: }
6277:
1.813 albertel 6278: sub is_course {
6279: my ($cdom,$cnum) = @_;
6280: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6281: undef,'.');
1.813 albertel 6282: if (exists($courses{$cdom.'_'.$cnum})) {
6283: return 1;
6284: }
6285: return 0;
6286: }
6287:
1.21 www 6288: # ---------------------------------------------------------- Assign Custom Role
6289:
6290: sub assigncustomrole {
1.957 raeburn 6291: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6292: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6293: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6294: }
6295:
6296: # ----------------------------------------------------------------- Revoke Role
6297:
6298: sub revokerole {
1.957 raeburn 6299: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6300: my $now=time;
1.965 raeburn 6301: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6302: }
6303:
6304: # ---------------------------------------------------------- Revoke Custom Role
6305:
6306: sub revokecustomrole {
1.957 raeburn 6307: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6308: my $now=time;
1.357 www 6309: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6310: $deleteflag,$selfenroll,$context);
1.17 www 6311: }
6312:
1.533 banghart 6313: # ------------------------------------------------------------ Disk usage
1.535 albertel 6314: sub diskusage {
1.955 raeburn 6315: my ($udom,$uname,$directorypath,$getpropath)=@_;
6316: $directorypath =~ s/\/$//;
6317: my $listing=&reply('du2:'.&escape($directorypath).':'
6318: .&escape($getpropath).':'.&escape($uname).':'
6319: .&escape($udom),homeserver($uname,$udom));
6320: if ($listing eq 'unknown_cmd') {
6321: if ($getpropath) {
6322: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6323: }
6324: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6325: }
1.514 albertel 6326: return $listing;
1.512 banghart 6327: }
6328:
1.566 banghart 6329: sub is_locked {
6330: my ($file_name, $domain, $user) = @_;
6331: my @check;
6332: my $is_locked;
6333: push @check, $file_name;
1.613 albertel 6334: my %locked = &get('file_permissions',\@check,
1.620 albertel 6335: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6336: my ($tmp)=keys(%locked);
6337: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6338:
1.566 banghart 6339: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6340: $is_locked = 'false';
6341: foreach my $entry (@{$locked{$file_name}}) {
6342: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6343: $is_locked = 'true';
6344: last;
1.745 raeburn 6345: }
6346: }
1.566 banghart 6347: } else {
6348: $is_locked = 'false';
6349: }
6350: }
6351:
1.759 albertel 6352: sub declutter_portfile {
6353: my ($file) = @_;
1.833 albertel 6354: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6355: return $file;
6356: }
6357:
1.559 banghart 6358: # ------------------------------------------------------------- Mark as Read Only
6359:
6360: sub mark_as_readonly {
6361: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6362: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6363: my ($tmp)=keys(%current_permissions);
6364: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6365: foreach my $file (@{$files}) {
1.759 albertel 6366: $file = &declutter_portfile($file);
1.561 banghart 6367: push(@{$current_permissions{$file}},$what);
1.559 banghart 6368: }
1.613 albertel 6369: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6370: return;
6371: }
6372:
1.572 banghart 6373: # ------------------------------------------------------------Save Selected Files
6374:
6375: sub save_selected_files {
6376: my ($user, $path, @files) = @_;
6377: my $filename = $user."savedfiles";
1.573 banghart 6378: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6379: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6380: foreach my $file (@files) {
1.620 albertel 6381: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6382: }
6383: foreach my $file (@other_files) {
1.574 banghart 6384: print (OUT $file."\n");
1.572 banghart 6385: }
1.574 banghart 6386: close (OUT);
1.572 banghart 6387: return 'ok';
6388: }
6389:
1.574 banghart 6390: sub clear_selected_files {
6391: my ($user) = @_;
6392: my $filename = $user."savedfiles";
6393: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6394: print (OUT undef);
6395: close (OUT);
6396: return ("ok");
6397: }
6398:
1.572 banghart 6399: sub files_in_path {
6400: my ($user, $path) = @_;
6401: my $filename = $user."savedfiles";
6402: my %return_files;
1.574 banghart 6403: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6404: while (my $line_in = <IN>) {
1.574 banghart 6405: chomp ($line_in);
6406: my @paths_and_file = split (m!/!, $line_in);
6407: my $file_part = pop (@paths_and_file);
6408: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6409: $path_part.='/';
6410: my $path_and_file = $path_part.$file_part;
6411: if ($path_part eq $path) {
6412: $return_files{$file_part}= 'selected';
6413: }
6414: }
1.574 banghart 6415: close (IN);
6416: return (\%return_files);
1.572 banghart 6417: }
6418:
6419: # called in portfolio select mode, to show files selected NOT in current directory
6420: sub files_not_in_path {
6421: my ($user, $path) = @_;
6422: my $filename = $user."savedfiles";
6423: my @return_files;
6424: my $path_part;
1.800 albertel 6425: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6426: while (my $line = <IN>) {
1.572 banghart 6427: #ok, I know it's clunky, but I want it to work
1.800 albertel 6428: my @paths_and_file = split(m|/|, $line);
6429: my $file_part = pop(@paths_and_file);
6430: chomp($file_part);
6431: my $path_part = join('/', @paths_and_file);
1.572 banghart 6432: $path_part .= '/';
6433: my $path_and_file = $path_part.$file_part;
6434: if ($path_part ne $path) {
1.800 albertel 6435: push(@return_files, ($path_and_file));
1.572 banghart 6436: }
6437: }
1.800 albertel 6438: close(OUT);
1.574 banghart 6439: return (@return_files);
1.572 banghart 6440: }
6441:
1.745 raeburn 6442: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6443:
1.745 raeburn 6444: sub get_portfile_permissions {
6445: my ($domain,$user) = @_;
1.613 albertel 6446: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6447: my ($tmp)=keys(%current_permissions);
6448: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6449: return \%current_permissions;
6450: }
6451:
6452: #---------------------------------------------Get portfolio file access controls
6453:
1.749 raeburn 6454: sub get_access_controls {
1.745 raeburn 6455: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6456: my %access;
6457: my $real_file = $file;
6458: $file =~ s/\.meta$//;
1.745 raeburn 6459: if (defined($file)) {
1.749 raeburn 6460: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6461: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6462: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6463: }
6464: }
1.745 raeburn 6465: } else {
1.749 raeburn 6466: foreach my $key (keys(%{$current_permissions})) {
6467: if ($key =~ /\0accesscontrol$/) {
6468: if (defined($group)) {
6469: if ($key !~ m-^\Q$group\E/-) {
6470: next;
6471: }
6472: }
6473: my ($fullpath) = split(/\0/,$key);
6474: if (ref($$current_permissions{$key}) eq 'HASH') {
6475: foreach my $control (keys(%{$$current_permissions{$key}})) {
6476: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6477: }
6478: }
6479: }
6480: }
6481: }
6482: return %access;
6483: }
6484:
6485: sub modify_access_controls {
6486: my ($file_name,$changes,$domain,$user)=@_;
6487: my ($outcome,$deloutcome);
6488: my %store_permissions;
6489: my %new_values;
6490: my %new_control;
6491: my %translation;
6492: my @deletions = ();
6493: my $now = time;
6494: if (exists($$changes{'activate'})) {
6495: if (ref($$changes{'activate'}) eq 'HASH') {
6496: my @newitems = sort(keys(%{$$changes{'activate'}}));
6497: my $numnew = scalar(@newitems);
6498: for (my $i=0; $i<$numnew; $i++) {
6499: my $newkey = $newitems[$i];
6500: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6501: if ($newkey =~ /^\d+:/) {
6502: $newkey =~ s/^(\d+)/$newid/;
6503: $translation{$1} = $newid;
6504: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6505: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6506: $translation{$1} = $newid;
6507: }
1.749 raeburn 6508: $new_values{$file_name."\0".$newkey} =
6509: $$changes{'activate'}{$newitems[$i]};
6510: $new_control{$newkey} = $now;
6511: }
6512: }
6513: }
6514: my %todelete;
6515: my %changed_items;
6516: foreach my $action ('delete','update') {
6517: if (exists($$changes{$action})) {
6518: if (ref($$changes{$action}) eq 'HASH') {
6519: foreach my $key (keys(%{$$changes{$action}})) {
6520: my ($itemnum) = ($key =~ /^([^:]+):/);
6521: if ($action eq 'delete') {
6522: $todelete{$itemnum} = 1;
6523: } else {
6524: $changed_items{$itemnum} = $key;
6525: }
6526: }
1.745 raeburn 6527: }
6528: }
1.749 raeburn 6529: }
6530: # get lock on access controls for file.
6531: my $lockhash = {
6532: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6533: ':'.$env{'user.domain'},
6534: };
6535: my $tries = 0;
6536: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6537:
6538: while (($gotlock ne 'ok') && $tries <3) {
6539: $tries ++;
6540: sleep 1;
6541: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6542: }
6543: if ($gotlock eq 'ok') {
6544: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6545: my ($tmp)=keys(%curr_permissions);
6546: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6547: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6548: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6549: if (ref($curr_controls) eq 'HASH') {
6550: foreach my $control_item (keys(%{$curr_controls})) {
6551: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6552: if (defined($todelete{$itemnum})) {
6553: push(@deletions,$file_name."\0".$control_item);
6554: } else {
6555: if (defined($changed_items{$itemnum})) {
6556: $new_control{$changed_items{$itemnum}} = $now;
6557: push(@deletions,$file_name."\0".$control_item);
6558: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6559: } else {
6560: $new_control{$control_item} = $$curr_controls{$control_item};
6561: }
6562: }
1.745 raeburn 6563: }
6564: }
6565: }
1.970 raeburn 6566: my ($group);
6567: if (&is_course($domain,$user)) {
6568: ($group,my $file) = split(/\//,$file_name,2);
6569: }
1.749 raeburn 6570: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6571: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6572: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6573: # remove lock
6574: my @del_lock = ($file_name."\0".'locked_access_records');
6575: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6576: my $sqlresult =
1.970 raeburn 6577: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6578: $group);
1.749 raeburn 6579: } else {
6580: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6581: }
1.749 raeburn 6582: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6583: }
6584:
1.827 raeburn 6585: sub make_public_indefinitely {
6586: my ($requrl) = @_;
6587: my $now = time;
6588: my $action = 'activate';
6589: my $aclnum = 0;
6590: if (&is_portfolio_url($requrl)) {
6591: my (undef,$udom,$unum,$file_name,$group) =
6592: &parse_portfolio_url($requrl);
6593: my $current_perms = &get_portfile_permissions($udom,$unum);
6594: my %access_controls = &get_access_controls($current_perms,
6595: $group,$file_name);
6596: foreach my $key (keys(%{$access_controls{$file_name}})) {
6597: my ($num,$scope,$end,$start) =
6598: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6599: if ($scope eq 'public') {
6600: if ($start <= $now && $end == 0) {
6601: $action = 'none';
6602: } else {
6603: $action = 'update';
6604: $aclnum = $num;
6605: }
6606: last;
6607: }
6608: }
6609: if ($action eq 'none') {
6610: return 'ok';
6611: } else {
6612: my %changes;
6613: my $newend = 0;
6614: my $newstart = $now;
6615: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6616: $changes{$action}{$newkey} = {
6617: type => 'public',
6618: time => {
6619: start => $newstart,
6620: end => $newend,
6621: },
6622: };
6623: my ($outcome,$deloutcome,$new_values,$translation) =
6624: &modify_access_controls($file_name,\%changes,$udom,$unum);
6625: return $outcome;
6626: }
6627: } else {
6628: return 'invalid';
6629: }
6630: }
6631:
1.745 raeburn 6632: #------------------------------------------------------Get Marked as Read Only
6633:
6634: sub get_marked_as_readonly {
6635: my ($domain,$user,$what,$group) = @_;
6636: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6637: my @readonly_files;
1.629 banghart 6638: my $cmp1=$what;
6639: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6640: while (my ($file_name,$value) = each(%{$current_permissions})) {
6641: if (defined($group)) {
6642: if ($file_name !~ m-^\Q$group\E/-) {
6643: next;
6644: }
6645: }
1.561 banghart 6646: if (ref($value) eq "ARRAY"){
6647: foreach my $stored_what (@{$value}) {
1.629 banghart 6648: my $cmp2=$stored_what;
1.759 albertel 6649: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6650: $cmp2=join('',@{$stored_what});
1.745 raeburn 6651: }
1.629 banghart 6652: if ($cmp1 eq $cmp2) {
1.561 banghart 6653: push(@readonly_files, $file_name);
1.745 raeburn 6654: last;
1.563 banghart 6655: } elsif (!defined($what)) {
6656: push(@readonly_files, $file_name);
1.745 raeburn 6657: last;
1.561 banghart 6658: }
6659: }
1.745 raeburn 6660: }
1.561 banghart 6661: }
6662: return @readonly_files;
6663: }
1.577 banghart 6664: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6665:
1.577 banghart 6666: sub get_marked_as_readonly_hash {
1.745 raeburn 6667: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6668: my %readonly_files;
1.745 raeburn 6669: while (my ($file_name,$value) = each(%{$current_permissions})) {
6670: if (defined($group)) {
6671: if ($file_name !~ m-^\Q$group\E/-) {
6672: next;
6673: }
6674: }
1.577 banghart 6675: if (ref($value) eq "ARRAY"){
6676: foreach my $stored_what (@{$value}) {
1.745 raeburn 6677: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6678: foreach my $lock_descriptor(@{$stored_what}) {
6679: if ($lock_descriptor eq 'graded') {
6680: $readonly_files{$file_name} = 'graded';
6681: } elsif ($lock_descriptor eq 'handback') {
6682: $readonly_files{$file_name} = 'handback';
6683: } else {
6684: if (!exists($readonly_files{$file_name})) {
6685: $readonly_files{$file_name} = 'locked';
6686: }
6687: }
1.745 raeburn 6688: }
1.750 banghart 6689: }
1.577 banghart 6690: }
6691: }
6692: }
6693: return %readonly_files;
6694: }
1.559 banghart 6695: # ------------------------------------------------------------ Unmark as Read Only
6696:
6697: sub unmark_as_readonly {
1.629 banghart 6698: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6699: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6700: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6701: $file_name = &declutter_portfile($file_name);
1.634 albertel 6702: my $symb_crs = $what;
6703: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6704: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6705: my ($tmp)=keys(%current_permissions);
6706: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6707: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6708: foreach my $file (@readonly_files) {
1.759 albertel 6709: my $clean_file = &declutter_portfile($file);
6710: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6711: my $current_locks = $current_permissions{$file};
1.563 banghart 6712: my @new_locks;
6713: my @del_keys;
6714: if (ref($current_locks) eq "ARRAY"){
6715: foreach my $locker (@{$current_locks}) {
1.632 albertel 6716: my $compare=$locker;
1.749 raeburn 6717: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6718: $compare=join('',@{$locker});
1.746 raeburn 6719: if ($compare ne $symb_crs) {
6720: push(@new_locks, $locker);
6721: }
1.563 banghart 6722: }
6723: }
1.650 albertel 6724: if (scalar(@new_locks) > 0) {
1.563 banghart 6725: $current_permissions{$file} = \@new_locks;
6726: } else {
6727: push(@del_keys, $file);
1.613 albertel 6728: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6729: delete($current_permissions{$file});
1.563 banghart 6730: }
6731: }
1.561 banghart 6732: }
1.613 albertel 6733: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6734: return;
6735: }
1.512 banghart 6736:
1.17 www 6737: # ------------------------------------------------------------ Directory lister
6738:
6739: sub dirlist {
1.955 raeburn 6740: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6741: $uri=~s/^\///;
6742: $uri=~s/\/$//;
1.253 stredwic 6743: my ($udom, $uname);
1.955 raeburn 6744: if ($getuserdir) {
1.253 stredwic 6745: $udom = $userdomain;
6746: $uname = $username;
1.955 raeburn 6747: } else {
6748: (undef,$udom,$uname)=split(/\//,$uri);
6749: if(defined($userdomain)) {
6750: $udom = $userdomain;
6751: }
6752: if(defined($username)) {
6753: $uname = $username;
6754: }
1.253 stredwic 6755: }
1.955 raeburn 6756: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6757:
1.955 raeburn 6758: $dirRoot = $perlvar{'lonDocRoot'};
6759: if (defined($getpropath)) {
6760: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6761: $dirRoot =~ s/\/$//;
1.955 raeburn 6762: } elsif (defined($getuserdir)) {
6763: my $subdir=$uname.'__';
6764: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6765: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6766: ."/$udom/$subdir/$uname";
6767: } elsif (defined($alternateRoot)) {
6768: $dirRoot = $alternateRoot;
1.751 banghart 6769: }
1.253 stredwic 6770:
6771: if($udom) {
6772: if($uname) {
1.955 raeburn 6773: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6774: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6775: .':'.&escape($uname).':'.&escape($udom),
6776: &homeserver($uname,$udom));
6777: if ($listing eq 'unknown_cmd') {
6778: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6779: &homeserver($uname,$udom));
6780: } else {
6781: @listing_results = map { &unescape($_); } split(/:/,$listing);
6782: }
1.605 matthew 6783: if ($listing eq 'unknown_cmd') {
1.800 albertel 6784: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6785: &homeserver($uname,$udom));
1.605 matthew 6786: @listing_results = split(/:/,$listing);
6787: } else {
6788: @listing_results = map { &unescape($_); } split(/:/,$listing);
6789: }
6790: return @listing_results;
1.955 raeburn 6791: } elsif(!$alternateRoot) {
1.800 albertel 6792: my %allusers;
1.841 albertel 6793: my %servers = &get_servers($udom,'library');
1.955 raeburn 6794: foreach my $tryserver (keys(%servers)) {
6795: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6796: &escape($udom),$tryserver);
6797: if ($listing eq 'unknown_cmd') {
6798: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6799: $udom, $tryserver);
6800: } else {
6801: @listing_results = map { &unescape($_); } split(/:/,$listing);
6802: }
1.841 albertel 6803: if ($listing eq 'unknown_cmd') {
6804: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6805: $udom, $tryserver);
6806: @listing_results = split(/:/,$listing);
6807: } else {
6808: @listing_results =
6809: map { &unescape($_); } split(/:/,$listing);
6810: }
6811: if ($listing_results[0] ne 'no_such_dir' &&
6812: $listing_results[0] ne 'empty' &&
6813: $listing_results[0] ne 'con_lost') {
6814: foreach my $line (@listing_results) {
6815: my ($entry) = split(/&/,$line,2);
6816: $allusers{$entry} = 1;
6817: }
6818: }
1.253 stredwic 6819: }
6820: my $alluserstr='';
1.800 albertel 6821: foreach my $user (sort(keys(%allusers))) {
6822: $alluserstr.=$user.'&user:';
1.253 stredwic 6823: }
6824: $alluserstr=~s/:$//;
6825: return split(/:/,$alluserstr);
6826: } else {
1.800 albertel 6827: return ('missing user name');
1.253 stredwic 6828: }
1.955 raeburn 6829: } elsif(!defined($getpropath)) {
1.841 albertel 6830: my @all_domains = sort(&all_domains());
1.955 raeburn 6831: foreach my $domain (@all_domains) {
6832: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6833: }
6834: return @all_domains;
6835: } else {
1.800 albertel 6836: return ('missing domain');
1.275 stredwic 6837: }
6838: }
6839:
6840: # --------------------------------------------- GetFileTimestamp
6841: # This function utilizes dirlist and returns the date stamp for
6842: # when it was last modified. It will also return an error of -1
6843: # if an error occurs
6844:
6845: sub GetFileTimestamp {
1.955 raeburn 6846: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6847: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6848: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6849: my ($fileStat) =
6850: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6851: undef,$getuserdir);
1.275 stredwic 6852: my @stats = split('&', $fileStat);
6853: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6854: # @stats contains first the filename, then the stat output
6855: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6856: } else {
6857: return -1;
1.253 stredwic 6858: }
1.26 www 6859: }
6860:
1.712 albertel 6861: sub stat_file {
6862: my ($uri) = @_;
1.787 albertel 6863: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6864:
1.955 raeburn 6865: my ($udom,$uname,$file);
1.712 albertel 6866: if ($uri =~ m-^/(uploaded|editupload)/-) {
6867: ($udom,$uname,$file) =
1.811 albertel 6868: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6869: $file = 'userfiles/'.$file;
6870: }
6871: if ($uri =~ m-^/res/-) {
6872: ($udom,$uname) =
1.807 albertel 6873: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6874: $file = $uri;
6875: }
6876:
6877: if (!$udom || !$uname || !$file) {
6878: # unable to handle the uri
6879: return ();
6880: }
1.956 raeburn 6881: my $getpropath;
6882: if ($file =~ /^userfiles\//) {
6883: $getpropath = 1;
6884: }
1.955 raeburn 6885: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6886: my @stats = split('&', $result);
1.721 banghart 6887:
1.712 albertel 6888: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6889: shift(@stats); #filename is first
6890: return @stats;
6891: }
6892: return ();
6893: }
6894:
1.26 www 6895: # -------------------------------------------------------- Value of a Condition
6896:
1.713 albertel 6897: # gets the value of a specific preevaluated condition
6898: # stored in the string $env{user.state.<cid>}
6899: # or looks up a condition reference in the bighash and if if hasn't
6900: # already been evaluated recurses into docondval to get the value of
6901: # the condition, then memoizing it to
6902: # $env{user.state.<cid>.<condition>}
1.40 www 6903: sub directcondval {
6904: my $number=shift;
1.620 albertel 6905: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6906: &Apache::lonuserstate::evalstate();
6907: }
1.713 albertel 6908: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6909: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6910: } elsif ($number =~ /^_/) {
6911: my $sub_condition;
6912: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6913: &GDBM_READER(),0640)) {
6914: $sub_condition=$bighash{'conditions'.$number};
6915: untie(%bighash);
6916: }
6917: my $value = &docondval($sub_condition);
1.949 raeburn 6918: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6919: return $value;
6920: }
1.620 albertel 6921: if ($env{'user.state.'.$env{'request.course.id'}}) {
6922: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6923: } else {
6924: return 2;
6925: }
6926: }
6927:
1.713 albertel 6928: # get the collection of conditions for this resource
1.26 www 6929: sub condval {
6930: my $condidx=shift;
1.54 www 6931: my $allpathcond='';
1.713 albertel 6932: foreach my $cond (split(/\|/,$condidx)) {
6933: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6934: $allpathcond.=
6935: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6936: }
1.191 harris41 6937: }
1.54 www 6938: $allpathcond=~s/\|$//;
1.713 albertel 6939: return &docondval($allpathcond);
6940: }
6941:
6942: #evaluates an expression of conditions
6943: sub docondval {
6944: my ($allpathcond) = @_;
6945: my $result=0;
6946: if ($env{'request.course.id'}
6947: && defined($allpathcond)) {
6948: my $operand='|';
6949: my @stack;
6950: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6951: if ($chunk eq '(') {
6952: push @stack,($operand,$result);
6953: } elsif ($chunk eq ')') {
6954: my $before=pop @stack;
6955: if (pop @stack eq '&') {
6956: $result=$result>$before?$before:$result;
6957: } else {
6958: $result=$result>$before?$result:$before;
6959: }
6960: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6961: $operand=$chunk;
6962: } else {
6963: my $new=directcondval($chunk);
6964: if ($operand eq '&') {
6965: $result=$result>$new?$new:$result;
6966: } else {
6967: $result=$result>$new?$result:$new;
6968: }
6969: }
6970: }
1.26 www 6971: }
6972: return $result;
1.421 albertel 6973: }
6974:
6975: # ---------------------------------------------------- Devalidate courseresdata
6976:
6977: sub devalidatecourseresdata {
6978: my ($coursenum,$coursedomain)=@_;
6979: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6980: &devalidate_cache_new('courseres',$hashid);
1.28 www 6981: }
6982:
1.763 www 6983:
1.200 www 6984: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6985: #
6986: # Parameters:
6987: # $coursenum - Number of the course.
6988: # $coursedomain - Domain at which the course was created.
6989: # Returns:
6990: # A hash of the course parameters along (I think) with timestamps
6991: # and version info.
1.877 foxr 6992:
1.624 albertel 6993: sub get_courseresdata {
6994: my ($coursenum,$coursedomain)=@_;
1.200 www 6995: my $coursehom=&homeserver($coursenum,$coursedomain);
6996: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6997: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6998: my %dumpreply;
1.417 albertel 6999: unless (defined($cached)) {
1.624 albertel 7000: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7001: $result=\%dumpreply;
1.251 albertel 7002: my ($tmp) = keys(%dumpreply);
7003: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7004: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7005: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7006: return $tmp;
1.416 albertel 7007: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7008: $result=undef;
1.599 albertel 7009: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7010: }
7011: }
1.624 albertel 7012: return $result;
7013: }
7014:
1.633 albertel 7015: sub devalidateuserresdata {
7016: my ($uname,$udom)=@_;
7017: my $hashid="$udom:$uname";
7018: &devalidate_cache_new('userres',$hashid);
7019: }
7020:
1.624 albertel 7021: sub get_userresdata {
7022: my ($uname,$udom)=@_;
7023: #most student don\'t have any data set, check if there is some data
7024: if (&EXT_cache_status($udom,$uname)) { return undef; }
7025:
7026: my $hashid="$udom:$uname";
7027: my ($result,$cached)=&is_cached_new('userres',$hashid);
7028: if (!defined($cached)) {
7029: my %resourcedata=&dump('resourcedata',$udom,$uname);
7030: $result=\%resourcedata;
7031: &do_cache_new('userres',$hashid,$result,600);
7032: }
7033: my ($tmp)=keys(%$result);
7034: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7035: return $result;
7036: }
7037: #error 2 occurs when the .db doesn't exist
7038: if ($tmp!~/error: 2 /) {
1.672 albertel 7039: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7040: " Trying to get resource data for ".
7041: $uname." at ".$udom.": ".
7042: $tmp."</font>");
7043: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7044: #&EXT_cache_set($udom,$uname);
7045: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7046: undef($tmp); # not really an error so don't send it back
1.624 albertel 7047: }
7048: return $tmp;
7049: }
1.879 foxr 7050: #----------------------------------------------- resdata - return resource data
7051: # Purpose:
7052: # Return resource data for either users or for a course.
7053: # Parameters:
7054: # $name - Course/user name.
7055: # $domain - Name of the domain the user/course is registered on.
7056: # $type - Type of thing $name is (must be 'course' or 'user'
7057: # @which - Array of names of resources desired.
7058: # Returns:
7059: # The value of the first reasource in @which that is found in the
7060: # resource hash.
7061: # Exceptional Conditions:
7062: # If the $type passed in is not valid (not the string 'course' or
7063: # 'user', an undefined reference is returned.
7064: # If none of the resources are found, an undef is returned
1.624 albertel 7065: sub resdata {
7066: my ($name,$domain,$type,@which)=@_;
7067: my $result;
7068: if ($type eq 'course') {
7069: $result=&get_courseresdata($name,$domain);
7070: } elsif ($type eq 'user') {
7071: $result=&get_userresdata($name,$domain);
7072: }
7073: if (!ref($result)) { return $result; }
1.251 albertel 7074: foreach my $item (@which) {
1.927 albertel 7075: if (defined($result->{$item->[0]})) {
7076: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7077: }
1.250 albertel 7078: }
1.291 albertel 7079: return undef;
1.200 www 7080: }
7081:
1.379 matthew 7082: #
7083: # EXT resource caching routines
7084: #
7085:
7086: sub clear_EXT_cache_status {
1.383 albertel 7087: &delenv('cache.EXT.');
1.379 matthew 7088: }
7089:
7090: sub EXT_cache_status {
7091: my ($target_domain,$target_user) = @_;
1.383 albertel 7092: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7093: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7094: # We know already the user has no data
7095: return 1;
7096: } else {
7097: return 0;
7098: }
7099: }
7100:
7101: sub EXT_cache_set {
7102: my ($target_domain,$target_user) = @_;
1.383 albertel 7103: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7104: #&appenv({$cachename => time});
1.379 matthew 7105: }
7106:
1.28 www 7107: # --------------------------------------------------------- Value of a Variable
1.58 www 7108: sub EXT {
1.715 albertel 7109:
1.395 albertel 7110: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7111: unless ($varname) { return ''; }
1.218 albertel 7112: #get real user name/domain, courseid and symb
7113: my $courseid;
1.359 albertel 7114: my $publicuser;
1.427 www 7115: if ($symbparm) {
7116: $symbparm=&get_symb_from_alias($symbparm);
7117: }
1.218 albertel 7118: if (!($uname && $udom)) {
1.790 albertel 7119: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7120: if (!$symbparm) { $symbparm=$cursymb; }
7121: } else {
1.620 albertel 7122: $courseid=$env{'request.course.id'};
1.218 albertel 7123: }
1.48 www 7124: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7125: my $rest;
1.320 albertel 7126: if (defined($therest[0])) {
1.48 www 7127: $rest=join('.',@therest);
7128: } else {
7129: $rest='';
7130: }
1.320 albertel 7131:
1.57 www 7132: my $qualifierrest=$qualifier;
7133: if ($rest) { $qualifierrest.='.'.$rest; }
7134: my $spacequalifierrest=$space;
7135: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7136: if ($realm eq 'user') {
1.48 www 7137: # --------------------------------------------------------------- user.resource
7138: if ($space eq 'resource') {
1.651 albertel 7139: if ( (defined($Apache::lonhomework::parsing_a_problem)
7140: || defined($Apache::lonhomework::parsing_a_task))
7141: &&
1.744 albertel 7142: ($symbparm eq &symbread()) ) {
7143: # if we are in the middle of processing the resource the
7144: # get the value we are planning on committing
7145: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7146: return $Apache::lonhomework::results{$qualifierrest};
7147: } else {
7148: return $Apache::lonhomework::history{$qualifierrest};
7149: }
1.335 albertel 7150: } else {
1.359 albertel 7151: my %restored;
1.620 albertel 7152: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7153: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7154: } else {
7155: %restored=&restore($symbparm,$courseid,$udom,$uname);
7156: }
1.335 albertel 7157: return $restored{$qualifierrest};
7158: }
1.48 www 7159: # ----------------------------------------------------------------- user.access
7160: } elsif ($space eq 'access') {
1.218 albertel 7161: # FIXME - not supporting calls for a specific user
1.48 www 7162: return &allowed($qualifier,$rest);
7163: # ------------------------------------------ user.preferences, user.environment
7164: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7165: if (($uname eq $env{'user.name'}) &&
7166: ($udom eq $env{'user.domain'})) {
7167: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7168: } else {
1.359 albertel 7169: my %returnhash;
7170: if (!$publicuser) {
7171: %returnhash=&userenvironment($udom,$uname,
7172: $qualifierrest);
7173: }
1.218 albertel 7174: return $returnhash{$qualifierrest};
7175: }
1.48 www 7176: # ----------------------------------------------------------------- user.course
7177: } elsif ($space eq 'course') {
1.218 albertel 7178: # FIXME - not supporting calls for a specific user
1.620 albertel 7179: return $env{join('.',('request.course',$qualifier))};
1.48 www 7180: # ------------------------------------------------------------------- user.role
7181: } elsif ($space eq 'role') {
1.218 albertel 7182: # FIXME - not supporting calls for a specific user
1.620 albertel 7183: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7184: if ($qualifier eq 'value') {
7185: return $role;
7186: } elsif ($qualifier eq 'extent') {
7187: return $where;
7188: }
7189: # ----------------------------------------------------------------- user.domain
7190: } elsif ($space eq 'domain') {
1.218 albertel 7191: return $udom;
1.48 www 7192: # ------------------------------------------------------------------- user.name
7193: } elsif ($space eq 'name') {
1.218 albertel 7194: return $uname;
1.48 www 7195: # ---------------------------------------------------- Any other user namespace
1.29 www 7196: } else {
1.359 albertel 7197: my %reply;
7198: if (!$publicuser) {
7199: %reply=&get($space,[$qualifierrest],$udom,$uname);
7200: }
7201: return $reply{$qualifierrest};
1.48 www 7202: }
1.236 www 7203: } elsif ($realm eq 'query') {
7204: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7205: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7206: [$spacequalifierrest]);
1.620 albertel 7207: return $env{'form.'.$spacequalifierrest};
1.236 www 7208: } elsif ($realm eq 'request') {
1.48 www 7209: # ------------------------------------------------------------- request.browser
7210: if ($space eq 'browser') {
1.430 www 7211: if ($qualifier eq 'textremote') {
1.676 albertel 7212: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7213: return 1;
7214: } else {
7215: return 0;
7216: }
7217: } else {
1.620 albertel 7218: return $env{'browser.'.$qualifier};
1.430 www 7219: }
1.57 www 7220: # ------------------------------------------------------------ request.filename
7221: } else {
1.620 albertel 7222: return $env{'request.'.$spacequalifierrest};
1.29 www 7223: }
1.28 www 7224: } elsif ($realm eq 'course') {
1.48 www 7225: # ---------------------------------------------------------- course.description
1.620 albertel 7226: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7227: } elsif ($realm eq 'resource') {
1.165 www 7228:
1.620 albertel 7229: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7230: if (!$symbparm) { $symbparm=&symbread(); }
7231: }
1.693 albertel 7232:
7233: if ($space eq 'title') {
7234: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7235: return &gettitle($symbparm);
7236: }
7237:
7238: if ($space eq 'map') {
7239: my ($map) = &decode_symb($symbparm);
7240: return &symbread($map);
7241: }
1.905 albertel 7242: if ($space eq 'filename') {
7243: if ($symbparm) {
7244: return &clutter((&decode_symb($symbparm))[2]);
7245: }
7246: return &hreflocation('',$env{'request.filename'});
7247: }
1.693 albertel 7248:
7249: my ($section, $group, @groups);
1.593 albertel 7250: my ($courselevelm,$courselevel);
1.539 albertel 7251: if ($symbparm && defined($courseid) &&
1.620 albertel 7252: $courseid eq $env{'request.course.id'}) {
1.165 www 7253:
1.218 albertel 7254: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7255:
1.60 www 7256: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7257: my $symbp=$symbparm;
1.735 albertel 7258: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7259:
7260: my $symbparm=$symbp.'.'.$spacequalifierrest;
7261: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7262:
1.620 albertel 7263: if (($env{'user.name'} eq $uname) &&
7264: ($env{'user.domain'} eq $udom)) {
7265: $section=$env{'request.course.sec'};
1.733 raeburn 7266: @groups = split(/:/,$env{'request.course.groups'});
7267: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7268: } else {
1.539 albertel 7269: if (! defined($usection)) {
1.551 albertel 7270: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7271: } else {
7272: $section = $usection;
7273: }
1.733 raeburn 7274: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7275: }
7276:
7277: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7278: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7279: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7280:
1.593 albertel 7281: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7282: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7283: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7284:
1.60 www 7285: # ----------------------------------------------------------- first, check user
1.624 albertel 7286:
7287: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7288: ([$courselevelr,'resource'],
7289: [$courselevelm,'map' ],
7290: [$courselevel, 'course' ]));
1.931 albertel 7291: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7292:
1.594 albertel 7293: # ------------------------------------------------ second, check some of course
1.684 raeburn 7294: my $coursereply;
1.691 raeburn 7295: if (@groups > 0) {
7296: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7297: $mapparm,$spacequalifierrest);
1.927 albertel 7298: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7299: }
1.96 www 7300:
1.684 raeburn 7301: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7302: $env{'course.'.$courseid.'.domain'},
7303: 'course',
7304: ([$seclevelr, 'resource'],
7305: [$seclevelm, 'map' ],
7306: [$seclevel, 'course' ],
7307: [$courselevelr,'resource']));
7308: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7309:
1.60 www 7310: # ------------------------------------------------------ third, check map parms
1.218 albertel 7311: my %parmhash=();
7312: my $thisparm='';
7313: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7314: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7315: &GDBM_READER(),0640)) {
1.218 albertel 7316: $thisparm=$parmhash{$symbparm};
7317: untie(%parmhash);
7318: }
1.927 albertel 7319: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7320: }
1.594 albertel 7321: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7322:
1.218 albertel 7323: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7324: my $filename;
7325: if (!$symbparm) { $symbparm=&symbread(); }
7326: if ($symbparm) {
1.409 www 7327: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7328: } else {
1.620 albertel 7329: $filename=$env{'request.filename'};
1.282 albertel 7330: }
7331: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7332: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7333: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7334: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7335:
1.927 albertel 7336: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7337: if ($symbparm && defined($courseid) &&
1.620 albertel 7338: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7339: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7340: $env{'course.'.$courseid.'.domain'},
7341: 'course',
1.927 albertel 7342: ([$courselevelm,'map' ],
7343: [$courselevel, 'course']));
7344: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7345: }
1.145 www 7346: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7347: unless ($space eq '0') {
1.336 albertel 7348: my @parts=split(/_/,$space);
7349: my $id=pop(@parts);
7350: my $part=join('_',@parts);
7351: if ($part eq '') { $part='0'; }
1.927 albertel 7352: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7353: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7354: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7355: }
1.395 albertel 7356: if ($recurse) { return undef; }
7357: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7358: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7359: # ---------------------------------------------------- Any other user namespace
7360: } elsif ($realm eq 'environment') {
7361: # ----------------------------------------------------------------- environment
1.620 albertel 7362: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7363: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7364: } else {
1.770 albertel 7365: if ($uname eq 'anonymous' && $udom eq '') {
7366: return '';
7367: }
1.219 albertel 7368: my %returnhash=&userenvironment($udom,$uname,
7369: $spacequalifierrest);
7370: return $returnhash{$spacequalifierrest};
7371: }
1.28 www 7372: } elsif ($realm eq 'system') {
1.48 www 7373: # ----------------------------------------------------------------- system.time
7374: if ($space eq 'time') {
7375: return time;
7376: }
1.696 albertel 7377: } elsif ($realm eq 'server') {
7378: # ----------------------------------------------------------------- system.time
7379: if ($space eq 'name') {
7380: return $ENV{'SERVER_NAME'};
7381: }
1.28 www 7382: }
1.48 www 7383: return '';
1.61 www 7384: }
7385:
1.927 albertel 7386: sub get_reply {
7387: my ($reply_value) = @_;
1.940 raeburn 7388: if (ref($reply_value) eq 'ARRAY') {
7389: if (wantarray) {
7390: return @$reply_value;
7391: }
7392: return $reply_value->[0];
7393: } else {
7394: return $reply_value;
1.927 albertel 7395: }
7396: }
7397:
1.691 raeburn 7398: sub check_group_parms {
7399: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7400: my @groupitems = ();
7401: my $resultitem;
1.927 albertel 7402: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7403: foreach my $group (@{$groups}) {
7404: foreach my $level (@levels) {
1.927 albertel 7405: my $item = $courseid.'.['.$group.'].'.$level->[0];
7406: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7407: }
7408: }
7409: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7410: $env{'course.'.$courseid.'.domain'},
7411: 'course',@groupitems);
7412: return $coursereply;
7413: }
7414:
7415: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7416: my ($courseid,@groups) = @_;
7417: @groups = sort(@groups);
1.691 raeburn 7418: return @groups;
7419: }
7420:
1.395 albertel 7421: sub packages_tab_default {
7422: my ($uri,$varname)=@_;
7423: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7424:
7425: my (@extension,@specifics,$do_default);
7426: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7427: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7428: if ($pack_type eq 'default') {
7429: $do_default=1;
7430: } elsif ($pack_type eq 'extension') {
7431: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7432: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7433: # only look at packages defaults for packages that this id is
1.738 albertel 7434: push(@specifics,[$package,$pack_type,$pack_part]);
7435: }
7436: }
7437: # first look for a package that matches the requested part id
7438: foreach my $package (@specifics) {
7439: my (undef,$pack_type,$pack_part)=@{$package};
7440: next if ($pack_part ne $part);
7441: if (defined($packagetab{"$pack_type&$name&default"})) {
7442: return $packagetab{"$pack_type&$name&default"};
7443: }
7444: }
7445: # look for any possible matching non extension_ package
7446: foreach my $package (@specifics) {
7447: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7448: if (defined($packagetab{"$pack_type&$name&default"})) {
7449: return $packagetab{"$pack_type&$name&default"};
7450: }
1.585 albertel 7451: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7452: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7453: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7454: }
7455: }
1.738 albertel 7456: # look for any posible extension_ match
7457: foreach my $package (@extension) {
7458: my ($package,$pack_type)=@{$package};
7459: if (defined($packagetab{"$pack_type&$name&default"})) {
7460: return $packagetab{"$pack_type&$name&default"};
7461: }
7462: if (defined($packagetab{$package."&$name&default"})) {
7463: return $packagetab{$package."&$name&default"};
7464: }
7465: }
7466: # look for a global default setting
7467: if ($do_default && defined($packagetab{"default&$name&default"})) {
7468: return $packagetab{"default&$name&default"};
7469: }
1.395 albertel 7470: return undef;
7471: }
7472:
1.334 albertel 7473: sub add_prefix_and_part {
7474: my ($prefix,$part)=@_;
7475: my $keyroot;
7476: if (defined($prefix) && $prefix !~ /^__/) {
7477: # prefix that has a part already
7478: $keyroot=$prefix;
7479: } elsif (defined($prefix)) {
7480: # prefix that is missing a part
7481: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7482: } else {
7483: # no prefix at all
7484: if (defined($part)) { $keyroot='_'.$part; }
7485: }
7486: return $keyroot;
7487: }
7488:
1.71 www 7489: # ---------------------------------------------------------------- Get metadata
7490:
1.599 albertel 7491: my %metaentry;
1.71 www 7492: sub metadata {
1.176 www 7493: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7494: $uri=&declutter($uri);
1.288 albertel 7495: # if it is a non metadata possible uri return quickly
1.529 albertel 7496: if (($uri eq '') ||
7497: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7498: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7499: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7500: return undef;
7501: }
7502: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7503: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7504: return undef;
1.288 albertel 7505: }
1.73 www 7506: my $filename=$uri;
7507: $uri=~s/\.meta$//;
1.172 www 7508: #
7509: # Is the metadata already cached?
1.177 www 7510: # Look at timestamp of caching
1.172 www 7511: # Everything is cached by the main uri, libraries are never directly cached
7512: #
1.428 albertel 7513: if (!defined($liburi)) {
1.599 albertel 7514: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7515: if (defined($cached)) { return $result->{':'.$what}; }
7516: }
7517: {
1.172 www 7518: #
7519: # Is this a recursive call for a library?
7520: #
1.599 albertel 7521: # if (! exists($metacache{$uri})) {
7522: # $metacache{$uri}={};
7523: # }
1.924 albertel 7524: my $cachetime = 60*60;
1.171 www 7525: if ($liburi) {
7526: $liburi=&declutter($liburi);
7527: $filename=$liburi;
1.401 bowersj2 7528: } else {
1.599 albertel 7529: &devalidate_cache_new('meta',$uri);
7530: undef(%metaentry);
1.401 bowersj2 7531: }
1.140 www 7532: my %metathesekeys=();
1.73 www 7533: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7534: my $metastring;
1.924 albertel 7535: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7536: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7537: $metastring =
1.929 albertel 7538: &Apache::lonnet::ssi_body($which,
1.924 albertel 7539: ('grade_target' => 'meta'));
7540: $cachetime = 1; # only want this cached in the child not long term
7541: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7542: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7543: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7544: $metastring=&getfile($file);
1.489 albertel 7545: }
1.208 albertel 7546: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7547: my $token;
1.140 www 7548: undef %metathesekeys;
1.71 www 7549: while ($token=$parser->get_token) {
1.339 albertel 7550: if ($token->[0] eq 'S') {
7551: if (defined($token->[2]->{'package'})) {
1.172 www 7552: #
7553: # This is a package - get package info
7554: #
1.339 albertel 7555: my $package=$token->[2]->{'package'};
7556: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7557: if (defined($token->[2]->{'id'})) {
7558: $keyroot.='_'.$token->[2]->{'id'};
7559: }
1.599 albertel 7560: if ($metaentry{':packages'}) {
7561: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7562: } else {
1.599 albertel 7563: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7564: }
1.736 albertel 7565: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7566: my $part=$keyroot;
7567: $part=~s/^\_//;
1.736 albertel 7568: if ($pack_entry=~/^\Q$package\E\&/ ||
7569: $pack_entry=~/^\Q$package\E_0\&/) {
7570: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7571: # ignore package.tab specified default values
7572: # here &package_tab_default() will fetch those
7573: if ($subp eq 'default') { next; }
1.736 albertel 7574: my $value=$packagetab{$pack_entry};
1.432 albertel 7575: my $unikey;
7576: if ($pack =~ /_0$/) {
7577: $unikey='parameter_0_'.$name;
7578: $part=0;
7579: } else {
7580: $unikey='parameter'.$keyroot.'_'.$name;
7581: }
1.339 albertel 7582: if ($subp eq 'display') {
7583: $value.=' [Part: '.$part.']';
7584: }
1.599 albertel 7585: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7586: $metathesekeys{$unikey}=1;
1.599 albertel 7587: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7588: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7589: }
1.599 albertel 7590: if (defined($metaentry{':'.$unikey.'.default'})) {
7591: $metaentry{':'.$unikey}=
7592: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7593: }
1.339 albertel 7594: }
7595: }
7596: } else {
1.172 www 7597: #
7598: # This is not a package - some other kind of start tag
1.339 albertel 7599: #
7600: my $entry=$token->[1];
7601: my $unikey;
7602: if ($entry eq 'import') {
7603: $unikey='';
7604: } else {
7605: $unikey=$entry;
7606: }
7607: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7608:
7609: if (defined($token->[2]->{'id'})) {
7610: $unikey.='_'.$token->[2]->{'id'};
7611: }
1.175 www 7612:
1.339 albertel 7613: if ($entry eq 'import') {
1.175 www 7614: #
7615: # Importing a library here
1.339 albertel 7616: #
7617: if ($depthcount<20) {
7618: my $location=$parser->get_text('/import');
7619: my $dir=$filename;
7620: $dir=~s|[^/]*$||;
7621: $location=&filelocation($dir,$location);
1.736 albertel 7622: my $metadata =
7623: &metadata($uri,'keys', $location,$unikey,
7624: $depthcount+1);
7625: foreach my $meta (split(',',$metadata)) {
7626: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7627: $metathesekeys{$meta}=1;
1.339 albertel 7628: }
7629: }
7630: } else {
7631:
7632: if (defined($token->[2]->{'name'})) {
7633: $unikey.='_'.$token->[2]->{'name'};
7634: }
7635: $metathesekeys{$unikey}=1;
1.736 albertel 7636: foreach my $param (@{$token->[3]}) {
7637: $metaentry{':'.$unikey.'.'.$param} =
7638: $token->[2]->{$param};
1.339 albertel 7639: }
7640: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7641: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7642: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7643: # only ws inside the tag, and not in default, so use default
7644: # as value
1.599 albertel 7645: $metaentry{':'.$unikey}=$default;
1.908 albertel 7646: } elsif ( $internaltext =~ /\S/ ) {
7647: # something interesting inside the tag
7648: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7649: } else {
1.908 albertel 7650: # no interesting values, don't set a default
1.339 albertel 7651: }
1.172 www 7652: # end of not-a-package not-a-library import
1.339 albertel 7653: }
1.172 www 7654: # end of not-a-package start tag
1.339 albertel 7655: }
1.172 www 7656: # the next is the end of "start tag"
1.339 albertel 7657: }
7658: }
1.483 albertel 7659: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7660: $extension = lc($extension);
7661: if ($extension eq 'htm') { $extension='html'; }
7662:
1.737 albertel 7663: foreach my $key (keys(%packagetab)) {
1.483 albertel 7664: #no specific packages #how's our extension
7665: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7666: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7667: \%metathesekeys);
7668: }
1.883 albertel 7669:
7670: if (!exists($metaentry{':packages'})
7671: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7672: foreach my $key (keys(%packagetab)) {
1.483 albertel 7673: #no specific packages well let's get default then
7674: if ($key!~/^default&/) { next; }
1.488 albertel 7675: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7676: \%metathesekeys);
7677: }
7678: }
1.338 www 7679: # are there custom rights to evaluate
1.599 albertel 7680: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7681:
1.338 www 7682: #
7683: # Importing a rights file here
1.339 albertel 7684: #
7685: unless ($depthcount) {
1.599 albertel 7686: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7687: my $dir=$filename;
7688: $dir=~s|[^/]*$||;
7689: $location=&filelocation($dir,$location);
1.736 albertel 7690: my $rights_metadata =
7691: &metadata($uri,'keys',$location,'_rights',
7692: $depthcount+1);
7693: foreach my $rights (split(',',$rights_metadata)) {
7694: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7695: $metathesekeys{$rights}=1;
1.339 albertel 7696: }
7697: }
7698: }
1.737 albertel 7699: # uniqifiy package listing
7700: my %seen;
7701: my @uniq_packages =
7702: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7703: $metaentry{':packages'} = join(',',@uniq_packages);
7704:
7705: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7706: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7707: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7708: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7709: # this is the end of "was not already recently cached
1.71 www 7710: }
1.599 albertel 7711: return $metaentry{':'.$what};
1.261 albertel 7712: }
7713:
1.488 albertel 7714: sub metadata_create_package_def {
1.483 albertel 7715: my ($uri,$key,$package,$metathesekeys)=@_;
7716: my ($pack,$name,$subp)=split(/\&/,$key);
7717: if ($subp eq 'default') { next; }
7718:
1.599 albertel 7719: if (defined($metaentry{':packages'})) {
7720: $metaentry{':packages'}.=','.$package;
1.483 albertel 7721: } else {
1.599 albertel 7722: $metaentry{':packages'}=$package;
1.483 albertel 7723: }
7724: my $value=$packagetab{$key};
7725: my $unikey;
7726: $unikey='parameter_0_'.$name;
1.599 albertel 7727: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7728: $$metathesekeys{$unikey}=1;
1.599 albertel 7729: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7730: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7731: }
1.599 albertel 7732: if (defined($metaentry{':'.$unikey.'.default'})) {
7733: $metaentry{':'.$unikey}=
7734: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7735: }
7736: }
7737:
1.261 albertel 7738: sub metadata_generate_part0 {
7739: my ($metadata,$metacache,$uri) = @_;
7740: my %allnames;
1.737 albertel 7741: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7742: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7743: my $part=$$metacache{':'.$metakey.'.part'};
7744: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7745: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7746: $allnames{$name}=$part;
7747: }
7748: }
7749: }
7750: foreach my $name (keys(%allnames)) {
7751: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7752: my $key=":parameter_0_$name";
1.261 albertel 7753: $$metacache{"$key.part"}='0';
7754: $$metacache{"$key.name"}=$name;
1.428 albertel 7755: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7756: $allnames{$name}.'_'.$name.
7757: '.type'};
1.428 albertel 7758: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7759: '.display'};
1.644 www 7760: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7761: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7762: $$metacache{"$key.display"}=$olddis;
7763: }
1.71 www 7764: }
7765:
1.764 albertel 7766: # ------------------------------------------------------ Devalidate title cache
7767:
7768: sub devalidate_title_cache {
7769: my ($url)=@_;
7770: if (!$env{'request.course.id'}) { return; }
7771: my $symb=&symbread($url);
7772: if (!$symb) { return; }
7773: my $key=$env{'request.course.id'}."\0".$symb;
7774: &devalidate_cache_new('title',$key);
7775: }
7776:
1.301 www 7777: # ------------------------------------------------- Get the title of a resource
7778:
7779: sub gettitle {
7780: my $urlsymb=shift;
7781: my $symb=&symbread($urlsymb);
1.534 albertel 7782: if ($symb) {
1.620 albertel 7783: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7784: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7785: if (defined($cached)) {
7786: return $result;
7787: }
1.534 albertel 7788: my ($map,$resid,$url)=&decode_symb($symb);
7789: my $title='';
1.907 albertel 7790: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7791: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7792: } else {
7793: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7794: &GDBM_READER(),0640)) {
7795: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7796: $title=$bighash{'title_'.$mapid.'.'.$resid};
7797: untie(%bighash);
7798: }
1.534 albertel 7799: }
7800: $title=~s/\&colon\;/\:/gs;
7801: if ($title) {
1.599 albertel 7802: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7803: }
7804: $urlsymb=$url;
7805: }
7806: my $title=&metadata($urlsymb,'title');
7807: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7808: return $title;
1.301 www 7809: }
1.613 albertel 7810:
1.614 albertel 7811: sub get_slot {
7812: my ($which,$cnum,$cdom)=@_;
7813: if (!$cnum || !$cdom) {
1.790 albertel 7814: (undef,my $courseid)=&whichuser();
1.620 albertel 7815: $cdom=$env{'course.'.$courseid.'.domain'};
7816: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7817: }
1.703 albertel 7818: my $key=join("\0",'slots',$cdom,$cnum,$which);
7819: my %slotinfo;
7820: if (exists($remembered{$key})) {
7821: $slotinfo{$which} = $remembered{$key};
7822: } else {
7823: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7824: &Apache::lonhomework::showhash(%slotinfo);
7825: my ($tmp)=keys(%slotinfo);
7826: if ($tmp=~/^error:/) { return (); }
7827: $remembered{$key} = $slotinfo{$which};
7828: }
1.616 albertel 7829: if (ref($slotinfo{$which}) eq 'HASH') {
7830: return %{$slotinfo{$which}};
7831: }
7832: return $slotinfo{$which};
1.614 albertel 7833: }
1.31 www 7834: # ------------------------------------------------- Update symbolic store links
7835:
7836: sub symblist {
7837: my ($mapname,%newhash)=@_;
1.438 www 7838: $mapname=&deversion(&declutter($mapname));
1.31 www 7839: my %hash;
1.620 albertel 7840: if (($env{'request.course.fn'}) && (%newhash)) {
7841: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7842: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7843: foreach my $url (keys %newhash) {
7844: next if ($url eq 'last_known'
7845: && $env{'form.no_update_last_known'});
7846: $hash{declutter($url)}=&encode_symb($mapname,
7847: $newhash{$url}->[1],
7848: $newhash{$url}->[0]);
1.191 harris41 7849: }
1.31 www 7850: if (untie(%hash)) {
7851: return 'ok';
7852: }
7853: }
7854: }
7855: return 'error';
1.212 www 7856: }
7857:
7858: # --------------------------------------------------------------- Verify a symb
7859:
7860: sub symbverify {
1.510 www 7861: my ($symb,$thisurl)=@_;
7862: my $thisfn=$thisurl;
1.439 www 7863: $thisfn=&declutter($thisfn);
1.215 www 7864: # direct jump to resource in page or to a sequence - will construct own symbs
7865: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7866: # check URL part
1.409 www 7867: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7868:
1.431 www 7869: unless ($url eq $thisfn) { return 0; }
1.213 www 7870:
1.216 www 7871: $symb=&symbclean($symb);
1.510 www 7872: $thisurl=&deversion($thisurl);
1.439 www 7873: $thisfn=&deversion($thisfn);
1.213 www 7874:
7875: my %bighash;
7876: my $okay=0;
1.431 www 7877:
1.620 albertel 7878: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7879: &GDBM_READER(),0640)) {
1.510 www 7880: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7881: unless ($ids) {
1.510 www 7882: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7883: }
7884: if ($ids) {
7885: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7886: foreach my $id (split(/\,/,$ids)) {
7887: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7888: if (
7889: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7890: eq $symb) {
1.620 albertel 7891: if (($env{'request.role.adv'}) ||
1.800 albertel 7892: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7893: $okay=1;
7894: }
7895: }
1.216 www 7896: }
7897: }
1.213 www 7898: untie(%bighash);
7899: }
7900: return $okay;
1.31 www 7901: }
7902:
1.210 www 7903: # --------------------------------------------------------------- Clean-up symb
7904:
7905: sub symbclean {
7906: my $symb=shift;
1.568 albertel 7907: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7908: # remove version from map
7909: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7910:
1.210 www 7911: # remove version from URL
7912: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7913:
1.507 www 7914: # remove wrapper
7915:
1.510 www 7916: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7917: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7918: return $symb;
1.409 www 7919: }
7920:
7921: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7922:
7923: sub encode_symb {
7924: my ($map,$resid,$url)=@_;
7925: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7926: }
1.409 www 7927:
7928: sub decode_symb {
1.568 albertel 7929: my $symb=shift;
7930: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7931: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7932: return (&fixversion($map),$resid,&fixversion($url));
7933: }
7934:
7935: sub fixversion {
7936: my $fn=shift;
1.609 banghart 7937: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7938: my %bighash;
7939: my $uri=&clutter($fn);
1.620 albertel 7940: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7941: # is this cached?
1.599 albertel 7942: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7943: if (defined($cached)) { return $result; }
7944: # unfortunately not cached, or expired
1.620 albertel 7945: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7946: &GDBM_READER(),0640)) {
7947: if ($bighash{'version_'.$uri}) {
7948: my $version=$bighash{'version_'.$uri};
1.444 www 7949: unless (($version eq 'mostrecent') ||
7950: ($version==&getversion($uri))) {
1.440 www 7951: $uri=~s/\.(\w+)$/\.$version\.$1/;
7952: }
7953: }
7954: untie %bighash;
1.413 www 7955: }
1.599 albertel 7956: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7957: }
7958:
7959: sub deversion {
7960: my $url=shift;
7961: $url=~s/\.\d+\.(\w+)$/\.$1/;
7962: return $url;
1.210 www 7963: }
7964:
1.31 www 7965: # ------------------------------------------------------ Return symb list entry
7966:
7967: sub symbread {
1.249 www 7968: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7969: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7970: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7971: # no filename provided? try from environment
1.44 www 7972: unless ($thisfn) {
1.620 albertel 7973: if ($env{'request.symb'}) {
7974: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7975: }
1.620 albertel 7976: $thisfn=$env{'request.filename'};
1.44 www 7977: }
1.569 albertel 7978: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7979: # is that filename actually a symb? Verify, clean, and return
7980: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7981: if (&symbverify($thisfn,$1)) {
1.620 albertel 7982: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7983: }
1.242 www 7984: }
1.44 www 7985: $thisfn=declutter($thisfn);
1.31 www 7986: my %hash;
1.37 www 7987: my %bighash;
7988: my $syval='';
1.620 albertel 7989: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7990: my $targetfn = $thisfn;
1.609 banghart 7991: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7992: $targetfn = 'adm/wrapper/'.$thisfn;
7993: }
1.687 albertel 7994: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7995: $targetfn=$1;
7996: }
1.620 albertel 7997: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7998: &GDBM_READER(),0640)) {
1.481 raeburn 7999: $syval=$hash{$targetfn};
1.37 www 8000: untie(%hash);
8001: }
8002: # ---------------------------------------------------------- There was an entry
8003: if ($syval) {
1.601 albertel 8004: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8005: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8006: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8007: #return $env{$cache_str}='';
1.601 albertel 8008: #}
8009: #$syval.=$1;
8010: #}
1.37 www 8011: } else {
8012: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8013: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8014: &GDBM_READER(),0640)) {
1.37 www 8015: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8016: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8017: unless ($ids) {
8018: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8019: }
8020: unless ($ids) {
8021: # alias?
8022: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8023: }
1.37 www 8024: if ($ids) {
8025: # ------------------------------------------------------------------- Has ID(s)
8026: my @possibilities=split(/\,/,$ids);
1.39 www 8027: if ($#possibilities==0) {
8028: # ----------------------------------------------- There is only one possibility
1.37 www 8029: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8030: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8031: $resid,$thisfn);
1.249 www 8032: } elsif (!$donotrecurse) {
1.39 www 8033: # ------------------------------------------ There is more than one possibility
8034: my $realpossible=0;
1.800 albertel 8035: foreach my $id (@possibilities) {
8036: my $file=$bighash{'src_'.$id};
1.39 www 8037: if (&allowed('bre',$file)) {
1.800 albertel 8038: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8039: if ($bighash{'map_type_'.$mapid} ne 'page') {
8040: $realpossible++;
1.626 albertel 8041: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8042: $resid,$thisfn);
1.39 www 8043: }
8044: }
1.191 harris41 8045: }
1.39 www 8046: if ($realpossible!=1) { $syval=''; }
1.249 www 8047: } else {
8048: $syval='';
1.37 www 8049: }
8050: }
8051: untie(%bighash)
1.481 raeburn 8052: }
1.31 www 8053: }
1.62 www 8054: if ($syval) {
1.620 albertel 8055: return $env{$cache_str}=$syval;
1.62 www 8056: }
1.31 www 8057: }
1.949 raeburn 8058: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8059: return $env{$cache_str}='';
1.31 www 8060: }
8061:
8062: # ---------------------------------------------------------- Return random seed
8063:
1.32 www 8064: sub numval {
8065: my $txt=shift;
8066: $txt=~tr/A-J/0-9/;
8067: $txt=~tr/a-j/0-9/;
8068: $txt=~tr/K-T/0-9/;
8069: $txt=~tr/k-t/0-9/;
8070: $txt=~tr/U-Z/0-5/;
8071: $txt=~tr/u-z/0-5/;
8072: $txt=~s/\D//g;
1.564 albertel 8073: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8074: return int($txt);
1.368 albertel 8075: }
8076:
1.484 albertel 8077: sub numval2 {
8078: my $txt=shift;
8079: $txt=~tr/A-J/0-9/;
8080: $txt=~tr/a-j/0-9/;
8081: $txt=~tr/K-T/0-9/;
8082: $txt=~tr/k-t/0-9/;
8083: $txt=~tr/U-Z/0-5/;
8084: $txt=~tr/u-z/0-5/;
8085: $txt=~s/\D//g;
8086: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8087: my $total;
8088: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8089: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8090: return int($total);
8091: }
8092:
1.575 albertel 8093: sub numval3 {
8094: use integer;
8095: my $txt=shift;
8096: $txt=~tr/A-J/0-9/;
8097: $txt=~tr/a-j/0-9/;
8098: $txt=~tr/K-T/0-9/;
8099: $txt=~tr/k-t/0-9/;
8100: $txt=~tr/U-Z/0-5/;
8101: $txt=~tr/u-z/0-5/;
8102: $txt=~s/\D//g;
8103: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8104: my $total;
8105: foreach my $val (@txts) { $total+=$val; }
8106: if ($_64bit) { $total=(($total<<32)>>32); }
8107: return $total;
8108: }
8109:
1.675 albertel 8110: sub digest {
8111: my ($data)=@_;
8112: my $digest=&Digest::MD5::md5($data);
8113: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8114: my ($e,$f);
8115: {
8116: use integer;
8117: $e=($a+$b);
8118: $f=($c+$d);
8119: if ($_64bit) {
8120: $e=(($e<<32)>>32);
8121: $f=(($f<<32)>>32);
8122: }
8123: }
8124: if (wantarray) {
8125: return ($e,$f);
8126: } else {
8127: my $g;
8128: {
8129: use integer;
8130: $g=($e+$f);
8131: if ($_64bit) {
8132: $g=(($g<<32)>>32);
8133: }
8134: }
8135: return $g;
8136: }
8137: }
8138:
1.368 albertel 8139: sub latest_rnd_algorithm_id {
1.675 albertel 8140: return '64bit5';
1.366 albertel 8141: }
1.32 www 8142:
1.503 albertel 8143: sub get_rand_alg {
8144: my ($courseid)=@_;
1.790 albertel 8145: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8146: if ($courseid) {
1.620 albertel 8147: return $env{"course.$courseid.rndseed"};
1.503 albertel 8148: }
8149: return &latest_rnd_algorithm_id();
8150: }
8151:
1.562 albertel 8152: sub validCODE {
8153: my ($CODE)=@_;
8154: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8155: return 0;
8156: }
8157:
1.491 albertel 8158: sub getCODE {
1.620 albertel 8159: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8160: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8161: defined($Apache::lonhomework::parsing_a_task) ) &&
8162: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8163: return $Apache::lonhomework::history{'resource.CODE'};
8164: }
8165: return undef;
8166: }
8167:
1.31 www 8168: sub rndseed {
1.155 albertel 8169: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8170: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8171: if (!defined($symb)) {
1.366 albertel 8172: unless ($symb=$wsymb) { return time; }
8173: }
8174: if (!$courseid) { $courseid=$wcourseid; }
8175: if (!$domain) { $domain=$wdomain; }
8176: if (!$username) { $username=$wusername }
1.503 albertel 8177: my $which=&get_rand_alg();
1.803 albertel 8178:
1.491 albertel 8179: if (defined(&getCODE())) {
1.675 albertel 8180: if ($which eq '64bit5') {
8181: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8182: } elsif ($which eq '64bit4') {
1.575 albertel 8183: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8184: } else {
8185: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8186: }
1.675 albertel 8187: } elsif ($which eq '64bit5') {
8188: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8189: } elsif ($which eq '64bit4') {
8190: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8191: } elsif ($which eq '64bit3') {
8192: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8193: } elsif ($which eq '64bit2') {
8194: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8195: } elsif ($which eq '64bit') {
8196: return &rndseed_64bit($symb,$courseid,$domain,$username);
8197: }
8198: return &rndseed_32bit($symb,$courseid,$domain,$username);
8199: }
8200:
8201: sub rndseed_32bit {
8202: my ($symb,$courseid,$domain,$username)=@_;
8203: {
8204: use integer;
8205: my $symbchck=unpack("%32C*",$symb) << 27;
8206: my $symbseed=numval($symb) << 22;
8207: my $namechck=unpack("%32C*",$username) << 17;
8208: my $nameseed=numval($username) << 12;
8209: my $domainseed=unpack("%32C*",$domain) << 7;
8210: my $courseseed=unpack("%32C*",$courseid);
8211: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8212: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8213: #&logthis("rndseed :$num:$symb");
1.564 albertel 8214: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8215: return $num;
8216: }
8217: }
8218:
8219: sub rndseed_64bit {
8220: my ($symb,$courseid,$domain,$username)=@_;
8221: {
8222: use integer;
8223: my $symbchck=unpack("%32S*",$symb) << 21;
8224: my $symbseed=numval($symb) << 10;
8225: my $namechck=unpack("%32S*",$username);
8226:
8227: my $nameseed=numval($username) << 21;
8228: my $domainseed=unpack("%32S*",$domain) << 10;
8229: my $courseseed=unpack("%32S*",$courseid);
8230:
8231: my $num1=$symbchck+$symbseed+$namechck;
8232: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8233: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8234: #&logthis("rndseed :$num:$symb");
1.564 albertel 8235: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8236: return "$num1,$num2";
1.155 albertel 8237: }
1.366 albertel 8238: }
8239:
1.443 albertel 8240: sub rndseed_64bit2 {
8241: my ($symb,$courseid,$domain,$username)=@_;
8242: {
8243: use integer;
8244: # strings need to be an even # of cahracters long, it it is odd the
8245: # last characters gets thrown away
8246: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8247: my $symbseed=numval($symb) << 10;
8248: my $namechck=unpack("%32S*",$username.' ');
8249:
8250: my $nameseed=numval($username) << 21;
1.501 albertel 8251: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8252: my $courseseed=unpack("%32S*",$courseid.' ');
8253:
8254: my $num1=$symbchck+$symbseed+$namechck;
8255: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8256: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8257: #&logthis("rndseed :$num:$symb");
1.803 albertel 8258: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8259: return "$num1,$num2";
8260: }
8261: }
8262:
8263: sub rndseed_64bit3 {
8264: my ($symb,$courseid,$domain,$username)=@_;
8265: {
8266: use integer;
8267: # strings need to be an even # of cahracters long, it it is odd the
8268: # last characters gets thrown away
8269: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8270: my $symbseed=numval2($symb) << 10;
8271: my $namechck=unpack("%32S*",$username.' ');
8272:
8273: my $nameseed=numval2($username) << 21;
1.443 albertel 8274: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8275: my $courseseed=unpack("%32S*",$courseid.' ');
8276:
8277: my $num1=$symbchck+$symbseed+$namechck;
8278: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8279: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8280: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8281: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8282:
1.503 albertel 8283: return "$num1:$num2";
1.443 albertel 8284: }
8285: }
8286:
1.575 albertel 8287: sub rndseed_64bit4 {
8288: my ($symb,$courseid,$domain,$username)=@_;
8289: {
8290: use integer;
8291: # strings need to be an even # of cahracters long, it it is odd the
8292: # last characters gets thrown away
8293: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8294: my $symbseed=numval3($symb) << 10;
8295: my $namechck=unpack("%32S*",$username.' ');
8296:
8297: my $nameseed=numval3($username) << 21;
8298: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8299: my $courseseed=unpack("%32S*",$courseid.' ');
8300:
8301: my $num1=$symbchck+$symbseed+$namechck;
8302: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8303: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8304: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8305: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8306:
8307: return "$num1:$num2";
8308: }
8309: }
8310:
1.675 albertel 8311: sub rndseed_64bit5 {
8312: my ($symb,$courseid,$domain,$username)=@_;
8313: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8314: return "$num1:$num2";
8315: }
8316:
1.366 albertel 8317: sub rndseed_CODE_64bit {
8318: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8319: {
1.366 albertel 8320: use integer;
1.443 albertel 8321: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8322: my $symbseed=numval2($symb);
1.491 albertel 8323: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8324: my $CODEseed=numval(&getCODE());
1.443 albertel 8325: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8326: my $num1=$symbseed+$CODEchck;
8327: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8328: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8329: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8330: if ($_64bit) { $num1=(($num1<<32)>>32); }
8331: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8332: return "$num1:$num2";
1.366 albertel 8333: }
8334: }
8335:
1.575 albertel 8336: sub rndseed_CODE_64bit4 {
8337: my ($symb,$courseid,$domain,$username)=@_;
8338: {
8339: use integer;
8340: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8341: my $symbseed=numval3($symb);
8342: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8343: my $CODEseed=numval3(&getCODE());
8344: my $courseseed=unpack("%32S*",$courseid.' ');
8345: my $num1=$symbseed+$CODEchck;
8346: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8347: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8348: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8349: if ($_64bit) { $num1=(($num1<<32)>>32); }
8350: if ($_64bit) { $num2=(($num2<<32)>>32); }
8351: return "$num1:$num2";
8352: }
8353: }
8354:
1.675 albertel 8355: sub rndseed_CODE_64bit5 {
8356: my ($symb,$courseid,$domain,$username)=@_;
8357: my $code = &getCODE();
8358: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8359: return "$num1:$num2";
8360: }
8361:
1.366 albertel 8362: sub setup_random_from_rndseed {
8363: my ($rndseed)=@_;
1.503 albertel 8364: if ($rndseed =~/([,:])/) {
8365: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8366: &Math::Random::random_set_seed(abs($num1),abs($num2));
8367: } else {
8368: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8369: }
1.36 albertel 8370: }
8371:
1.474 albertel 8372: sub latest_receipt_algorithm_id {
1.835 albertel 8373: return 'receipt3';
1.474 albertel 8374: }
8375:
1.480 www 8376: sub recunique {
8377: my $fucourseid=shift;
8378: my $unique;
1.835 albertel 8379: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8380: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8381: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8382: } else {
8383: $unique=$perlvar{'lonReceipt'};
8384: }
8385: return unpack("%32C*",$unique);
8386: }
8387:
8388: sub recprefix {
8389: my $fucourseid=shift;
8390: my $prefix;
1.835 albertel 8391: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8392: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8393: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8394: } else {
8395: $prefix=$perlvar{'lonHostID'};
8396: }
8397: return unpack("%32C*",$prefix);
8398: }
8399:
1.76 www 8400: sub ireceipt {
1.474 albertel 8401: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8402:
8403: my $return =&recprefix($fucourseid).'-';
8404:
8405: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8406: $env{'request.state'} eq 'construct') {
8407: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8408: return $return;
8409: }
8410:
1.76 www 8411: my $cuname=unpack("%32C*",$funame);
8412: my $cudom=unpack("%32C*",$fudom);
8413: my $cucourseid=unpack("%32C*",$fucourseid);
8414: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8415: my $cunique=&recunique($fucourseid);
1.474 albertel 8416: my $cpart=unpack("%32S*",$part);
1.835 albertel 8417: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8418:
1.790 albertel 8419: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8420:
8421: $return.= ($cunique%$cuname+
8422: $cunique%$cudom+
8423: $cusymb%$cuname+
8424: $cusymb%$cudom+
8425: $cucourseid%$cuname+
8426: $cucourseid%$cudom+
8427: $cpart%$cuname+
8428: $cpart%$cudom);
8429: } else {
8430: $return.= ($cunique%$cuname+
8431: $cunique%$cudom+
8432: $cusymb%$cuname+
8433: $cusymb%$cudom+
8434: $cucourseid%$cuname+
8435: $cucourseid%$cudom);
8436: }
8437: return $return;
1.76 www 8438: }
8439:
8440: sub receipt {
1.474 albertel 8441: my ($part)=@_;
1.790 albertel 8442: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8443: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8444: }
1.260 ng 8445:
1.790 albertel 8446: sub whichuser {
8447: my ($passedsymb)=@_;
8448: my ($symb,$courseid,$domain,$name,$publicuser);
8449: if (defined($env{'form.grade_symb'})) {
8450: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8451: my $allowed=&allowed('vgr',$tmp_courseid);
8452: if (!$allowed &&
8453: exists($env{'request.course.sec'}) &&
8454: $env{'request.course.sec'} !~ /^\s*$/) {
8455: $allowed=&allowed('vgr',$tmp_courseid.
8456: '/'.$env{'request.course.sec'});
8457: }
8458: if ($allowed) {
8459: ($symb)=&get_env_multiple('form.grade_symb');
8460: $courseid=$tmp_courseid;
8461: ($domain)=&get_env_multiple('form.grade_domain');
8462: ($name)=&get_env_multiple('form.grade_username');
8463: return ($symb,$courseid,$domain,$name,$publicuser);
8464: }
8465: }
8466: if (!$passedsymb) {
8467: $symb=&symbread();
8468: } else {
8469: $symb=$passedsymb;
8470: }
8471: $courseid=$env{'request.course.id'};
8472: $domain=$env{'user.domain'};
8473: $name=$env{'user.name'};
8474: if ($name eq 'public' && $domain eq 'public') {
8475: if (!defined($env{'form.username'})) {
8476: $env{'form.username'}.=time.rand(10000000);
8477: }
8478: $name.=$env{'form.username'};
8479: }
8480: return ($symb,$courseid,$domain,$name,$publicuser);
8481:
8482: }
8483:
1.36 albertel 8484: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8485: # returns either the contents of the file or
8486: # -1 if the file doesn't exist
1.481 raeburn 8487: #
8488: # if the target is a file that was uploaded via DOCS,
8489: # a check will be made to see if a current copy exists on the local server,
8490: # if it does this will be served, otherwise a copy will be retrieved from
8491: # the home server for the course and stored in /home/httpd/html/userfiles on
8492: # the local server.
1.472 albertel 8493:
1.36 albertel 8494: sub getfile {
1.538 albertel 8495: my ($file) = @_;
1.609 banghart 8496: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8497: &repcopy($file);
8498: return &readfile($file);
8499: }
8500:
8501: sub repcopy_userfile {
8502: my ($file)=@_;
1.609 banghart 8503: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8504: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8505: my ($cdom,$cnum,$filename) =
1.811 albertel 8506: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8507: my $uri="/uploaded/$cdom/$cnum/$filename";
8508: if (-e "$file") {
1.828 www 8509: # we already have a local copy, check it out
1.538 albertel 8510: my @fileinfo = stat($file);
1.828 www 8511: my $rtncode;
8512: my $info;
1.538 albertel 8513: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8514: if ($lwpresp ne 'ok') {
1.828 www 8515: # there is no such file anymore, even though we had a local copy
1.482 albertel 8516: if ($rtncode eq '404') {
1.538 albertel 8517: unlink($file);
1.482 albertel 8518: }
8519: return -1;
8520: }
8521: if ($info < $fileinfo[9]) {
1.828 www 8522: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8523: return 'ok';
1.828 www 8524: } else {
8525: # the file is outdated, get rid of it
8526: unlink($file);
1.482 albertel 8527: }
1.828 www 8528: }
8529: # one way or the other, at this point, we don't have the file
8530: # construct the correct path for the file
8531: my @parts = ($cdom,$cnum);
8532: if ($filename =~ m|^(.+)/[^/]+$|) {
8533: push @parts, split(/\//,$1);
8534: }
8535: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8536: foreach my $part (@parts) {
8537: $path .= '/'.$part;
8538: if (!-e $path) {
8539: mkdir($path,0770);
1.482 albertel 8540: }
8541: }
1.828 www 8542: # now the path exists for sure
8543: # get a user agent
8544: my $ua=new LWP::UserAgent;
8545: my $transferfile=$file.'.in.transfer';
8546: # FIXME: this should flock
8547: if (-e $transferfile) { return 'ok'; }
8548: my $request;
8549: $uri=~s/^\///;
1.980 raeburn 8550: my $homeserver = &homeserver($cnum,$cdom);
8551: my $protocol = $protocol{$homeserver};
8552: $protocol = 'http' if ($protocol ne 'https');
8553: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8554: my $response=$ua->request($request,$transferfile);
8555: # did it work?
8556: if ($response->is_error()) {
8557: unlink($transferfile);
8558: &logthis("Userfile repcopy failed for $uri");
8559: return -1;
8560: }
8561: # worked, rename the transfer file
8562: rename($transferfile,$file);
1.607 raeburn 8563: return 'ok';
1.481 raeburn 8564: }
8565:
1.517 albertel 8566: sub tokenwrapper {
8567: my $uri=shift;
1.980 raeburn 8568: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8569: $uri=~s|^/||;
1.620 albertel 8570: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8571: my $token=$1;
1.552 albertel 8572: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8573: if ($udom && $uname && $file) {
8574: $file=~s|(\?\.*)*$||;
1.949 raeburn 8575: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 8576: my $homeserver = &homeserver($uname,$udom);
8577: my $protocol = $protocol{$homeserver};
8578: $protocol = 'http' if ($protocol ne 'https');
8579: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8580: (($uri=~/\?/)?'&':'?').'token='.$token.
8581: '&tokenissued='.$perlvar{'lonHostID'};
8582: } else {
8583: return '/adm/notfound.html';
8584: }
8585: }
8586:
1.828 www 8587: # call with reqtype HEAD: get last modification time
8588: # call with reqtype GET: get the file contents
8589: # Do not call this with reqtype GET for large files! It loads everything into memory
8590: #
1.481 raeburn 8591: sub getuploaded {
8592: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8593: $uri=~s/^\///;
1.980 raeburn 8594: my $homeserver = &homeserver($cnum,$cdom);
8595: my $protocol = $protocol{$homeserver};
8596: $protocol = 'http' if ($protocol ne 'https');
8597: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8598: my $ua=new LWP::UserAgent;
8599: my $request=new HTTP::Request($reqtype,$uri);
8600: my $response=$ua->request($request);
8601: $$rtncode = $response->code;
1.482 albertel 8602: if (! $response->is_success()) {
8603: return 'failed';
8604: }
8605: if ($reqtype eq 'HEAD') {
1.486 www 8606: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8607: } elsif ($reqtype eq 'GET') {
8608: $$info = $response->content;
1.472 albertel 8609: }
1.482 albertel 8610: return 'ok';
1.36 albertel 8611: }
8612:
1.481 raeburn 8613: sub readfile {
8614: my $file = shift;
8615: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8616: my $fh;
8617: open($fh,"<$file");
8618: my $a='';
1.800 albertel 8619: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8620: return $a;
8621: }
8622:
1.36 albertel 8623: sub filelocation {
1.590 banghart 8624: my ($dir,$file) = @_;
8625: my $location;
8626: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8627:
8628: if ($file =~ m-^/adm/-) {
8629: $file=~s-^/adm/wrapper/-/-;
8630: $file=~s-^/adm/coursedocs/showdoc/-/-;
8631: }
1.882 albertel 8632:
1.590 banghart 8633: if ($file=~m:^/~:) { # is a contruction space reference
8634: $location = $file;
8635: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8636: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8637: # is a correct contruction space reference
8638: $location = $file;
1.956 raeburn 8639: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8640: $location = $file;
1.609 banghart 8641: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8642: my ($udom,$uname,$filename)=
1.811 albertel 8643: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8644: my $home=&homeserver($uname,$udom);
8645: my $is_me=0;
8646: my @ids=¤t_machine_ids();
8647: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8648: if ($is_me) {
1.955 raeburn 8649: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8650: } else {
8651: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8652: $udom.'/'.$uname.'/'.$filename;
8653: }
1.882 albertel 8654: } elsif ($file =~ m-^/adm/-) {
8655: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8656: } else {
8657: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8658: $file=~s:^/res/:/:;
8659: if ( !( $file =~ m:^/:) ) {
8660: $location = $dir. '/'.$file;
8661: } else {
8662: $location = '/home/httpd/html/res'.$file;
8663: }
1.59 albertel 8664: }
1.590 banghart 8665: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8666: while ($location=~m{/\.\./}) {
8667: if ($location =~ m{/[^/]+/\.\./}) {
8668: $location=~ s{/[^/]+/\.\./}{/}g;
8669: } else {
8670: $location=~ s{/\.\./}{/}g;
8671: }
8672: } #remove dir/..
1.590 banghart 8673: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8674: return $location;
1.46 www 8675: }
1.36 albertel 8676:
1.46 www 8677: sub hreflocation {
8678: my ($dir,$file)=@_;
1.980 raeburn 8679: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8680: $file=filelocation($dir,$file);
1.700 albertel 8681: } elsif ($file=~m-^/adm/-) {
8682: $file=~s-^/adm/wrapper/-/-;
8683: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8684: }
8685: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8686: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8687: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8688: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8689: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8690: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8691: -/uploaded/$1/$2/-x;
1.46 www 8692: }
1.913 albertel 8693: if ($file=~ m{^/userfiles/}) {
8694: $file =~ s{^/userfiles/}{/uploaded/};
8695: }
1.462 albertel 8696: return $file;
1.465 albertel 8697: }
8698:
8699: sub current_machine_domains {
1.853 albertel 8700: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8701: }
8702:
8703: sub machine_domains {
8704: my ($hostname) = @_;
1.465 albertel 8705: my @domains;
1.838 albertel 8706: my %hostname = &all_hostnames();
1.465 albertel 8707: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8708: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8709: if ($hostname eq $name) {
1.844 albertel 8710: push(@domains,&host_domain($id));
1.465 albertel 8711: }
8712: }
8713: return @domains;
8714: }
8715:
8716: sub current_machine_ids {
1.853 albertel 8717: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8718: }
8719:
8720: sub machine_ids {
8721: my ($hostname) = @_;
8722: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8723: my @ids;
1.888 albertel 8724: my %name_to_host = &all_names();
1.889 albertel 8725: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8726: return @{ $name_to_host{$hostname} };
8727: }
8728: return;
1.31 www 8729: }
8730:
1.824 raeburn 8731: sub additional_machine_domains {
8732: my @domains;
8733: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8734: while( my $line = <$fh>) {
8735: $line =~ s/\s//g;
8736: push(@domains,$line);
8737: }
8738: return @domains;
8739: }
8740:
8741: sub default_login_domain {
8742: my $domain = $perlvar{'lonDefDomain'};
8743: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8744: foreach my $posdom (¤t_machine_domains(),
8745: &additional_machine_domains()) {
8746: if (lc($posdom) eq lc($testdomain)) {
8747: $domain=$posdom;
8748: last;
8749: }
8750: }
8751: return $domain;
8752: }
8753:
1.31 www 8754: # ------------------------------------------------------------- Declutters URLs
8755:
8756: sub declutter {
8757: my $thisfn=shift;
1.569 albertel 8758: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8759: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8760: $thisfn=~s/^\///;
1.697 albertel 8761: $thisfn=~s|^adm/wrapper/||;
8762: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8763: $thisfn=~s/^res\///;
1.235 www 8764: $thisfn=~s/\?.+$//;
1.268 www 8765: return $thisfn;
8766: }
8767:
8768: # ------------------------------------------------------------- Clutter up URLs
8769:
8770: sub clutter {
8771: my $thisfn='/'.&declutter(shift);
1.887 albertel 8772: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8773: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8774: $thisfn='/res'.$thisfn;
8775: }
1.694 albertel 8776: if ($thisfn !~m|/adm|) {
1.695 albertel 8777: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8778: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8779: } else {
8780: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8781: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8782: if ($embstyle eq 'ssi'
8783: || ($embstyle eq 'hdn')
8784: || ($embstyle eq 'rat')
8785: || ($embstyle eq 'prv')
8786: || ($embstyle eq 'ign')) {
8787: #do nothing with these
8788: } elsif (($embstyle eq 'img')
1.695 albertel 8789: || ($embstyle eq 'emb')
8790: || ($embstyle eq 'wrp')) {
8791: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8792: } elsif ($embstyle eq 'unk'
8793: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8794: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8795: } else {
1.718 www 8796: # &logthis("Got a blank emb style");
1.695 albertel 8797: }
1.694 albertel 8798: }
8799: }
1.31 www 8800: return $thisfn;
1.12 www 8801: }
8802:
1.787 albertel 8803: sub clutter_with_no_wrapper {
8804: my $uri = &clutter(shift);
8805: if ($uri =~ m-^/adm/-) {
8806: $uri =~ s-^/adm/wrapper/-/-;
8807: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8808: }
8809: return $uri;
8810: }
8811:
1.557 albertel 8812: sub freeze_escape {
8813: my ($value)=@_;
8814: if (ref($value)) {
8815: $value=&nfreeze($value);
8816: return '__FROZEN__'.&escape($value);
8817: }
8818: return &escape($value);
8819: }
8820:
1.11 www 8821:
1.557 albertel 8822: sub thaw_unescape {
8823: my ($value)=@_;
8824: if ($value =~ /^__FROZEN__/) {
8825: substr($value,0,10,undef);
8826: $value=&unescape($value);
8827: return &thaw($value);
8828: }
8829: return &unescape($value);
8830: }
8831:
1.436 albertel 8832: sub correct_line_ends {
8833: my ($result)=@_;
8834: $$result =~s/\r\n/\n/mg;
8835: $$result =~s/\r/\n/mg;
1.415 albertel 8836: }
1.1 albertel 8837: # ================================================================ Main Program
8838:
1.184 www 8839: sub goodbye {
1.204 albertel 8840: &logthis("Starting Shut down");
1.443 albertel 8841: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8842: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8843: #converted
1.599 albertel 8844: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8845: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8846: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8847: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8848: #1.1 only
1.870 albertel 8849: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8850: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8851: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8852: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8853: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8854: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8855: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8856: &flushcourselogs();
8857: &logthis("Shutting down");
8858: }
8859:
1.852 albertel 8860: sub get_dns {
1.869 albertel 8861: my ($url,$func,$ignore_cache) = @_;
8862: if (!$ignore_cache) {
8863: my ($content,$cached)=
8864: &Apache::lonnet::is_cached_new('dns',$url);
8865: if ($cached) {
8866: &$func($content);
8867: return;
8868: }
8869: }
8870:
8871: my %alldns;
1.852 albertel 8872: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8873: foreach my $dns (<$config>) {
8874: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 8875: my $line = $1;
8876: my ($host,$protocol) = split(/:/,$line);
8877: if ($protocol ne 'https') {
8878: $protocol = 'http';
8879: }
8880: $alldns{$host} = $protocol;
1.869 albertel 8881: }
8882: while (%alldns) {
8883: my ($dns) = keys(%alldns);
1.852 albertel 8884: my $ua=new LWP::UserAgent;
1.979 raeburn 8885: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 8886: my $response=$ua->request($request);
1.979 raeburn 8887: delete($alldns{$dns});
1.852 albertel 8888: next if ($response->is_error());
8889: my @content = split("\n",$response->content);
1.869 albertel 8890: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8891: &$func(\@content);
1.869 albertel 8892: return;
1.852 albertel 8893: }
8894: close($config);
1.871 albertel 8895: my $which = (split('/',$url))[3];
8896: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8897: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8898: my @content = <$config>;
8899: &$func(\@content);
8900: return;
1.852 albertel 8901: }
1.327 albertel 8902: # ------------------------------------------------------------ Read domain file
8903: {
1.852 albertel 8904: my $loaded;
1.846 albertel 8905: my %domain;
8906:
1.852 albertel 8907: sub parse_domain_tab {
8908: my ($lines) = @_;
8909: foreach my $line (@$lines) {
8910: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8911:
1.846 albertel 8912: chomp($line);
1.852 albertel 8913: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8914: my %this_domain;
8915: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8916: 'lang_def', 'city', 'longi', 'lati',
8917: 'primary') {
8918: $this_domain{$field} = shift(@elements);
8919: }
8920: $domain{$name} = \%this_domain;
1.852 albertel 8921: }
8922: }
1.864 albertel 8923:
8924: sub reset_domain_info {
8925: undef($loaded);
8926: undef(%domain);
8927: }
8928:
1.852 albertel 8929: sub load_domain_tab {
1.869 albertel 8930: my ($ignore_cache) = @_;
8931: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8932: my $fh;
8933: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8934: my @lines = <$fh>;
8935: &parse_domain_tab(\@lines);
1.448 albertel 8936: }
1.852 albertel 8937: close($fh);
8938: $loaded = 1;
1.327 albertel 8939: }
1.846 albertel 8940:
8941: sub domain {
1.852 albertel 8942: &load_domain_tab() if (!$loaded);
8943:
1.846 albertel 8944: my ($name,$what) = @_;
8945: return if ( !exists($domain{$name}) );
8946:
8947: if (!$what) {
8948: return $domain{$name}{'description'};
8949: }
8950: return $domain{$name}{$what};
8951: }
1.974 raeburn 8952:
8953: sub domain_info {
8954: &load_domain_tab() if (!$loaded);
8955: return %domain;
8956: }
8957:
1.327 albertel 8958: }
8959:
8960:
1.1 albertel 8961: # ------------------------------------------------------------- Read hosts file
8962: {
1.838 albertel 8963: my %hostname;
1.844 albertel 8964: my %hostdom;
1.845 albertel 8965: my %libserv;
1.852 albertel 8966: my $loaded;
1.888 albertel 8967: my %name_to_host;
1.852 albertel 8968:
8969: sub parse_hosts_tab {
8970: my ($file) = @_;
8971: foreach my $configline (@$file) {
8972: next if ($configline =~ /^(\#|\s*$ )/x);
8973: next if ($configline =~ /^\^/);
8974: chomp($configline);
1.968 raeburn 8975: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 8976: $name=~s/\s//g;
8977: if ($id && $domain && $role && $name) {
8978: $hostname{$id}=$name;
1.888 albertel 8979: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8980: $hostdom{$id}=$domain;
8981: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 8982: if (defined($protocol)) {
8983: if ($protocol eq 'https') {
8984: $protocol{$id} = $protocol;
8985: } else {
8986: $protocol{$id} = 'http';
8987: }
1.968 raeburn 8988: } else {
1.969 raeburn 8989: $protocol{$id} = 'http';
1.968 raeburn 8990: }
1.852 albertel 8991: }
8992: }
8993: }
1.864 albertel 8994:
8995: sub reset_hosts_info {
1.897 albertel 8996: &purge_remembered();
1.864 albertel 8997: &reset_domain_info();
8998: &reset_hosts_ip_info();
1.892 albertel 8999: undef(%name_to_host);
1.864 albertel 9000: undef(%hostname);
9001: undef(%hostdom);
9002: undef(%libserv);
9003: undef($loaded);
9004: }
1.1 albertel 9005:
1.852 albertel 9006: sub load_hosts_tab {
1.869 albertel 9007: my ($ignore_cache) = @_;
9008: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9009: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9010: my @config = <$config>;
9011: &parse_hosts_tab(\@config);
9012: close($config);
9013: $loaded=1;
1.1 albertel 9014: }
1.852 albertel 9015:
1.838 albertel 9016: sub hostname {
1.852 albertel 9017: &load_hosts_tab() if (!$loaded);
9018:
1.838 albertel 9019: my ($lonid) = @_;
9020: return $hostname{$lonid};
9021: }
1.845 albertel 9022:
1.838 albertel 9023: sub all_hostnames {
1.852 albertel 9024: &load_hosts_tab() if (!$loaded);
9025:
1.838 albertel 9026: return %hostname;
9027: }
1.845 albertel 9028:
1.888 albertel 9029: sub all_names {
9030: &load_hosts_tab() if (!$loaded);
9031:
9032: return %name_to_host;
9033: }
9034:
1.974 raeburn 9035: sub all_host_domain {
9036: &load_hosts_tab() if (!$loaded);
9037: return %hostdom;
9038: }
9039:
1.845 albertel 9040: sub is_library {
1.852 albertel 9041: &load_hosts_tab() if (!$loaded);
9042:
1.845 albertel 9043: return exists($libserv{$_[0]});
9044: }
9045:
9046: sub all_library {
1.852 albertel 9047: &load_hosts_tab() if (!$loaded);
9048:
1.845 albertel 9049: return %libserv;
9050: }
9051:
1.841 albertel 9052: sub get_servers {
1.852 albertel 9053: &load_hosts_tab() if (!$loaded);
9054:
1.841 albertel 9055: my ($domain,$type) = @_;
9056: my %possible_hosts = ($type eq 'library') ? %libserv
9057: : %hostname;
9058: my %result;
1.842 albertel 9059: if (ref($domain) eq 'ARRAY') {
9060: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9061: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9062: $result{$host} = $hostname;
9063: }
9064: }
9065: } else {
9066: while ( my ($host,$hostname) = each(%possible_hosts)) {
9067: if ($hostdom{$host} eq $domain) {
9068: $result{$host} = $hostname;
9069: }
1.841 albertel 9070: }
9071: }
9072: return %result;
9073: }
1.845 albertel 9074:
1.844 albertel 9075: sub host_domain {
1.852 albertel 9076: &load_hosts_tab() if (!$loaded);
9077:
1.844 albertel 9078: my ($lonid) = @_;
9079: return $hostdom{$lonid};
9080: }
9081:
1.841 albertel 9082: sub all_domains {
1.852 albertel 9083: &load_hosts_tab() if (!$loaded);
9084:
1.841 albertel 9085: my %seen;
9086: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9087: return @uniq;
9088: }
1.1 albertel 9089: }
9090:
1.847 albertel 9091: {
9092: my %iphost;
1.856 albertel 9093: my %name_to_ip;
9094: my %lonid_to_ip;
1.869 albertel 9095:
1.847 albertel 9096: sub get_hosts_from_ip {
9097: my ($ip) = @_;
9098: my %iphosts = &get_iphost();
9099: if (ref($iphosts{$ip})) {
9100: return @{$iphosts{$ip}};
9101: }
9102: return;
1.839 albertel 9103: }
1.864 albertel 9104:
9105: sub reset_hosts_ip_info {
9106: undef(%iphost);
9107: undef(%name_to_ip);
9108: undef(%lonid_to_ip);
9109: }
1.856 albertel 9110:
9111: sub get_host_ip {
9112: my ($lonid) = @_;
9113: if (exists($lonid_to_ip{$lonid})) {
9114: return $lonid_to_ip{$lonid};
9115: }
9116: my $name=&hostname($lonid);
9117: my $ip = gethostbyname($name);
9118: return if (!$ip || length($ip) ne 4);
9119: $ip=inet_ntoa($ip);
9120: $name_to_ip{$name} = $ip;
9121: $lonid_to_ip{$lonid} = $ip;
9122: return $ip;
9123: }
1.847 albertel 9124:
9125: sub get_iphost {
1.869 albertel 9126: my ($ignore_cache) = @_;
1.894 albertel 9127:
1.869 albertel 9128: if (!$ignore_cache) {
9129: if (%iphost) {
9130: return %iphost;
9131: }
9132: my ($ip_info,$cached)=
9133: &Apache::lonnet::is_cached_new('iphost','iphost');
9134: if ($cached) {
9135: %iphost = %{$ip_info->[0]};
9136: %name_to_ip = %{$ip_info->[1]};
9137: %lonid_to_ip = %{$ip_info->[2]};
9138: return %iphost;
9139: }
9140: }
1.894 albertel 9141:
9142: # get yesterday's info for fallback
9143: my %old_name_to_ip;
9144: my ($ip_info,$cached)=
9145: &Apache::lonnet::is_cached_new('iphost','iphost');
9146: if ($cached) {
9147: %old_name_to_ip = %{$ip_info->[1]};
9148: }
9149:
1.888 albertel 9150: my %name_to_host = &all_names();
9151: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9152: my $ip;
9153: if (!exists($name_to_ip{$name})) {
9154: $ip = gethostbyname($name);
9155: if (!$ip || length($ip) ne 4) {
1.894 albertel 9156: if (defined($old_name_to_ip{$name})) {
9157: $ip = $old_name_to_ip{$name};
9158: &logthis("Can't find $name defaulting to old $ip");
9159: } else {
9160: &logthis("Name $name no IP found");
9161: next;
9162: }
9163: } else {
9164: $ip=inet_ntoa($ip);
1.847 albertel 9165: }
9166: $name_to_ip{$name} = $ip;
9167: } else {
9168: $ip = $name_to_ip{$name};
1.653 albertel 9169: }
1.888 albertel 9170: foreach my $id (@{ $name_to_host{$name} }) {
9171: $lonid_to_ip{$id} = $ip;
9172: }
9173: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9174: }
1.869 albertel 9175: &Apache::lonnet::do_cache_new('iphost','iphost',
9176: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9177: 48*60*60);
1.869 albertel 9178:
1.847 albertel 9179: return %iphost;
1.598 albertel 9180: }
9181:
1.992 raeburn 9182: #
9183: # Given a DNS returns the loncapa host name for that DNS
9184: #
9185: sub host_from_dns {
9186: my ($dns) = @_;
9187: my @hosts;
9188: my $ip;
9189:
1.993 raeburn 9190: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9191: $ip = $name_to_ip{$dns};
9192: }
9193: if (!$ip) {
9194: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9195: if (length($ip) == 4) {
9196: $ip = &IO::Socket::inet_ntoa($ip);
9197: }
9198: }
9199: if ($ip) {
9200: @hosts = get_hosts_from_ip($ip);
9201: return $hosts[0];
9202: }
9203: return undef;
1.986 foxr 9204: }
1.992 raeburn 9205:
1.986 foxr 9206: }
9207:
1.862 albertel 9208: BEGIN {
9209:
9210: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9211: unless ($readit) {
9212: {
9213: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9214: %perlvar = (%perlvar,%{$configvars});
9215: }
9216:
9217:
1.1 albertel 9218: # ------------------------------------------------------ Read spare server file
9219: {
1.448 albertel 9220: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9221:
9222: while (my $configline=<$config>) {
9223: chomp($configline);
1.284 matthew 9224: if ($configline) {
1.784 albertel 9225: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9226: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9227: push(@{ $spareid{$type} }, $host);
1.1 albertel 9228: }
9229: }
1.448 albertel 9230: close($config);
1.1 albertel 9231: }
1.11 www 9232: # ------------------------------------------------------------ Read permissions
9233: {
1.448 albertel 9234: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9235:
9236: while (my $configline=<$config>) {
1.448 albertel 9237: chomp($configline);
9238: if ($configline) {
9239: my ($role,$perm)=split(/ /,$configline);
9240: if ($perm ne '') { $pr{$role}=$perm; }
9241: }
1.11 www 9242: }
1.448 albertel 9243: close($config);
1.11 www 9244: }
9245:
9246: # -------------------------------------------- Read plain texts for permissions
9247: {
1.448 albertel 9248: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9249:
9250: while (my $configline=<$config>) {
1.448 albertel 9251: chomp($configline);
9252: if ($configline) {
1.742 raeburn 9253: my ($short,@plain)=split(/:/,$configline);
9254: %{$prp{$short}} = ();
9255: if (@plain > 0) {
9256: $prp{$short}{'std'} = $plain[0];
9257: for (my $i=1; $i<@plain; $i++) {
9258: $prp{$short}{'alt'.$i} = $plain[$i];
9259: }
9260: }
1.448 albertel 9261: }
1.135 www 9262: }
1.448 albertel 9263: close($config);
1.135 www 9264: }
9265:
9266: # ---------------------------------------------------------- Read package table
9267: {
1.448 albertel 9268: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9269:
9270: while (my $configline=<$config>) {
1.483 albertel 9271: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9272: chomp($configline);
9273: my ($short,$plain)=split(/:/,$configline);
9274: my ($pack,$name)=split(/\&/,$short);
9275: if ($plain ne '') {
9276: $packagetab{$pack.'&'.$name.'&name'}=$name;
9277: $packagetab{$short}=$plain;
9278: }
1.11 www 9279: }
1.448 albertel 9280: close($config);
1.329 matthew 9281: }
9282:
9283: # ------------- set up temporary directory
9284: {
9285: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9286:
1.11 www 9287: }
9288:
1.794 albertel 9289: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9290: 'compress_threshold'=> 20_000,
9291: });
1.185 www 9292:
1.281 www 9293: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9294: $dumpcount=0;
1.958 www 9295: $locknum=0;
1.22 www 9296:
1.163 harris41 9297: &logtouch();
1.672 albertel 9298: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9299: $readit=1;
1.564 albertel 9300: {
9301: use integer;
9302: my $test=(2**32)+1;
1.568 albertel 9303: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9304: &logthis(" Detected 64bit platform ($_64bit)");
9305: }
1.195 www 9306: }
1.1 albertel 9307: }
1.179 www 9308:
1.1 albertel 9309: 1;
1.191 harris41 9310: __END__
9311:
1.243 albertel 9312: =pod
9313:
1.191 harris41 9314: =head1 NAME
9315:
1.243 albertel 9316: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9317:
9318: =head1 SYNOPSIS
9319:
1.243 albertel 9320: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9321:
9322: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9323:
1.243 albertel 9324: Common parameters:
9325:
9326: =over 4
9327:
9328: =item *
9329:
9330: $uname : an internal username (if $cname expecting a course Id specifically)
9331:
9332: =item *
9333:
9334: $udom : a domain (if $cdom expecting a course's domain specifically)
9335:
9336: =item *
9337:
9338: $symb : a resource instance identifier
9339:
9340: =item *
9341:
9342: $namespace : the name of a .db file that contains the data needed or
9343: being set.
9344:
9345: =back
9346:
1.394 bowersj2 9347: =head1 OVERVIEW
1.191 harris41 9348:
1.394 bowersj2 9349: lonnet provides subroutines which interact with the
9350: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9351: about classes, users, and resources.
1.243 albertel 9352:
9353: For many of these objects you can also use this to store data about
9354: them or modify them in various ways.
1.191 harris41 9355:
1.394 bowersj2 9356: =head2 Symbs
1.191 harris41 9357:
1.394 bowersj2 9358: To identify a specific instance of a resource, LON-CAPA uses symbols
9359: or "symbs"X<symb>. These identifiers are built from the URL of the
9360: map, the resource number of the resource in the map, and the URL of
9361: the resource itself. The latter is somewhat redundant, but might help
9362: if maps change.
9363:
9364: An example is
9365:
9366: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9367:
9368: The respective map entry is
9369:
9370: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9371: title="Problem 2">
9372: </resource>
9373:
9374: Symbs are used by the random number generator, as well as to store and
9375: restore data specific to a certain instance of for example a problem.
9376:
9377: =head2 Storing And Retrieving Data
9378:
9379: X<store()>X<cstore()>X<restore()>Three of the most important functions
9380: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9381: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9382: is is the non-critical message twin of cstore. These functions are for
9383: handlers to store a perl hash to a user's permanent data space in an
9384: easy manner, and to retrieve it again on another call. It is expected
9385: that a handler would use this once at the beginning to retrieve data,
9386: and then again once at the end to send only the new data back.
9387:
9388: The data is stored in the user's data directory on the user's
9389: homeserver under the ID of the course.
9390:
9391: The hash that is returned by restore will have all of the previous
9392: value for all of the elements of the hash.
9393:
9394: Example:
9395:
9396: #creating a hash
9397: my %hash;
9398: $hash{'foo'}='bar';
9399:
9400: #storing it
9401: &Apache::lonnet::cstore(\%hash);
9402:
9403: #changing a value
9404: $hash{'foo'}='notbar';
9405:
9406: #adding a new value
9407: $hash{'bar'}='foo';
9408: &Apache::lonnet::cstore(\%hash);
9409:
9410: #retrieving the hash
9411: my %history=&Apache::lonnet::restore();
9412:
9413: #print the hash
9414: foreach my $key (sort(keys(%history))) {
9415: print("\%history{$key} = $history{$key}");
9416: }
9417:
9418: Will print out:
1.191 harris41 9419:
1.394 bowersj2 9420: %history{1:foo} = bar
9421: %history{1:keys} = foo:timestamp
9422: %history{1:timestamp} = 990455579
9423: %history{2:bar} = foo
9424: %history{2:foo} = notbar
9425: %history{2:keys} = foo:bar:timestamp
9426: %history{2:timestamp} = 990455580
9427: %history{bar} = foo
9428: %history{foo} = notbar
9429: %history{timestamp} = 990455580
9430: %history{version} = 2
9431:
9432: Note that the special hash entries C<keys>, C<version> and
9433: C<timestamp> were added to the hash. C<version> will be equal to the
9434: total number of versions of the data that have been stored. The
9435: C<timestamp> attribute will be the UNIX time the hash was
9436: stored. C<keys> is available in every historical section to list which
9437: keys were added or changed at a specific historical revision of a
9438: hash.
9439:
9440: B<Warning>: do not store the hash that restore returns directly. This
9441: will cause a mess since it will restore the historical keys as if the
9442: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9443:
1.394 bowersj2 9444: Calling convention:
1.191 harris41 9445:
1.394 bowersj2 9446: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9447: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9448:
1.394 bowersj2 9449: For more detailed information, see lonnet specific documentation.
1.191 harris41 9450:
1.394 bowersj2 9451: =head1 RETURN MESSAGES
1.191 harris41 9452:
1.394 bowersj2 9453: =over 4
1.191 harris41 9454:
1.394 bowersj2 9455: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9456:
1.394 bowersj2 9457: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9458: when the connection is brought back up
1.191 harris41 9459:
1.394 bowersj2 9460: =item * B<con_failed>: unable to contact remote host and unable to save message
9461: for later delivery
1.191 harris41 9462:
1.967 bisitz 9463: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9464:
1.394 bowersj2 9465: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9466: that was requested
1.191 harris41 9467:
1.243 albertel 9468: =back
1.191 harris41 9469:
1.243 albertel 9470: =head1 PUBLIC SUBROUTINES
1.191 harris41 9471:
1.243 albertel 9472: =head2 Session Environment Functions
1.191 harris41 9473:
1.243 albertel 9474: =over 4
1.191 harris41 9475:
1.394 bowersj2 9476: =item *
9477: X<appenv()>
1.949 raeburn 9478: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9479: the user envirnoment file, and will be restored for each access this
1.620 albertel 9480: user makes during this session, also modifies the %env for the current
1.949 raeburn 9481: process. Optional rolesarrayref - if defined contains a reference to an array
9482: of roles which are exempt from the restriction on modifying user.role entries
9483: in the user's environment.db and in %env.
1.191 harris41 9484:
9485: =item *
1.394 bowersj2 9486: X<delenv()>
1.987 raeburn 9487: B<delenv($delthis,$regexp)>: removes all items from the session
9488: environment file that begin with $delthis. If the
9489: optional second arg - $regexp - is true, $delthis is treated as a
9490: regular expression, otherwise \Q$delthis\E is used.
9491: The values are also deleted from the current processes %env.
1.191 harris41 9492:
1.795 albertel 9493: =item * get_env_multiple($name)
9494:
9495: gets $name from the %env hash, it seemlessly handles the cases where multiple
9496: values may be defined and end up as an array ref.
9497:
9498: returns an array of values
9499:
1.243 albertel 9500: =back
9501:
9502: =head2 User Information
1.191 harris41 9503:
1.243 albertel 9504: =over 4
1.191 harris41 9505:
9506: =item *
1.394 bowersj2 9507: X<queryauthenticate()>
9508: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9509: authentication scheme
9510:
9511: =item *
1.394 bowersj2 9512: X<authenticate()>
9513: B<authenticate($uname,$upass,$udom)>: try to
9514: authenticate user from domain's lib servers (first use the current
9515: one). C<$upass> should be the users password.
1.191 harris41 9516:
9517: =item *
1.394 bowersj2 9518: X<homeserver()>
9519: B<homeserver($uname,$udom)>: find the server which has
9520: the user's directory and files (there must be only one), this caches
9521: the answer, and also caches if there is a borken connection.
1.191 harris41 9522:
9523: =item *
1.394 bowersj2 9524: X<idget()>
9525: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9526: (IDs are a unique resource in a domain, there must be only 1 ID per
9527: username, and only 1 username per ID in a specific domain) (returns
9528: hash: id=>name,id=>name)
1.191 harris41 9529:
9530: =item *
1.394 bowersj2 9531: X<idrget()>
9532: B<idrget($udom,@unames)>: find the IDs behind a list of
9533: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9534:
9535: =item *
1.394 bowersj2 9536: X<idput()>
9537: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9538:
9539: =item *
1.394 bowersj2 9540: X<rolesinit()>
9541: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9542:
9543: =item *
1.551 albertel 9544: X<getsection()>
9545: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9546: course $cname, return section name/number or '' for "not in course"
9547: and '-1' for "no section"
9548:
9549: =item *
1.394 bowersj2 9550: X<userenvironment()>
9551: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9552: passed in @what from the requested user's environment, returns a hash
9553:
1.858 raeburn 9554: =item *
9555: X<userlog_query()>
1.859 albertel 9556: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9557: activity.log file. %filters defines filters applied when parsing the
9558: log file. These can be start or end timestamps, or the type of action
9559: - log to look for Login or Logout events, check for Checkin or
9560: Checkout, role for role selection. The response is in the form
9561: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9562: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9563:
1.243 albertel 9564: =back
9565:
9566: =head2 User Roles
9567:
9568: =over 4
9569:
9570: =item *
9571:
1.810 raeburn 9572: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9573: F: full access
9574: U,I,K: authentication modes (cxx only)
9575: '': forbidden
9576: 1: user needs to choose course
9577: 2: browse allowed
1.766 albertel 9578: A: passphrase authentication needed
1.243 albertel 9579:
9580: =item *
9581:
9582: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9583: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9584: and course level
9585:
9586: =item *
9587:
1.988 raeburn 9588: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9589: (rolesplain.tab); plain text explanation of a user role term.
9590: $type is Course (default) or Group.
9591: If $forcedefault evaluates to true, text returned will be default
9592: text for $type. Otherwise, if this is a course, the text returned
9593: will be a custom name for the role (if defined in the course's
9594: environment). If no custom name is defined the default is returned.
9595:
1.832 raeburn 9596: =item *
9597:
1.935 raeburn 9598: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9599: All arguments are optional. Returns a hash of a roles, either for
9600: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9601: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9602: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9603: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9604: For each key, value is set to colon-separated start and end times for
9605: the role. If no username and domain are specified, will default to
1.934 raeburn 9606: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9607: of role statuses (active, future or previous), roles
9608: (e.g., cc,in, st etc.) and domains of the roles which can be used
9609: to restrict the list of roles reported. If no array ref is
9610: provided for types, will default to return only active roles.
1.834 albertel 9611:
1.243 albertel 9612: =back
9613:
9614: =head2 User Modification
9615:
9616: =over 4
9617:
9618: =item *
9619:
1.957 raeburn 9620: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9621: user for the level given by URL. Optional start and end dates (leave empty
9622: string or zero for "no date")
1.191 harris41 9623:
9624: =item *
9625:
1.243 albertel 9626: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9627: change a users, password, possible return values are: ok,
9628: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9629: refused
1.191 harris41 9630:
9631: =item *
9632:
1.243 albertel 9633: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9634:
9635: =item *
9636:
1.963 raeburn 9637: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9638: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9639: modify user
1.191 harris41 9640:
9641: =item *
9642:
1.286 matthew 9643: modifystudent
9644:
1.957 raeburn 9645: modify a student's enrollment and identification information.
1.286 matthew 9646: The course id is resolved based on the current users environment.
9647: This means the envoking user must be a course coordinator or otherwise
9648: associated with a course.
9649:
1.297 matthew 9650: This call is essentially a wrapper for lonnet::modifyuser and
9651: lonnet::modify_student_enrollment
1.286 matthew 9652:
9653: Inputs:
9654:
9655: =over 4
9656:
1.957 raeburn 9657: =item B<$udom> Student's loncapa domain
1.286 matthew 9658:
1.957 raeburn 9659: =item B<$uname> Student's loncapa login name
1.286 matthew 9660:
1.964 bisitz 9661: =item B<$uid> Student/Employee ID
1.286 matthew 9662:
1.957 raeburn 9663: =item B<$umode> Student's authentication mode
1.286 matthew 9664:
1.957 raeburn 9665: =item B<$upass> Student's password
1.286 matthew 9666:
1.957 raeburn 9667: =item B<$first> Student's first name
1.286 matthew 9668:
1.957 raeburn 9669: =item B<$middle> Student's middle name
1.286 matthew 9670:
1.957 raeburn 9671: =item B<$last> Student's last name
1.286 matthew 9672:
1.957 raeburn 9673: =item B<$gene> Student's generation
1.286 matthew 9674:
1.957 raeburn 9675: =item B<$usec> Student's section in course
1.286 matthew 9676:
9677: =item B<$end> Unix time of the roles expiration
9678:
9679: =item B<$start> Unix time of the roles start date
9680:
9681: =item B<$forceid> If defined, allow $uid to be changed
9682:
9683: =item B<$desiredhome> server to use as home server for student
9684:
1.957 raeburn 9685: =item B<$email> Student's permanent e-mail address
9686:
9687: =item B<$type> Type of enrollment (auto or manual)
9688:
1.963 raeburn 9689: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9690:
9691: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9692:
1.963 raeburn 9693: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9694:
1.963 raeburn 9695: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9696:
1.963 raeburn 9697: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9698:
1.286 matthew 9699: =back
1.297 matthew 9700:
9701: =item *
9702:
9703: modify_student_enrollment
9704:
9705: Change a students enrollment status in a class. The environment variable
9706: 'role.request.course' must be defined for this function to proceed.
9707:
9708: Inputs:
9709:
9710: =over 4
9711:
9712: =item $udom, students domain
9713:
9714: =item $uname, students name
9715:
9716: =item $uid, students user id
9717:
9718: =item $first, students first name
9719:
9720: =item $middle
9721:
9722: =item $last
9723:
9724: =item $gene
9725:
9726: =item $usec
9727:
9728: =item $end
9729:
9730: =item $start
9731:
1.957 raeburn 9732: =item $type
9733:
9734: =item $locktype
9735:
9736: =item $cid
9737:
9738: =item $selfenroll
9739:
9740: =item $context
9741:
1.297 matthew 9742: =back
9743:
1.191 harris41 9744:
9745: =item *
9746:
1.243 albertel 9747: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9748: custom role; give a custom role to a user for the level given by URL. Specify
9749: name and domain of role author, and role name
1.191 harris41 9750:
9751: =item *
9752:
1.243 albertel 9753: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9754:
9755: =item *
9756:
1.243 albertel 9757: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9758:
9759: =back
9760:
9761: =head2 Course Infomation
9762:
9763: =over 4
1.191 harris41 9764:
9765: =item *
9766:
1.631 albertel 9767: coursedescription($courseid) : returns a hash of information about the
9768: specified course id, including all environment settings for the
9769: course, the description of the course will be in the hash under the
9770: key 'description'
1.191 harris41 9771:
9772: =item *
9773:
1.624 albertel 9774: resdata($name,$domain,$type,@which) : request for current parameter
9775: setting for a specific $type, where $type is either 'course' or 'user',
9776: @what should be a list of parameters to ask about. This routine caches
9777: answers for 5 minutes.
1.243 albertel 9778:
1.877 foxr 9779: =item *
9780:
9781: get_courseresdata($courseid, $domain) : dump the entire course resource
9782: data base, returning a hash that is keyed by the resource name and has
9783: values that are the resource value. I believe that the timestamps and
9784: versions are also returned.
9785:
9786:
1.243 albertel 9787: =back
9788:
9789: =head2 Course Modification
9790:
9791: =over 4
1.191 harris41 9792:
9793: =item *
9794:
1.243 albertel 9795: writecoursepref($courseid,%prefs) : write preferences (environment
9796: database) for a course
1.191 harris41 9797:
9798: =item *
9799:
1.243 albertel 9800: createcourse($udom,$description,$url) : make/modify course
9801:
9802: =back
9803:
9804: =head2 Resource Subroutines
9805:
9806: =over 4
1.191 harris41 9807:
9808: =item *
9809:
1.243 albertel 9810: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9811:
9812: =item *
9813:
1.243 albertel 9814: repcopy($filename) : subscribes to the requested file, and attempts to
9815: replicate from the owning library server, Might return
1.607 raeburn 9816: 'unavailable', 'not_found', 'forbidden', 'ok', or
9817: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9818: resource. Expects the local filesystem pathname
9819: (/home/httpd/html/res/....)
9820:
9821: =back
9822:
9823: =head2 Resource Information
9824:
9825: =over 4
1.191 harris41 9826:
9827: =item *
9828:
1.243 albertel 9829: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9830: a vairety of different possible values, $varname should be a request
9831: string, and the other parameters can be used to specify who and what
9832: one is asking about.
9833:
9834: Possible values for $varname are environment.lastname (or other item
9835: from the envirnment hash), user.name (or someother aspect about the
9836: user), resource.0.maxtries (or some other part and parameter of a
9837: resource)
1.204 albertel 9838:
9839: =item *
9840:
1.243 albertel 9841: directcondval($number) : get current value of a condition; reads from a state
9842: string
1.204 albertel 9843:
9844: =item *
9845:
1.243 albertel 9846: condval($condidx) : value of condition index based on state
1.204 albertel 9847:
9848: =item *
9849:
1.243 albertel 9850: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9851: resource's metadata, $what should be either a specific key, or either
9852: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9853: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9854:
9855: this function automatically caches all requests
1.191 harris41 9856:
9857: =item *
9858:
1.243 albertel 9859: metadata_query($query,$custom,$customshow) : make a metadata query against the
9860: network of library servers; returns file handle of where SQL and regex results
9861: will be stored for query
1.191 harris41 9862:
9863: =item *
9864:
1.243 albertel 9865: symbread($filename) : return symbolic list entry (filename argument optional);
9866: returns the data handle
1.191 harris41 9867:
9868: =item *
9869:
1.243 albertel 9870: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9871: a possible symb for the URL in $thisfn, and if is an encryypted
9872: resource that the user accessed using /enc/ returns a 1 on success, 0
9873: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9874: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9875:
1.191 harris41 9876:
9877: =item *
9878:
1.243 albertel 9879: symbclean($symb) : removes versions numbers from a symb, returns the
9880: cleaned symb
1.191 harris41 9881:
9882: =item *
9883:
1.243 albertel 9884: is_on_map($uri) : checks if the $uri is somewhere on the current
9885: course map, user must be in a course for it to work.
1.191 harris41 9886:
9887: =item *
9888:
1.243 albertel 9889: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9890:
9891: =item *
9892:
1.243 albertel 9893: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9894: a random seed, all arguments are optional, if they aren't sent it uses the
9895: environment to derive them. Note: if symb isn't sent and it can't get one
9896: from &symbread it will use the current time as its return value
1.191 harris41 9897:
9898: =item *
9899:
1.243 albertel 9900: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9901: unfakeable, receipt
1.191 harris41 9902:
9903: =item *
9904:
1.620 albertel 9905: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9906:
9907: =item *
9908:
1.243 albertel 9909: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9910:
9911: =item *
9912:
1.243 albertel 9913: 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 9914:
9915: =item *
9916:
1.243 albertel 9917: 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 9918:
9919: =item *
9920:
1.243 albertel 9921: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9922:
9923: =item *
9924:
1.243 albertel 9925: devalidate($symb) : devalidate temporary spreadsheet calculations,
9926: forcing spreadsheet to reevaluate the resource scores next time.
9927:
9928: =back
9929:
9930: =head2 Storing/Retreiving Data
9931:
9932: =over 4
1.191 harris41 9933:
9934: =item *
9935:
1.243 albertel 9936: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9937: for this url; hashref needs to be given and should be a \%hashname; the
9938: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9939: be derived from the env
1.191 harris41 9940:
9941: =item *
9942:
1.243 albertel 9943: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9944: uses critical subroutine
1.191 harris41 9945:
9946: =item *
9947:
1.243 albertel 9948: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9949: all args are optional
1.191 harris41 9950:
9951: =item *
9952:
1.717 albertel 9953: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9954: dumps the complete (or key matching regexp) namespace into a hash
9955: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9956: normally &store()ed into
9957:
9958: $range should be either an integer '100' (give me the first 100
9959: matching records)
9960: or be two integers sperated by a - with no spaces
9961: '30-50' (give me the 30th through the 50th matching
9962: records)
9963:
9964:
9965: =item *
9966:
9967: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9968: replaces a &store() version of data with a replacement set of data
9969: for a particular resource in a namespace passed in the $storehash hash
9970: reference
9971:
9972: =item *
9973:
1.243 albertel 9974: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9975: works very similar to store/cstore, but all data is stored in a
9976: temporary location and can be reset using tmpreset, $storehash should
9977: be a hash reference, returns nothing on success
1.191 harris41 9978:
9979: =item *
9980:
1.243 albertel 9981: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9982: similar to restore, but all data is stored in a temporary location and
9983: can be reset using tmpreset. Returns a hash of values on success,
9984: error string otherwise.
1.191 harris41 9985:
9986: =item *
9987:
1.243 albertel 9988: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9989: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9990:
9991: =item *
9992:
1.243 albertel 9993: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9994: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9995:
9996: =item *
9997:
1.243 albertel 9998: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9999: namesp ($udom and $uname are optional)
1.191 harris41 10000:
10001: =item *
10002:
1.702 albertel 10003: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10004: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10005: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10006:
1.702 albertel 10007: $range should be either an integer '100' (give me the first 100
10008: matching records)
10009: or be two integers sperated by a - with no spaces
10010: '30-50' (give me the 30th through the 50th matching
10011: records)
1.449 matthew 10012: =item *
10013:
10014: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10015: $store can be a scalar, an array reference, or if the amount to be
10016: incremented is > 1, a hash reference.
10017:
10018: ($udom and $uname are optional)
1.191 harris41 10019:
10020: =item *
10021:
1.243 albertel 10022: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10023: ($udom and $uname are optional)
1.191 harris41 10024:
10025: =item *
10026:
1.243 albertel 10027: cput($namespace,$storehash,$udom,$uname) : critical put
10028: ($udom and $uname are optional)
1.191 harris41 10029:
10030: =item *
10031:
1.748 albertel 10032: newput($namespace,$storehash,$udom,$uname) :
10033:
10034: Attempts to store the items in the $storehash, but only if they don't
10035: currently exist, if this succeeds you can be certain that you have
10036: successfully created a new key value pair in the $namespace db.
10037:
10038:
10039: Args:
10040: $namespace: name of database to store values to
10041: $storehash: hashref to store to the db
10042: $udom: (optional) domain of user containing the db
10043: $uname: (optional) name of user caontaining the db
10044:
10045: Returns:
10046: 'ok' -> succeeded in storing all keys of $storehash
10047: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10048: least <key> already existed in the db (other
10049: requested keys may also already exist)
1.967 bisitz 10050: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10051: 'con_lost' -> unable to contact request server
10052: 'refused' -> action was not allowed by remote machine
10053:
10054:
10055: =item *
10056:
1.243 albertel 10057: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10058: reference filled in from namesp (encrypts the return communication)
10059: ($udom and $uname are optional)
1.191 harris41 10060:
10061: =item *
10062:
1.243 albertel 10063: log($udom,$name,$home,$message) : write to permanent log for user; use
10064: critical subroutine
10065:
1.806 raeburn 10066: =item *
10067:
1.860 raeburn 10068: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10069: array reference filled in from namespace found in domain level on either
10070: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10071:
10072: =item *
10073:
1.860 raeburn 10074: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10075: domain level either on specified domain server ($uhome) or primary domain
10076: server ($udom and $uhome are optional)
1.806 raeburn 10077:
1.943 raeburn 10078: =item *
10079:
10080: get_domain_defaults($target_domain) : returns hash with defaults for
10081: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10082: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10083: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10084: Values are retrieved from cache (if current), or from domain's configuration.db
10085: (if available), or lastly from values in lonTabs/dns_domain,tab,
10086: or lonTabs/domain.tab.
10087:
10088: %domdefaults = &get_auth_defaults($target_domain);
10089:
1.243 albertel 10090: =back
10091:
10092: =head2 Network Status Functions
10093:
10094: =over 4
1.191 harris41 10095:
10096: =item *
10097:
10098: dirlist($uri) : return directory list based on URI
10099:
10100: =item *
10101:
1.243 albertel 10102: spareserver() : find server with least workload from spare.tab
10103:
1.986 foxr 10104:
10105: =item *
10106:
10107: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10108: if there is no corresponding loncapa host.
10109:
1.243 albertel 10110: =back
10111:
1.986 foxr 10112:
1.243 albertel 10113: =head2 Apache Request
10114:
10115: =over 4
1.191 harris41 10116:
10117: =item *
10118:
1.243 albertel 10119: ssi($url,%hash) : server side include, does a complete request cycle on url to
10120: localhost, posts hash
10121:
10122: =back
10123:
10124: =head2 Data to String to Data
10125:
10126: =over 4
1.191 harris41 10127:
10128: =item *
10129:
1.243 albertel 10130: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10131: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10132:
10133: =item *
10134:
1.243 albertel 10135: hashref2str($hashref) : convert a hashref into a string complete with
10136: escaping and '=' and '&' separators, supports elements that are
10137: arrayrefs and hashrefs
1.191 harris41 10138:
10139: =item *
10140:
1.243 albertel 10141: arrayref2str($arrayref) : convert an arrayref into a string complete
10142: with escaping and '&' separators, supports elements that are arrayrefs
10143: and hashrefs
1.191 harris41 10144:
10145: =item *
10146:
1.243 albertel 10147: str2hash($string) : convert string to hash using unescaping and
10148: splitting on '=' and '&', supports elements that are arrayrefs and
10149: hashrefs
1.191 harris41 10150:
10151: =item *
10152:
1.243 albertel 10153: str2array($string) : convert string to hash using unescaping and
10154: splitting on '&', supports elements that are arrayrefs and hashrefs
10155:
10156: =back
10157:
10158: =head2 Logging Routines
10159:
10160: =over 4
10161:
10162: These routines allow one to make log messages in the lonnet.log and
10163: lonnet.perm logfiles.
1.191 harris41 10164:
10165: =item *
10166:
1.243 albertel 10167: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10168:
10169: =item *
10170:
1.243 albertel 10171: logthis() : append message to the normal lonnet.log file, it gets
10172: preiodically rolled over and deleted.
1.191 harris41 10173:
10174: =item *
10175:
1.243 albertel 10176: logperm() : append a permanent message to lonnet.perm.log, this log
10177: file never gets deleted by any automated portion of the system, only
10178: messages of critical importance should go in here.
10179:
10180: =back
10181:
10182: =head2 General File Helper Routines
10183:
10184: =over 4
1.191 harris41 10185:
10186: =item *
10187:
1.481 raeburn 10188: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10189: (a) files in /uploaded
10190: (i) If a local copy of the file exists -
10191: compares modification date of local copy with last-modified date for
10192: definitive version stored on home server for course. If local copy is
10193: stale, requests a new version from the home server and stores it.
10194: If the original has been removed from the home server, then local copy
10195: is unlinked.
10196: (ii) If local copy does not exist -
10197: requests the file from the home server and stores it.
10198:
10199: If $caller is 'uploadrep':
10200: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10201: for request for files originally uploaded via DOCS.
10202: - returns 'ok' if fresh local copy now available, -1 otherwise.
10203:
10204: Otherwise:
10205: This indicates a call from the content generation phase of the request.
10206: - returns the entire contents of the file or -1.
10207:
10208: (b) files in /res
10209: - returns the entire contents of a file or -1;
10210: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10211:
1.712 albertel 10212:
10213: =item *
10214:
10215: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10216: reference
10217:
10218: returns either a stat() list of data about the file or an empty list
10219: if the file doesn't exist or couldn't find out about it (connection
10220: problems or user unknown)
10221:
1.191 harris41 10222: =item *
10223:
1.243 albertel 10224: filelocation($dir,$file) : returns file system location of a file
10225: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10226: directory that relative $file lookups are to looked in ($dir of /a/dir
10227: and a file of ../bob will become /a/bob)
1.191 harris41 10228:
10229: =item *
10230:
10231: hreflocation($dir,$file) : returns file system location or a URL; same as
10232: filelocation except for hrefs
10233:
10234: =item *
10235:
10236: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10237:
1.243 albertel 10238: =back
10239:
1.608 albertel 10240: =head2 Usererfile file routines (/uploaded*)
10241:
10242: =over 4
10243:
10244: =item *
10245:
10246: userfileupload(): main rotine for putting a file in a user or course's
10247: filespace, arguments are,
10248:
1.620 albertel 10249: formname - required - this is the name of the element in $env where the
1.608 albertel 10250: filename, and the contents of the file to create/modifed exist
1.620 albertel 10251: the filename is in $env{'form.'.$formname.'.filename'} and the
10252: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10253: coursedoc - if true, store the file in the course of the active role
10254: of the current user
10255: subdir - required - subdirectory to put the file in under ../userfiles/
10256: if undefined, it will be placed in "unknown"
10257:
10258: (This routine calls clean_filename() to remove any dangerous
10259: characters from the filename, and then calls finuserfileupload() to
10260: complete the transaction)
10261:
10262: returns either the url of the uploaded file (/uploaded/....) if successful
10263: and /adm/notfound.html if unsuccessful
10264:
10265: =item *
10266:
10267: clean_filename(): routine for cleaing a filename up for storage in
10268: userfile space, argument is:
10269:
10270: filename - proposed filename
10271:
10272: returns: the new clean filename
10273:
10274: =item *
10275:
10276: finishuserfileupload(): routine that creaes and sends the file to
10277: userspace, probably shouldn't be called directly
10278:
10279: docuname: username or courseid of destination for the file
10280: docudom: domain of user/course of destination for the file
10281: formname: same as for userfileupload()
10282: fname: filename (inculding subdirectories) for the file
10283:
10284: returns either the url of the uploaded file (/uploaded/....) if successful
10285: and /adm/notfound.html if unsuccessful
10286:
10287: =item *
10288:
10289: renameuserfile(): renames an existing userfile to a new name
10290:
10291: Args:
10292: docuname: username or courseid of destination for the file
10293: docudom: domain of user/course of destination for the file
10294: old: current file name (including any subdirs under userfiles)
10295: new: desired file name (including any subdirs under userfiles)
10296:
10297: =item *
10298:
10299: mkdiruserfile(): creates a directory is a userfiles dir
10300:
10301: Args:
10302: docuname: username or courseid of destination for the file
10303: docudom: domain of user/course of destination for the file
10304: dir: dir to create (including any subdirs under userfiles)
10305:
10306: =item *
10307:
10308: removeuserfile(): removes a file that exists in userfiles
10309:
10310: Args:
10311: docuname: username or courseid of destination for the file
10312: docudom: domain of user/course of destination for the file
10313: fname: filname to delete (including any subdirs under userfiles)
10314:
10315: =item *
10316:
10317: removeuploadedurl(): convience function for removeuserfile()
10318:
10319: Args:
10320: url: a full /uploaded/... url to delete
10321:
1.747 albertel 10322: =item *
10323:
10324: get_portfile_permissions():
10325: Args:
10326: domain: domain of user or course contain the portfolio files
10327: user: name of user or num of course contain the portfolio files
10328: Returns:
10329: hashref of a dump of the proper file_permissions.db
10330:
10331:
10332: =item *
10333:
10334: get_access_controls():
10335:
10336: Args:
10337: current_permissions: the hash ref returned from get_portfile_permissions()
10338: group: (optional) the group you want the files associated with
10339: file: (optional) the file you want access info on
10340:
10341: Returns:
1.749 raeburn 10342: a hash (keys are file names) of hashes containing
10343: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10344: values are XML containing access control settings (see below)
1.747 albertel 10345:
10346: Internal notes:
10347:
1.749 raeburn 10348: access controls are stored in file_permissions.db as key=value pairs.
10349: key -> path to file/file_name\0uniqueID:scope_end_start
10350: where scope -> public,guest,course,group,domains or users.
10351: end -> UNIX time for end of access (0 -> no end date)
10352: start -> UNIX time for start of access
10353:
10354: value -> XML description of access control
10355: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10356: <start></start>
10357: <end></end>
10358:
10359: <password></password> for scope type = guest
10360:
10361: <domain></domain> for scope type = course or group
10362: <number></number>
10363: <roles id="">
10364: <role></role>
10365: <access></access>
10366: <section></section>
10367: <group></group>
10368: </roles>
10369:
10370: <dom></dom> for scope type = domains
10371:
10372: <users> for scope type = users
10373: <user>
10374: <uname></uname>
10375: <udom></udom>
10376: </user>
10377: </users>
10378: </scope>
10379:
10380: Access data is also aggregated for each file in an additional key=value pair:
10381: key -> path to file/file_name\0accesscontrol
10382: value -> reference to hash
10383: hash contains key = value pairs
10384: where key = uniqueID:scope_end_start
10385: value = UNIX time record was last updated
10386:
10387: Used to improve speed of look-ups of access controls for each file.
10388:
10389: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10390:
10391: modify_access_controls():
10392:
10393: Modifies access controls for a portfolio file
10394: Args
10395: 1. file name
10396: 2. reference to hash of required changes,
10397: 3. domain
10398: 4. username
10399: where domain,username are the domain of the portfolio owner
10400: (either a user or a course)
10401:
10402: Returns:
10403: 1. result of additions or updates ('ok' or 'error', with error message).
10404: 2. result of deletions ('ok' or 'error', with error message).
10405: 3. reference to hash of any new or updated access controls.
10406: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10407: key = integer (inbound ID)
10408: value = uniqueID
1.747 albertel 10409:
1.608 albertel 10410: =back
10411:
1.243 albertel 10412: =head2 HTTP Helper Routines
10413:
10414: =over 4
10415:
1.191 harris41 10416: =item *
10417:
10418: escape() : unpack non-word characters into CGI-compatible hex codes
10419:
10420: =item *
10421:
10422: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10423:
1.243 albertel 10424: =back
10425:
10426: =head1 PRIVATE SUBROUTINES
10427:
10428: =head2 Underlying communication routines (Shouldn't call)
10429:
10430: =over 4
10431:
10432: =item *
10433:
10434: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10435:
10436: =item *
10437:
10438: reply() : uses subreply to send a message to remote machine, logs all failures
10439:
10440: =item *
10441:
10442: critical() : passes a critical message to another server; if cannot
10443: get through then place message in connection buffer directory and
10444: returns con_delayed, if incapable of saving message, returns
10445: con_failed
10446:
10447: =item *
10448:
10449: reconlonc() : tries to reconnect lonc client processes.
10450:
10451: =back
10452:
10453: =head2 Resource Access Logging
10454:
10455: =over 4
10456:
10457: =item *
10458:
10459: flushcourselogs() : flush (save) buffer logs and access logs
10460:
10461: =item *
10462:
10463: courselog($what) : save message for course in hash
10464:
10465: =item *
10466:
10467: courseacclog($what) : save message for course using &courselog(). Perform
10468: special processing for specific resource types (problems, exams, quizzes, etc).
10469:
1.191 harris41 10470: =item *
10471:
10472: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10473: as a PerlChildExitHandler
1.243 albertel 10474:
10475: =back
10476:
10477: =head2 Other
10478:
10479: =over 4
10480:
10481: =item *
10482:
10483: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10484:
10485: =back
10486:
10487: =cut
1.877 foxr 10488:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>