Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.986
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.986 ! foxr 4: # $Id: lonnet.pm,v 1.985 2009/02/08 20:28:52 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;
1.986 ! foxr 77: use IO::Socket;
1.977 amueller 78:
1.486 www 79: # use Date::Parse;
1.871 albertel 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 81: $_64bit %env %protocol);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.539 albertel 93: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.676 albertel 99:
1.195 www 100: my $readit;
1.550 foxr 101: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 102:
1.977 amueller 103: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
104:
1.619 albertel 105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
1.449 matthew 110:
1.1 albertel 111: # --------------------------------------------------------------------- Logging
1.729 www 112: {
113: my $logid;
114: sub instructor_log {
1.957 raeburn 115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
1.729 www 120: $logid++;
1.957 raeburn 121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 123: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 127: 'exe_time' => $now,
1.730 www 128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
1.957 raeburn 134: },$cdom,$cnum);
1.729 www 135: }
136: }
1.1 albertel 137:
1.163 harris41 138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
1.1 albertel 148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
1.448 albertel 153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 ! foxr 154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
! 155: print $fh $logstring;
1.448 albertel 156: close($fh);
157: }
1.1 albertel 158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
1.448 albertel 166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
1.850 albertel 173: sub create_connection {
1.853 albertel 174: my ($hostname,$lonid) = @_;
1.851 albertel 175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
1.890 albertel 179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
1.983 raeburn 186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
1.850 albertel 200:
1.1 albertel 201: # -------------------------------------------------- Non-critical communication
202: sub subreply {
203: my ($cmd,$server)=@_;
1.838 albertel 204: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 205: #
206: # With loncnew process trimming, there's a timing hole between lonc server
207: # process exit and the master server picking up the listen on the AF_UNIX
208: # socket. In that time interval, a lock file will exist:
209:
210: my $lockfile=$peerfile.".lock";
211: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
212: sleep(1);
213: }
214: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 215: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 216: #
1.550 foxr 217: # We'll give the connection a few tries before abandoning it. If
218: # connection is not possible, we'll con_lost back to the client.
219: #
220: my $client;
221: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
222: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
223: Type => SOCK_STREAM,
224: Timeout => 10);
1.869 albertel 225: if ($client) {
1.550 foxr 226: last; # Connected!
1.850 albertel 227: } else {
1.853 albertel 228: &create_connection(&hostname($server),$server);
1.550 foxr 229: }
1.850 albertel 230: sleep(1); # Try again later if failed connection.
1.550 foxr 231: }
232: my $answer;
233: if ($client) {
1.704 albertel 234: print $client "sethost:$server:$cmd\n";
1.550 foxr 235: $answer=<$client>;
236: if (!$answer) { $answer="con_lost"; }
237: chomp($answer);
238: } else {
239: $answer = 'con_lost'; # Failed connection.
240: }
1.1 albertel 241: return $answer;
242: }
243:
244: sub reply {
245: my ($cmd,$server)=@_;
1.838 albertel 246: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 247: my $answer=subreply($cmd,$server);
1.65 www 248: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 249: &logthis("<font color=\"blue\">WARNING:".
1.12 www 250: " $cmd to $server returned $answer</font>");
251: }
1.1 albertel 252: return $answer;
253: }
254:
255: # ----------------------------------------------------------- Send USR1 to lonc
256:
257: sub reconlonc {
1.891 albertel 258: my ($lonid) = @_;
259: my $hostname = &hostname($lonid);
260: if ($lonid) {
261: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
262: if ($hostname && -e $peerfile) {
263: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
264: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
265: Type => SOCK_STREAM,
266: Timeout => 10);
267: if ($client) {
268: print $client ("reset_retries\n");
269: my $answer=<$client>;
270: #reset just this one.
271: }
272: }
273: return;
274: }
275:
1.836 www 276: &logthis("Trying to reconnect lonc");
1.1 albertel 277: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 278: if (open(my $fh,"<$loncfile")) {
1.1 albertel 279: my $loncpid=<$fh>;
280: chomp($loncpid);
281: if (kill 0 => $loncpid) {
282: &logthis("lonc at pid $loncpid responding, sending USR1");
283: kill USR1 => $loncpid;
284: sleep 1;
1.836 www 285: } else {
1.12 www 286: &logthis(
1.672 albertel 287: "<font color=\"blue\">WARNING:".
1.12 www 288: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 289: }
290: } else {
1.836 www 291: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 292: }
293: }
294:
295: # ------------------------------------------------------ Critical communication
1.12 www 296:
1.1 albertel 297: sub critical {
298: my ($cmd,$server)=@_;
1.838 albertel 299: unless (&hostname($server)) {
1.672 albertel 300: &logthis("<font color=\"blue\">WARNING:".
1.89 www 301: " Critical message to unknown server ($server)</font>");
302: return 'no_such_host';
303: }
1.1 albertel 304: my $answer=reply($cmd,$server);
305: if ($answer eq 'con_lost') {
306: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 307: my $answer=reply($cmd,$server);
1.1 albertel 308: if ($answer eq 'con_lost') {
309: my $now=time;
310: my $middlename=$cmd;
1.5 www 311: $middlename=substr($middlename,0,16);
1.1 albertel 312: $middlename=~s/\W//g;
313: my $dfilename=
1.305 www 314: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
315: $dumpcount++;
1.1 albertel 316: {
1.448 albertel 317: my $dfh;
318: if (open($dfh,">$dfilename")) {
319: print $dfh "$cmd\n";
320: close($dfh);
321: }
1.1 albertel 322: }
323: sleep 2;
324: my $wcmd='';
325: {
1.448 albertel 326: my $dfh;
327: if (open($dfh,"<$dfilename")) {
328: $wcmd=<$dfh>;
329: close($dfh);
330: }
1.1 albertel 331: }
332: chomp($wcmd);
1.7 www 333: if ($wcmd eq $cmd) {
1.672 albertel 334: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 335: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 336: &logperm("D:$server:$cmd");
337: return 'con_delayed';
338: } else {
1.672 albertel 339: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 340: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 341: &logperm("F:$server:$cmd");
342: return 'con_failed';
343: }
344: }
345: }
346: return $answer;
1.405 albertel 347: }
348:
1.755 albertel 349: # ------------------------------------------- check if return value is an error
350:
351: sub error {
352: my ($result) = @_;
1.756 albertel 353: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 354: if ($2 == 2) { return undef; }
355: return $1;
356: }
357: return undef;
358: }
359:
1.783 albertel 360: sub convert_and_load_session_env {
361: my ($lonidsdir,$handle)=@_;
362: my @profile;
363: {
1.917 albertel 364: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
365: if (!$opened) {
1.915 albertel 366: return 0;
367: }
1.783 albertel 368: flock($idf,LOCK_SH);
369: @profile=<$idf>;
370: close($idf);
371: }
372: my %temp_env;
373: foreach my $line (@profile) {
1.786 albertel 374: if ($line !~ m/=/) {
375: return 0;
376: }
1.783 albertel 377: chomp($line);
378: my ($envname,$envvalue)=split(/=/,$line,2);
379: $temp_env{&unescape($envname)} = &unescape($envvalue);
380: }
381: unlink("$lonidsdir/$handle.id");
382: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
383: 0640)) {
384: %disk_env = %temp_env;
385: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
386: untie(%disk_env);
387: }
1.786 albertel 388: return 1;
1.783 albertel 389: }
390:
1.374 www 391: # ------------------------------------------- Transfer profile into environment
1.780 albertel 392: my $env_loaded;
393: sub transfer_profile_to_env {
1.788 albertel 394: my ($lonidsdir,$handle,$force_transfer) = @_;
395: if (!$force_transfer && $env_loaded) { return; }
1.374 www 396:
1.720 albertel 397: if (!defined($lonidsdir)) {
398: $lonidsdir = $perlvar{'lonIDsDir'};
399: }
400: if (!defined($handle)) {
401: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
402: }
403:
1.786 albertel 404: my $convert;
405: {
1.917 albertel 406: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
407: if (!$opened) {
1.915 albertel 408: return;
409: }
1.786 albertel 410: flock($idf,LOCK_SH);
411: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
412: &GDBM_READER(),0640)) {
413: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
414: untie(%disk_env);
415: } else {
416: $convert = 1;
417: }
418: }
419: if ($convert) {
420: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
421: &logthis("Failed to load session, or convert session.");
422: }
1.374 www 423: }
1.783 albertel 424:
1.786 albertel 425: my %remove;
1.783 albertel 426: while ( my $envname = each(%env) ) {
1.433 matthew 427: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
428: if ($time < time-300) {
1.783 albertel 429: $remove{$key}++;
1.433 matthew 430: }
431: }
432: }
1.783 albertel 433:
1.619 albertel 434: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 435: $env_loaded=1;
1.783 albertel 436: foreach my $expired_key (keys(%remove)) {
1.433 matthew 437: &delenv($expired_key);
1.374 www 438: }
1.1 albertel 439: }
440:
1.916 albertel 441: # ---------------------------------------------------- Check for valid session
442: sub check_for_valid_session {
443: my ($r) = @_;
444: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
445: my $lonid=$cookies{'lonID'};
446: return undef if (!$lonid);
447:
448: my $handle=&LONCAPA::clean_handle($lonid->value);
449: my $lonidsdir=$r->dir_config('lonIDsDir');
450: return undef if (!-e "$lonidsdir/$handle.id");
451:
1.917 albertel 452: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
453: return undef if (!$opened);
1.916 albertel 454:
455: flock($idf,LOCK_SH);
456: my %disk_env;
457: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
458: &GDBM_READER(),0640)) {
459: return undef;
460: }
461:
462: if (!defined($disk_env{'user.name'})
463: || !defined($disk_env{'user.domain'})) {
464: return undef;
465: }
466: return $handle;
467: }
468:
1.830 albertel 469: sub timed_flock {
470: my ($file,$lock_type) = @_;
471: my $failed=0;
472: eval {
473: local $SIG{__DIE__}='DEFAULT';
474: local $SIG{ALRM}=sub {
475: $failed=1;
476: die("failed lock");
477: };
478: alarm(13);
479: flock($file,$lock_type);
480: alarm(0);
481: };
482: if ($failed) {
483: return undef;
484: } else {
485: return 1;
486: }
487: }
488:
1.5 www 489: # ---------------------------------------------------------- Append Environment
490:
491: sub appenv {
1.949 raeburn 492: my ($newenv,$roles) = @_;
493: if (ref($newenv) eq 'HASH') {
494: foreach my $key (keys(%{$newenv})) {
495: my $refused = 0;
496: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
497: $refused = 1;
498: if (ref($roles) eq 'ARRAY') {
499: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
500: if (grep(/^\Q$role\E$/,@{$roles})) {
501: $refused = 0;
502: }
503: }
504: }
505: if ($refused) {
506: &logthis("<font color=\"blue\">WARNING: ".
507: "Attempt to modify environment ".$key." to ".$newenv->{$key}
508: .'</font>');
509: delete($newenv->{$key});
510: } else {
511: $env{$key}=$newenv->{$key};
512: }
513: }
514: my $opened = open(my $env_file,'+<',$env{'user.environment'});
515: if ($opened
516: && &timed_flock($env_file,LOCK_EX)
517: &&
518: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
519: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
520: while (my ($key,$value) = each(%{$newenv})) {
521: $disk_env{$key} = $value;
522: }
523: untie(%disk_env);
1.35 www 524: }
1.191 harris41 525: }
1.56 www 526: return 'ok';
527: }
528: # ----------------------------------------------------- Delete from Environment
529:
530: sub delenv {
531: my $delthis=shift;
532: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 533: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 534: "Attempt to delete from environment ".$delthis);
535: return 'error';
536: }
1.917 albertel 537: my $opened = open(my $env_file,'+<',$env{'user.environment'});
538: if ($opened
1.915 albertel 539: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 540: &&
541: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
542: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 543: foreach my $key (keys(%disk_env)) {
1.981 raeburn 544: if ($key=~/^\Q$delthis\E/) {
1.915 albertel 545: delete($env{$key});
546: delete($disk_env{$key});
547: }
1.448 albertel 548: }
1.783 albertel 549: untie(%disk_env);
1.5 www 550: }
551: return 'ok';
1.369 albertel 552: }
553:
1.790 albertel 554: sub get_env_multiple {
555: my ($name) = @_;
556: my @values;
557: if (defined($env{$name})) {
558: # exists is it an array
559: if (ref($env{$name})) {
560: @values=@{ $env{$name} };
561: } else {
562: $values[0]=$env{$name};
563: }
564: }
565: return(@values);
566: }
567:
1.958 www 568: # ------------------------------------------------------------------- Locking
569:
570: sub set_lock {
571: my ($text)=@_;
572: $locknum++;
573: my $id=$$.'-'.$locknum;
574: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
575: 'session.lock.'.$id => $text});
576: return $id;
577: }
578:
579: sub get_locks {
580: my $num=0;
581: my %texts=();
582: foreach my $lock (split(/\,/,$env{'session.locks'})) {
583: if ($lock=~/\w/) {
584: $num++;
585: $texts{$lock}=$env{'session.lock.'.$lock};
586: }
587: }
588: return ($num,%texts);
589: }
590:
591: sub remove_lock {
592: my ($id)=@_;
593: my $newlocks='';
594: foreach my $lock (split(/\,/,$env{'session.locks'})) {
595: if (($lock=~/\w/) && ($lock ne $id)) {
596: $newlocks.=','.$lock;
597: }
598: }
599: &appenv({'session.locks' => $newlocks});
600: &delenv('session.lock.'.$id);
601: }
602:
603: sub remove_all_locks {
604: my $activelocks=$env{'session.locks'};
605: foreach my $lock (split(/\,/,$env{'session.locks'})) {
606: if ($lock=~/\w/) {
607: &remove_lock($lock);
608: }
609: }
610: }
611:
612:
1.369 albertel 613: # ------------------------------------------ Find out current server userload
614: sub userload {
615: my $numusers=0;
616: {
617: opendir(LONIDS,$perlvar{'lonIDsDir'});
618: my $filename;
619: my $curtime=time;
620: while ($filename=readdir(LONIDS)) {
1.925 albertel 621: next if ($filename eq '.' || $filename eq '..');
622: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 623: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 624: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 625: }
626: closedir(LONIDS);
627: }
628: my $userloadpercent=0;
629: my $maxuserload=$perlvar{'lonUserLoadLim'};
630: if ($maxuserload) {
1.371 albertel 631: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 632: }
1.372 albertel 633: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 634: return $userloadpercent;
1.283 www 635: }
636:
637: # ------------------------------------------ Fight off request when overloaded
638:
639: sub overloaderror {
640: my ($r,$checkserver)=@_;
641: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
642: my $loadavg;
643: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 644: open(my $loadfile,'/proc/loadavg');
1.283 www 645: $loadavg=<$loadfile>;
646: $loadavg =~ s/\s.*//g;
1.285 matthew 647: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 648: close($loadfile);
1.283 www 649: } else {
650: $loadavg=&reply('load',$checkserver);
651: }
1.285 matthew 652: my $overload=$loadavg-100;
1.283 www 653: if ($overload>0) {
1.285 matthew 654: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 655: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 656: return 413;
1.283 www 657: }
658: return '';
1.5 www 659: }
1.1 albertel 660:
661: # ------------------------------ Find server with least workload from spare.tab
1.11 www 662:
1.1 albertel 663: sub spareserver {
1.670 albertel 664: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 665: my $spare_server;
1.370 albertel 666: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 667: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
668: : $userloadpercent;
669:
670: foreach my $try_server (@{ $spareid{'primary'} }) {
671: ($spare_server, $lowest_load) =
672: &compare_server_load($try_server, $spare_server, $lowest_load);
673: }
674:
675: my $found_server = ($spare_server ne '' && $lowest_load < 100);
676:
677: if (!$found_server) {
678: foreach my $try_server (@{ $spareid{'default'} }) {
679: ($spare_server, $lowest_load) =
680: &compare_server_load($try_server, $spare_server, $lowest_load);
681: }
682: }
683:
684: if (!$want_server_name) {
1.968 raeburn 685: my $protocol = 'http';
686: if ($protocol{$spare_server} eq 'https') {
687: $protocol = $protocol{$spare_server};
688: }
689: $spare_server = $protocol.'://'.&hostname($spare_server);
1.784 albertel 690: }
691: return $spare_server;
692: }
693:
694: sub compare_server_load {
695: my ($try_server, $spare_server, $lowest_load) = @_;
696:
697: my $loadans = &reply('load', $try_server);
698: my $userloadans = &reply('userload',$try_server);
699:
700: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
701: next; #didn't get a number from the server
702: }
703:
704: my $load;
705: if ($loadans =~ /\d/) {
706: if ($userloadans =~ /\d/) {
707: #both are numbers, pick the bigger one
708: $load = ($loadans > $userloadans) ? $loadans
709: : $userloadans;
1.411 albertel 710: } else {
1.784 albertel 711: $load = $loadans;
1.411 albertel 712: }
1.784 albertel 713: } else {
714: $load = $userloadans;
715: }
716:
717: if (($load =~ /\d/) && ($load < $lowest_load)) {
718: $spare_server = $try_server;
719: $lowest_load = $load;
1.370 albertel 720: }
1.784 albertel 721: return ($spare_server,$lowest_load);
1.202 matthew 722: }
1.914 albertel 723:
724: # --------------------------- ask offload servers if user already has a session
725: sub find_existing_session {
726: my ($udom,$uname) = @_;
727: foreach my $try_server (@{ $spareid{'primary'} },
728: @{ $spareid{'default'} }) {
729: return $try_server if (&has_user_session($try_server, $udom, $uname));
730: }
731: return;
732: }
733:
734: # -------------------------------- ask if server already has a session for user
735: sub has_user_session {
736: my ($lonid,$udom,$uname) = @_;
737: my $result = &reply(join(':','userhassession',
738: map {&escape($_)} ($udom,$uname)),$lonid);
739: return 1 if ($result eq 'ok');
740:
741: return 0;
742: }
743:
1.202 matthew 744: # --------------------------------------------- Try to change a user's password
745:
746: sub changepass {
1.799 raeburn 747: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 748: $currentpass = &escape($currentpass);
749: $newpass = &escape($newpass);
1.799 raeburn 750: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 751: $server);
752: if (! $answer) {
753: &logthis("No reply on password change request to $server ".
754: "by $uname in domain $udom.");
755: } elsif ($answer =~ "^ok") {
756: &logthis("$uname in $udom successfully changed their password ".
757: "on $server.");
758: } elsif ($answer =~ "^pwchange_failure") {
759: &logthis("$uname in $udom was unable to change their password ".
760: "on $server. The action was blocked by either lcpasswd ".
761: "or pwchange");
762: } elsif ($answer =~ "^non_authorized") {
763: &logthis("$uname in $udom did not get their password correct when ".
764: "attempting to change it on $server.");
765: } elsif ($answer =~ "^auth_mode_error") {
766: &logthis("$uname in $udom attempted to change their password despite ".
767: "not being locally or internally authenticated on $server.");
768: } elsif ($answer =~ "^unknown_user") {
769: &logthis("$uname in $udom attempted to change their password ".
770: "on $server but were unable to because $server is not ".
771: "their home server.");
772: } elsif ($answer =~ "^refused") {
773: &logthis("$server refused to change $uname in $udom password because ".
774: "it was sent an unencrypted request to change the password.");
775: }
776: return $answer;
1.1 albertel 777: }
778:
1.169 harris41 779: # ----------------------- Try to determine user's current authentication scheme
780:
781: sub queryauthenticate {
782: my ($uname,$udom)=@_;
1.456 albertel 783: my $uhome=&homeserver($uname,$udom);
784: if (!$uhome) {
785: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
786: return 'no_host';
787: }
788: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
789: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
790: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 791: }
1.456 albertel 792: return $answer;
1.169 harris41 793: }
794:
1.1 albertel 795: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 796:
1.1 albertel 797: sub authenticate {
1.952 raeburn 798: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 799: $upass=&escape($upass);
800: $uname= &LONCAPA::clean_username($uname);
1.836 www 801: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 802: my $newhome;
1.836 www 803: if ((!$uhome) || ($uhome eq 'no_host')) {
804: # Maybe the machine was offline and only re-appeared again recently?
805: &reconlonc();
806: # One more
1.952 raeburn 807: $uhome=&homeserver($uname,$udom,1);
808: if (($uhome eq 'no_host') && $checkdefauth) {
809: if (defined(&domain($udom,'primary'))) {
810: $newhome=&domain($udom,'primary');
811: }
812: if ($newhome ne '') {
813: $uhome = $newhome;
814: }
815: }
1.836 www 816: if ((!$uhome) || ($uhome eq 'no_host')) {
817: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 818: return 'no_host';
819: }
1.1 albertel 820: }
1.952 raeburn 821: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 822: if ($answer eq 'authorized') {
1.952 raeburn 823: if ($newhome) {
824: &logthis("User $uname at $udom authorized by $uhome, but needs account");
825: return 'no_account_on_host';
826: } else {
827: &logthis("User $uname at $udom authorized by $uhome");
828: return $uhome;
829: }
1.471 albertel 830: }
831: if ($answer eq 'non_authorized') {
832: &logthis("User $uname at $udom rejected by $uhome");
833: return 'no_host';
1.9 www 834: }
1.471 albertel 835: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 836: return 'no_host';
837: }
838:
839: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 840:
1.599 albertel 841: my %homecache;
1.1 albertel 842: sub homeserver {
1.230 stredwic 843: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 844: my $index="$uname:$udom";
1.426 albertel 845:
1.599 albertel 846: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 847:
848: my %servers = &get_servers($udom,'library');
849: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 850: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 851: exists($badServerCache{$tryserver}));
1.841 albertel 852:
853: my $answer=reply("home:$udom:$uname",$tryserver);
854: if ($answer eq 'found') {
855: delete($badServerCache{$tryserver});
856: return $homecache{$index}=$tryserver;
857: } elsif ($answer eq 'no_host') {
858: $badServerCache{$tryserver}=1;
859: }
1.1 albertel 860: }
861: return 'no_host';
1.70 www 862: }
863:
864: # ------------------------------------- Find the usernames behind a list of IDs
865:
866: sub idget {
867: my ($udom,@ids)=@_;
868: my %returnhash=();
869:
1.841 albertel 870: my %servers = &get_servers($udom,'library');
871: foreach my $tryserver (keys(%servers)) {
872: my $idlist=join('&',@ids);
873: $idlist=~tr/A-Z/a-z/;
874: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
875: my @answer=();
876: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
877: @answer=split(/\&/,$reply);
878: } ;
879: my $i;
880: for ($i=0;$i<=$#ids;$i++) {
881: if ($answer[$i]) {
882: $returnhash{$ids[$i]}=$answer[$i];
883: }
884: }
885: }
1.70 www 886: return %returnhash;
887: }
888:
889: # ------------------------------------- Find the IDs behind a list of usernames
890:
891: sub idrget {
892: my ($udom,@unames)=@_;
893: my %returnhash=();
1.800 albertel 894: foreach my $uname (@unames) {
895: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 896: }
1.70 www 897: return %returnhash;
898: }
899:
900: # ------------------------------- Store away a list of names and associated IDs
901:
902: sub idput {
903: my ($udom,%ids)=@_;
904: my %servers=();
1.800 albertel 905: foreach my $uname (keys(%ids)) {
906: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
907: my $uhom=&homeserver($uname,$udom);
1.70 www 908: if ($uhom ne 'no_host') {
1.800 albertel 909: my $id=&escape($ids{$uname});
1.70 www 910: $id=~tr/A-Z/a-z/;
1.800 albertel 911: my $esc_unam=&escape($uname);
1.70 www 912: if ($servers{$uhom}) {
1.800 albertel 913: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 914: } else {
1.800 albertel 915: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 916: }
917: }
1.191 harris41 918: }
1.800 albertel 919: foreach my $server (keys(%servers)) {
920: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 921: }
1.344 www 922: }
923:
1.806 raeburn 924: # ------------------------------------------- get items from domain db files
925:
926: sub get_dom {
1.860 raeburn 927: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 928: my $items='';
929: foreach my $item (@$storearr) {
930: $items.=&escape($item).'&';
931: }
932: $items=~s/\&$//;
1.860 raeburn 933: if (!$udom) {
934: $udom=$env{'user.domain'};
935: if (defined(&domain($udom,'primary'))) {
936: $uhome=&domain($udom,'primary');
937: } else {
1.874 albertel 938: undef($uhome);
1.860 raeburn 939: }
940: } else {
941: if (!$uhome) {
942: if (defined(&domain($udom,'primary'))) {
943: $uhome=&domain($udom,'primary');
944: }
945: }
946: }
947: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 948: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 949: my %returnhash;
1.875 albertel 950: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 951: return %returnhash;
952: }
1.806 raeburn 953: my @pairs=split(/\&/,$rep);
954: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
955: return @pairs;
956: }
957: my $i=0;
958: foreach my $item (@$storearr) {
959: $returnhash{$item}=&thaw_unescape($pairs[$i]);
960: $i++;
961: }
962: return %returnhash;
963: } else {
1.880 banghart 964: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 965: }
966: }
967:
968: # -------------------------------------------- put items in domain db files
969:
970: sub put_dom {
1.860 raeburn 971: my ($namespace,$storehash,$udom,$uhome)=@_;
972: if (!$udom) {
973: $udom=$env{'user.domain'};
974: if (defined(&domain($udom,'primary'))) {
975: $uhome=&domain($udom,'primary');
976: } else {
1.874 albertel 977: undef($uhome);
1.860 raeburn 978: }
979: } else {
980: if (!$uhome) {
981: if (defined(&domain($udom,'primary'))) {
982: $uhome=&domain($udom,'primary');
983: }
984: }
985: }
986: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 987: my $items='';
988: foreach my $item (keys(%$storehash)) {
989: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
990: }
991: $items=~s/\&$//;
992: return &reply("putdom:$udom:$namespace:$items",$uhome);
993: } else {
1.860 raeburn 994: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 995: }
996: }
997:
1.837 raeburn 998: sub retrieve_inst_usertypes {
999: my ($udom) = @_;
1000: my (%returnhash,@order);
1.846 albertel 1001: if (defined(&domain($udom,'primary'))) {
1002: my $uhome=&domain($udom,'primary');
1.837 raeburn 1003: my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960 raeburn 1004: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1005: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1006: return (\%returnhash,\@order);
1007: }
1.837 raeburn 1008: my ($hashitems,$orderitems) = split(/:/,$rep);
1009: my @pairs=split(/\&/,$hashitems);
1010: foreach my $item (@pairs) {
1011: my ($key,$value)=split(/=/,$item,2);
1012: $key = &unescape($key);
1013: next if ($key =~ /^error: 2 /);
1014: $returnhash{$key}=&thaw_unescape($value);
1015: }
1016: my @esc_order = split(/\&/,$orderitems);
1017: foreach my $item (@esc_order) {
1018: push(@order,&unescape($item));
1019: }
1020: } else {
1021: &logthis("get_dom failed - no primary domain server for $udom");
1022: }
1023: return (\%returnhash,\@order);
1024: }
1025:
1.868 raeburn 1026: sub is_domainimage {
1027: my ($url) = @_;
1028: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1029: if (&domain($1) ne '') {
1030: return '1';
1031: }
1032: }
1033: return;
1034: }
1035:
1.899 raeburn 1036: sub inst_directory_query {
1037: my ($srch) = @_;
1038: my $udom = $srch->{'srchdomain'};
1039: my %results;
1040: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1041: my $outcome;
1.899 raeburn 1042: if ($homeserver ne '') {
1.904 albertel 1043: my $queryid=&reply("querysend:instdirsearch:".
1044: &escape($srch->{'srchby'}).':'.
1045: &escape($srch->{'srchterm'}).':'.
1046: &escape($srch->{'srchtype'}),$homeserver);
1047: my $host=&hostname($homeserver);
1048: if ($queryid !~/^\Q$host\E\_/) {
1049: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1050: return;
1051: }
1052: my $response = &get_query_reply($queryid);
1053: my $maxtries = 5;
1054: my $tries = 1;
1055: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1056: $response = &get_query_reply($queryid);
1057: $tries ++;
1058: }
1059:
1060: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1061: if ($response eq 'unavailable') {
1062: $outcome = $response;
1063: } else {
1064: $outcome = 'ok';
1065: my @matches = split(/\n/,$response);
1066: foreach my $match (@matches) {
1067: my ($key,$value) = split(/=/,$match);
1068: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1069: }
1.899 raeburn 1070: }
1071: }
1072: }
1.909 raeburn 1073: return ($outcome,%results);
1.899 raeburn 1074: }
1075:
1076: sub usersearch {
1077: my ($srch) = @_;
1078: my $dom = $srch->{'srchdomain'};
1079: my %results;
1080: my %libserv = &all_library();
1081: my $query = 'usersearch';
1082: foreach my $tryserver (keys(%libserv)) {
1083: if (&host_domain($tryserver) eq $dom) {
1084: my $host=&hostname($tryserver);
1085: my $queryid=
1.911 raeburn 1086: &reply("querysend:".&escape($query).':'.
1087: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1088: &escape($srch->{'srchtype'}).':'.
1089: &escape($srch->{'srchterm'}),$tryserver);
1090: if ($queryid !~/^\Q$host\E\_/) {
1091: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1092: next;
1.899 raeburn 1093: }
1094: my $reply = &get_query_reply($queryid);
1095: my $maxtries = 1;
1096: my $tries = 1;
1097: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1098: $reply = &get_query_reply($queryid);
1099: $tries ++;
1100: }
1101: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1102: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1103: } else {
1.911 raeburn 1104: my @matches;
1105: if ($reply =~ /\n/) {
1106: @matches = split(/\n/,$reply);
1107: } else {
1108: @matches = split(/\&/,$reply);
1109: }
1.899 raeburn 1110: foreach my $match (@matches) {
1111: my ($uname,$udom,%userhash);
1.911 raeburn 1112: foreach my $entry (split(/:/,$match)) {
1113: my ($key,$value) =
1114: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1115: $userhash{$key} = $value;
1116: if ($key eq 'username') {
1117: $uname = $value;
1118: } elsif ($key eq 'domain') {
1119: $udom = $value;
1.911 raeburn 1120: }
1.899 raeburn 1121: }
1122: $results{$uname.':'.$udom} = \%userhash;
1123: }
1124: }
1125: }
1126: }
1127: return %results;
1128: }
1129:
1.912 raeburn 1130: sub get_instuser {
1131: my ($udom,$uname,$id) = @_;
1132: my $homeserver = &domain($udom,'primary');
1133: my ($outcome,%results);
1134: if ($homeserver ne '') {
1135: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1136: &escape($id).':'.&escape($udom),$homeserver);
1137: my $host=&hostname($homeserver);
1138: if ($queryid !~/^\Q$host\E\_/) {
1139: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1140: return;
1141: }
1142: my $response = &get_query_reply($queryid);
1143: my $maxtries = 5;
1144: my $tries = 1;
1145: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1146: $response = &get_query_reply($queryid);
1147: $tries ++;
1148: }
1149: if (!&error($response) && $response ne 'refused') {
1150: if ($response eq 'unavailable') {
1151: $outcome = $response;
1152: } else {
1153: $outcome = 'ok';
1154: my @matches = split(/\n/,$response);
1155: foreach my $match (@matches) {
1156: my ($key,$value) = split(/=/,$match);
1157: $results{&unescape($key)} = &thaw_unescape($value);
1158: }
1159: }
1160: }
1161: }
1162: my %userinfo;
1163: if (ref($results{$uname}) eq 'HASH') {
1164: %userinfo = %{$results{$uname}};
1165: }
1166: return ($outcome,%userinfo);
1167: }
1168:
1169: sub inst_rulecheck {
1.923 raeburn 1170: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1171: my %returnhash;
1172: if ($udom ne '') {
1173: if (ref($rules) eq 'ARRAY') {
1174: @{$rules} = map {&escape($_);} (@{$rules});
1175: my $rulestr = join(':',@{$rules});
1176: my $homeserver=&domain($udom,'primary');
1177: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1178: my $response;
1179: if ($item eq 'username') {
1180: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1181: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1182: $homeserver));
1.923 raeburn 1183: } elsif ($item eq 'id') {
1184: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1185: ':'.&escape($id).':'.$rulestr,
1186: $homeserver));
1.945 raeburn 1187: } elsif ($item eq 'selfcreate') {
1188: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1189: &escape($udom).':'.&escape($uname).
1190: ':'.$rulestr,$homeserver));
1.923 raeburn 1191: }
1.912 raeburn 1192: if ($response ne 'refused') {
1193: my @pairs=split(/\&/,$response);
1194: foreach my $item (@pairs) {
1195: my ($key,$value)=split(/=/,$item,2);
1196: $key = &unescape($key);
1197: next if ($key =~ /^error: 2 /);
1198: $returnhash{$key}=&thaw_unescape($value);
1199: }
1200: }
1201: }
1202: }
1203: }
1204: return %returnhash;
1205: }
1206:
1207: sub inst_userrules {
1.923 raeburn 1208: my ($udom,$check) = @_;
1.912 raeburn 1209: my (%ruleshash,@ruleorder);
1210: if ($udom ne '') {
1211: my $homeserver=&domain($udom,'primary');
1212: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1213: my $response;
1214: if ($check eq 'id') {
1215: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1216: $homeserver);
1.943 raeburn 1217: } elsif ($check eq 'email') {
1218: $response=&reply('instemailrules:'.&escape($udom),
1219: $homeserver);
1.923 raeburn 1220: } else {
1221: $response=&reply('instuserrules:'.&escape($udom),
1222: $homeserver);
1223: }
1.912 raeburn 1224: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1225: ($response ne 'unknown_cmd') &&
1.912 raeburn 1226: ($response ne 'no_such_host')) {
1227: my ($hashitems,$orderitems) = split(/:/,$response);
1228: my @pairs=split(/\&/,$hashitems);
1229: foreach my $item (@pairs) {
1230: my ($key,$value)=split(/=/,$item,2);
1231: $key = &unescape($key);
1232: next if ($key =~ /^error: 2 /);
1233: $ruleshash{$key}=&thaw_unescape($value);
1234: }
1235: my @esc_order = split(/\&/,$orderitems);
1236: foreach my $item (@esc_order) {
1237: push(@ruleorder,&unescape($item));
1238: }
1239: }
1240: }
1241: }
1242: return (\%ruleshash,\@ruleorder);
1243: }
1244:
1.976 raeburn 1245: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1246:
1247: sub get_domain_defaults {
1248: my ($domain) = @_;
1249: my $cachetime = 60*60*24;
1250: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1251: if (defined($cached)) {
1252: if (ref($result) eq 'HASH') {
1253: return %{$result};
1254: }
1255: }
1256: my %domdefaults;
1257: my %domconfig =
1.976 raeburn 1258: &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943 raeburn 1259: if (ref($domconfig{'defaults'}) eq 'HASH') {
1260: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1261: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1262: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1263: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1264: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1265: } else {
1266: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1267: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1268: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1269: }
1.976 raeburn 1270: if (ref($domconfig{'quotas'}) eq 'HASH') {
1271: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1272: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1273: } else {
1274: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1275: }
1276: my @usertools = ('aboutme','blog','portfolio');
1277: foreach my $item (@usertools) {
1278: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1279: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1280: }
1281: }
1282: }
1.985 raeburn 1283: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1284: foreach my $item ('official','unofficial') {
1285: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1286: }
1287: }
1.943 raeburn 1288: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1289: $cachetime);
1290: return %domdefaults;
1291: }
1292:
1.344 www 1293: # --------------------------------------------------- Assign a key to a student
1294:
1295: sub assign_access_key {
1.364 www 1296: #
1297: # a valid key looks like uname:udom#comments
1298: # comments are being appended
1299: #
1.498 www 1300: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1301: $kdom=
1.620 albertel 1302: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1303: $knum=
1.620 albertel 1304: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1305: $cdom=
1.620 albertel 1306: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1307: $cnum=
1.620 albertel 1308: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1309: $udom=$env{'user.name'} unless (defined($udom));
1310: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1311: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1312: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1313: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1314: # assigned to this person
1315: # - this should not happen,
1.345 www 1316: # unless something went wrong
1317: # the first time around
1318: # ready to assign
1.364 www 1319: $logentry=$1.'; '.$logentry;
1.496 www 1320: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1321: $kdom,$knum) eq 'ok') {
1.345 www 1322: # key now belongs to user
1.346 www 1323: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1324: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1325: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1326: return 'ok';
1327: } else {
1328: return
1329: 'error: Count not permanently assign key, will need to be re-entered later.';
1330: }
1331: } else {
1332: return 'error: Could not assign key, try again later.';
1333: }
1.364 www 1334: } elsif (!$existing{$ckey}) {
1.345 www 1335: # the key does not exist
1336: return 'error: The key does not exist';
1337: } else {
1338: # the key is somebody else's
1339: return 'error: The key is already in use';
1340: }
1.344 www 1341: }
1342:
1.364 www 1343: # ------------------------------------------ put an additional comment on a key
1344:
1345: sub comment_access_key {
1346: #
1347: # a valid key looks like uname:udom#comments
1348: # comments are being appended
1349: #
1350: my ($ckey,$cdom,$cnum,$logentry)=@_;
1351: $cdom=
1.620 albertel 1352: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1353: $cnum=
1.620 albertel 1354: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1355: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1356: if ($existing{$ckey}) {
1357: $existing{$ckey}.='; '.$logentry;
1358: # ready to assign
1.367 www 1359: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1360: $cdom,$cnum) eq 'ok') {
1361: return 'ok';
1362: } else {
1363: return 'error: Count not store comment.';
1364: }
1365: } else {
1366: # the key does not exist
1367: return 'error: The key does not exist';
1368: }
1369: }
1370:
1.344 www 1371: # ------------------------------------------------------ Generate a set of keys
1372:
1373: sub generate_access_keys {
1.364 www 1374: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1375: $cdom=
1.620 albertel 1376: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1377: $cnum=
1.620 albertel 1378: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1379: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1380: unless (($cdom) && ($cnum)) { return 0; }
1381: if ($number>10000) { return 0; }
1382: sleep(2); # make sure don't get same seed twice
1383: srand(time()^($$+($$<<15))); # from "Programming Perl"
1384: my $total=0;
1385: for (my $i=1;$i<=$number;$i++) {
1386: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1387: sprintf("%lx",int(100000*rand)).'-'.
1388: sprintf("%lx",int(100000*rand));
1389: $newkey=~s/1/g/g; # folks mix up 1 and l
1390: $newkey=~s/0/h/g; # and also 0 and O
1391: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1392: if ($existing{$newkey}) {
1393: $i--;
1394: } else {
1.364 www 1395: if (&put('accesskeys',
1396: { $newkey => '# generated '.localtime().
1.620 albertel 1397: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1398: '; '.$logentry },
1399: $cdom,$cnum) eq 'ok') {
1.344 www 1400: $total++;
1401: }
1402: }
1403: }
1.620 albertel 1404: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1405: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1406: return $total;
1407: }
1408:
1409: # ------------------------------------------------------- Validate an accesskey
1410:
1411: sub validate_access_key {
1412: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1413: $cdom=
1.620 albertel 1414: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1415: $cnum=
1.620 albertel 1416: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1417: $udom=$env{'user.domain'} unless (defined($udom));
1418: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1419: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1420: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1421: }
1422:
1423: # ------------------------------------- Find the section of student in a course
1.652 albertel 1424: sub devalidate_getsection_cache {
1425: my ($udom,$unam,$courseid)=@_;
1426: my $hashid="$udom:$unam:$courseid";
1427: &devalidate_cache_new('getsection',$hashid);
1428: }
1.298 matthew 1429:
1.815 albertel 1430: sub courseid_to_courseurl {
1431: my ($courseid) = @_;
1432: #already url style courseid
1433: return $courseid if ($courseid =~ m{^/});
1434:
1435: if (exists($env{'course.'.$courseid.'.num'})) {
1436: my $cnum = $env{'course.'.$courseid.'.num'};
1437: my $cdom = $env{'course.'.$courseid.'.domain'};
1438: return "/$cdom/$cnum";
1439: }
1440:
1441: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1442: if (exists($courseinfo{'num'})) {
1443: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1444: }
1445:
1446: return undef;
1447: }
1448:
1.298 matthew 1449: sub getsection {
1450: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1451: my $cachetime=1800;
1.551 albertel 1452:
1453: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1454: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1455: if (defined($cached)) { return $result; }
1456:
1.298 matthew 1457: my %Pending;
1458: my %Expired;
1459: #
1460: # Each role can either have not started yet (pending), be active,
1461: # or have expired.
1462: #
1463: # If there is an active role, we are done.
1464: #
1465: # If there is more than one role which has not started yet,
1466: # choose the one which will start sooner
1467: # If there is one role which has not started yet, return it.
1468: #
1469: # If there is more than one expired role, choose the one which ended last.
1470: # If there is a role which has expired, return it.
1471: #
1.815 albertel 1472: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1473: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1474: foreach my $key (keys(%roleshash)) {
1.479 albertel 1475: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1476: my $section=$1;
1477: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1478: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1479: my $now=time;
1.548 albertel 1480: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1481: $Expired{$end}=$section;
1482: next;
1483: }
1.548 albertel 1484: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1485: $Pending{$start}=$section;
1486: next;
1487: }
1.599 albertel 1488: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1489: }
1490: #
1491: # Presumedly there will be few matching roles from the above
1492: # loop and the sorting time will be negligible.
1493: if (scalar(keys(%Pending))) {
1494: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1495: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1496: }
1497: if (scalar(keys(%Expired))) {
1498: my @sorted = sort {$a <=> $b} keys(%Expired);
1499: my $time = pop(@sorted);
1.599 albertel 1500: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1501: }
1.599 albertel 1502: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1503: }
1.70 www 1504:
1.599 albertel 1505: sub save_cache {
1506: &purge_remembered();
1.722 albertel 1507: #&Apache::loncommon::validate_page();
1.620 albertel 1508: undef(%env);
1.780 albertel 1509: undef($env_loaded);
1.599 albertel 1510: }
1.452 albertel 1511:
1.599 albertel 1512: my $to_remember=-1;
1513: my %remembered;
1514: my %accessed;
1515: my $kicks=0;
1516: my $hits=0;
1.849 albertel 1517: sub make_key {
1518: my ($name,$id) = @_;
1.872 albertel 1519: if (length($id) > 65
1520: && length(&escape($id)) > 200) {
1521: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1522: }
1.849 albertel 1523: return &escape($name.':'.$id);
1524: }
1525:
1.599 albertel 1526: sub devalidate_cache_new {
1527: my ($name,$id,$debug) = @_;
1528: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1529: $id=&make_key($name,$id);
1.599 albertel 1530: $memcache->delete($id);
1531: delete($remembered{$id});
1532: delete($accessed{$id});
1533: }
1534:
1535: sub is_cached_new {
1536: my ($name,$id,$debug) = @_;
1.849 albertel 1537: $id=&make_key($name,$id);
1.599 albertel 1538: if (exists($remembered{$id})) {
1539: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1540: $accessed{$id}=[&gettimeofday()];
1541: $hits++;
1542: return ($remembered{$id},1);
1543: }
1544: my $value = $memcache->get($id);
1545: if (!(defined($value))) {
1546: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1547: return (undef,undef);
1.416 albertel 1548: }
1.599 albertel 1549: if ($value eq '__undef__') {
1550: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1551: $value=undef;
1552: }
1553: &make_room($id,$value,$debug);
1554: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1555: return ($value,1);
1556: }
1557:
1558: sub do_cache_new {
1559: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1560: $id=&make_key($name,$id);
1.599 albertel 1561: my $setvalue=$value;
1562: if (!defined($setvalue)) {
1563: $setvalue='__undef__';
1564: }
1.623 albertel 1565: if (!defined($time) ) {
1566: $time=600;
1567: }
1.599 albertel 1568: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1569: my $result = $memcache->set($id,$setvalue,$time);
1570: if (! $result) {
1.872 albertel 1571: &logthis("caching of id -> $id failed");
1.910 albertel 1572: $memcache->disconnect_all();
1.872 albertel 1573: }
1.600 albertel 1574: # need to make a copy of $value
1.919 albertel 1575: &make_room($id,$value,$debug);
1.599 albertel 1576: return $value;
1577: }
1578:
1579: sub make_room {
1580: my ($id,$value,$debug)=@_;
1.919 albertel 1581:
1582: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1583: : $value;
1.599 albertel 1584: if ($to_remember<0) { return; }
1585: $accessed{$id}=[&gettimeofday()];
1586: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1587: my $to_kick;
1588: my $max_time=0;
1589: foreach my $other (keys(%accessed)) {
1590: if (&tv_interval($accessed{$other}) > $max_time) {
1591: $to_kick=$other;
1592: $max_time=&tv_interval($accessed{$other});
1593: }
1594: }
1595: delete($remembered{$to_kick});
1596: delete($accessed{$to_kick});
1597: $kicks++;
1598: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1599: return;
1600: }
1601:
1.599 albertel 1602: sub purge_remembered {
1.604 albertel 1603: #&logthis("Tossing ".scalar(keys(%remembered)));
1604: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1605: undef(%remembered);
1606: undef(%accessed);
1.428 albertel 1607: }
1.70 www 1608: # ------------------------------------- Read an entry from a user's environment
1609:
1610: sub userenvironment {
1611: my ($udom,$unam,@what)=@_;
1.976 raeburn 1612: my $items;
1613: foreach my $item (@what) {
1614: $items.=&escape($item).'&';
1615: }
1616: $items=~s/\&$//;
1.70 www 1617: my %returnhash=();
1618: my @answer=split(/\&/,
1.976 raeburn 1619: &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70 www 1620: &homeserver($unam,$udom)));
1621: my $i;
1622: for ($i=0;$i<=$#what;$i++) {
1623: $returnhash{$what[$i]}=&unescape($answer[$i]);
1624: }
1625: return %returnhash;
1.1 albertel 1626: }
1627:
1.617 albertel 1628: # ---------------------------------------------------------- Get a studentphoto
1629: sub studentphoto {
1630: my ($udom,$unam,$ext) = @_;
1631: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1632: if (defined($env{'request.course.id'})) {
1.708 raeburn 1633: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1634: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1635: return(&retrievestudentphoto($udom,$unam,$ext));
1636: } else {
1637: my ($result,$perm_reqd)=
1.707 albertel 1638: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1639: if ($result eq 'ok') {
1640: if (!($perm_reqd eq 'yes')) {
1641: return(&retrievestudentphoto($udom,$unam,$ext));
1642: }
1643: }
1644: }
1645: }
1646: } else {
1647: my ($result,$perm_reqd) =
1.707 albertel 1648: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1649: if ($result eq 'ok') {
1650: if (!($perm_reqd eq 'yes')) {
1651: return(&retrievestudentphoto($udom,$unam,$ext));
1652: }
1653: }
1654: }
1655: return '/adm/lonKaputt/lonlogo_broken.gif';
1656: }
1657:
1658: sub retrievestudentphoto {
1659: my ($udom,$unam,$ext,$type) = @_;
1660: my $home=&Apache::lonnet::homeserver($unam,$udom);
1661: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1662: if ($ret eq 'ok') {
1663: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1664: if ($type eq 'thumbnail') {
1665: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1666: }
1667: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1668: return $tokenurl;
1669: } else {
1670: if ($type eq 'thumbnail') {
1671: return '/adm/lonKaputt/genericstudent_tn.gif';
1672: } else {
1673: return '/adm/lonKaputt/lonlogo_broken.gif';
1674: }
1.617 albertel 1675: }
1676: }
1677:
1.263 www 1678: # -------------------------------------------------------------------- New chat
1679:
1680: sub chatsend {
1.724 raeburn 1681: my ($newentry,$anon,$group)=@_;
1.620 albertel 1682: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1683: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1684: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1685: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1686: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1687: &escape($newentry)).':'.$group,$chome);
1.292 www 1688: }
1689:
1690: # ------------------------------------------ Find current version of a resource
1691:
1692: sub getversion {
1693: my $fname=&clutter(shift);
1694: unless ($fname=~/^\/res\//) { return -1; }
1695: return ¤tversion(&filelocation('',$fname));
1696: }
1697:
1698: sub currentversion {
1699: my $fname=shift;
1.599 albertel 1700: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1701: if (defined($cached)) { return $result; }
1.292 www 1702: my $author=$fname;
1703: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1704: my ($udom,$uname)=split(/\//,$author);
1705: my $home=homeserver($uname,$udom);
1706: if ($home eq 'no_host') {
1707: return -1;
1708: }
1709: my $answer=reply("currentversion:$fname",$home);
1710: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1711: return -1;
1712: }
1.599 albertel 1713: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1714: }
1715:
1.1 albertel 1716: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1717:
1.1 albertel 1718: sub subscribe {
1719: my $fname=shift;
1.761 raeburn 1720: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1721: $fname=~s/[\n\r]//g;
1.1 albertel 1722: my $author=$fname;
1723: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1724: my ($udom,$uname)=split(/\//,$author);
1725: my $home=homeserver($uname,$udom);
1.335 albertel 1726: if ($home eq 'no_host') {
1727: return 'not_found';
1.1 albertel 1728: }
1729: my $answer=reply("sub:$fname",$home);
1.64 www 1730: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1731: $answer.=' by '.$home;
1732: }
1.1 albertel 1733: return $answer;
1734: }
1735:
1.8 www 1736: # -------------------------------------------------------------- Replicate file
1737:
1738: sub repcopy {
1739: my $filename=shift;
1.23 www 1740: $filename=~s/\/+/\//g;
1.607 raeburn 1741: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1742: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1743: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1744: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1745: return &repcopy_userfile($filename);
1746: }
1.532 albertel 1747: $filename=~s/[\n\r]//g;
1.8 www 1748: my $transname="$filename.in.transfer";
1.828 www 1749: # FIXME: this should flock
1.607 raeburn 1750: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1751: my $remoteurl=subscribe($filename);
1.64 www 1752: if ($remoteurl =~ /^con_lost by/) {
1753: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1754: return 'unavailable';
1.8 www 1755: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1756: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1757: return 'not_found';
1.64 www 1758: } elsif ($remoteurl =~ /^rejected by/) {
1759: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1760: return 'forbidden';
1.20 www 1761: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1762: return 'ok';
1.8 www 1763: } else {
1.290 www 1764: my $author=$filename;
1765: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1766: my ($udom,$uname)=split(/\//,$author);
1767: my $home=homeserver($uname,$udom);
1768: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1769: my @parts=split(/\//,$filename);
1770: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1771: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1772: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1773: return 'bad_request';
1.8 www 1774: }
1775: my $count;
1776: for ($count=5;$count<$#parts;$count++) {
1777: $path.="/$parts[$count]";
1778: if ((-e $path)!=1) {
1779: mkdir($path,0777);
1780: }
1781: }
1782: my $ua=new LWP::UserAgent;
1783: my $request=new HTTP::Request('GET',"$remoteurl");
1784: my $response=$ua->request($request,$transname);
1785: if ($response->is_error()) {
1786: unlink($transname);
1787: my $message=$response->status_line;
1.672 albertel 1788: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1789: ." LWP get: $message: $filename</font>");
1.607 raeburn 1790: return 'unavailable';
1.8 www 1791: } else {
1.16 www 1792: if ($remoteurl!~/\.meta$/) {
1793: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1794: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1795: if ($mresponse->is_error()) {
1796: unlink($filename.'.meta');
1797: &logthis(
1.672 albertel 1798: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1799: }
1800: }
1.8 www 1801: rename($transname,$filename);
1.607 raeburn 1802: return 'ok';
1.8 www 1803: }
1.290 www 1804: }
1.8 www 1805: }
1.330 www 1806: }
1807:
1808: # ------------------------------------------------ Get server side include body
1809: sub ssi_body {
1.381 albertel 1810: my ($filelink,%form)=@_;
1.606 matthew 1811: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1812: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1813: }
1.953 www 1814: my $output='';
1815: my $response;
1.980 raeburn 1816: if ($filelink=~/^https?\:/) {
1.954 raeburn 1817: ($output,$response)=&externalssi($filelink);
1.953 www 1818: } else {
1819: ($output,$response)=&ssi($filelink,%form);
1820: }
1.778 albertel 1821: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1822: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1823: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1824: if (wantarray) {
1825: return ($output, $response);
1826: } else {
1827: return $output;
1828: }
1.8 www 1829: }
1830:
1.15 www 1831: # --------------------------------------------------------- Server Side Include
1832:
1.782 albertel 1833: sub absolute_url {
1834: my ($host_name) = @_;
1835: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1836: if ($host_name eq '') {
1837: $host_name = $ENV{'SERVER_NAME'};
1838: }
1839: return $protocol.$host_name;
1840: }
1841:
1.942 foxr 1842: #
1843: # Server side include.
1844: # Parameters:
1845: # fn Possibly encrypted resource name/id.
1846: # form Hash that describes how the rendering should be done
1847: # and other things.
1.944 foxr 1848: # Returns:
1.950 raeburn 1849: # Scalar context: The content of the response.
1850: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1851: #
1.15 www 1852: sub ssi {
1853:
1.944 foxr 1854: my ($fn,%form)=@_;
1.15 www 1855: my $ua=new LWP::UserAgent;
1.23 www 1856: my $request;
1.711 albertel 1857:
1858: $form{'no_update_last_known'}=1;
1.895 albertel 1859: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1860: if (%form) {
1.782 albertel 1861: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1862: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1863: } else {
1.782 albertel 1864: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1865: }
1866:
1.15 www 1867: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1868: my $response=$ua->request($request);
1869:
1.944 foxr 1870: if (wantarray) {
1871: return ($response->content, $response);
1872: } else {
1873: return $response->content;
1.942 foxr 1874: }
1.324 www 1875: }
1876:
1877: sub externalssi {
1878: my ($url)=@_;
1879: my $ua=new LWP::UserAgent;
1880: my $request=new HTTP::Request('GET',$url);
1881: my $response=$ua->request($request);
1.954 raeburn 1882: if (wantarray) {
1883: return ($response->content, $response);
1884: } else {
1885: return $response->content;
1886: }
1.15 www 1887: }
1.254 www 1888:
1.492 albertel 1889: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1890:
1891: sub allowuploaded {
1892: my ($srcurl,$url)=@_;
1893: $url=&clutter(&declutter($url));
1894: my $dir=$url;
1895: $dir=~s/\/[^\/]+$//;
1896: my %httpref=();
1897: my $httpurl=&hreflocation('',$url);
1898: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1899: &Apache::lonnet::appenv(\%httpref);
1.254 www 1900: }
1.477 raeburn 1901:
1.478 albertel 1902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1903: # input: action, courseID, current domain, intended
1.637 raeburn 1904: # path to file, source of file, instruction to parse file for objects,
1905: # ref to hash for embedded objects,
1906: # ref to hash for codebase of java objects.
1907: #
1.485 raeburn 1908: # output: url to file (if action was uploaddoc),
1909: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1910: #
1.478 albertel 1911: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1912: # course.
1.477 raeburn 1913: #
1.478 albertel 1914: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1915: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1916: # course's home server.
1.477 raeburn 1917: #
1.478 albertel 1918: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1919: # be copied from $source (current location) to
1920: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1921: # and will then be copied to
1922: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1923: # course's home server.
1.485 raeburn 1924: #
1.481 raeburn 1925: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1926: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1927: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1928: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1929: # in course's home server.
1.637 raeburn 1930: #
1.477 raeburn 1931:
1932: sub process_coursefile {
1.638 albertel 1933: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1934: my $fetchresult;
1.638 albertel 1935: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1936: if ($action eq 'propagate') {
1.638 albertel 1937: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1938: $home);
1.481 raeburn 1939: } else {
1.477 raeburn 1940: my $fpath = '';
1941: my $fname = $file;
1.478 albertel 1942: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1943: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1944: my $filepath = &build_filepath($fpath);
1.481 raeburn 1945: if ($action eq 'copy') {
1946: if ($source eq '') {
1947: $fetchresult = 'no source file';
1948: return $fetchresult;
1949: } else {
1950: my $destination = $filepath.'/'.$fname;
1951: rename($source,$destination);
1952: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1953: $home);
1.481 raeburn 1954: }
1955: } elsif ($action eq 'uploaddoc') {
1956: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1957: print $fh $env{'form.'.$source};
1.481 raeburn 1958: close($fh);
1.637 raeburn 1959: if ($parser eq 'parse') {
1.961 raeburn 1960: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 1961: unless ($parse_result eq 'ok') {
1962: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1963: }
1964: }
1.477 raeburn 1965: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1966: $home);
1.481 raeburn 1967: if ($fetchresult eq 'ok') {
1968: return '/uploaded/'.$fpath.'/'.$fname;
1969: } else {
1970: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1971: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1972: return '/adm/notfound.html';
1973: }
1.477 raeburn 1974: }
1975: }
1.485 raeburn 1976: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1977: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1978: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1979: }
1980: return $fetchresult;
1981: }
1982:
1.637 raeburn 1983: sub build_filepath {
1984: my ($fpath) = @_;
1985: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1986: unless ($fpath eq '') {
1987: my @parts=split('/',$fpath);
1988: foreach my $part (@parts) {
1989: $filepath.= '/'.$part;
1990: if ((-e $filepath)!=1) {
1991: mkdir($filepath,0777);
1992: }
1993: }
1994: }
1995: return $filepath;
1996: }
1997:
1998: sub store_edited_file {
1.638 albertel 1999: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2000: my $file = $primary_url;
2001: $file =~ s#^/uploaded/$docudom/$docuname/##;
2002: my $fpath = '';
2003: my $fname = $file;
2004: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2005: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2006: my $filepath = &build_filepath($fpath);
2007: open(my $fh,'>'.$filepath.'/'.$fname);
2008: print $fh $content;
2009: close($fh);
1.638 albertel 2010: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2011: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2012: $home);
1.637 raeburn 2013: if ($$fetchresult eq 'ok') {
2014: return '/uploaded/'.$fpath.'/'.$fname;
2015: } else {
1.638 albertel 2016: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2017: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2018: return '/adm/notfound.html';
2019: }
2020: }
2021:
1.531 albertel 2022: sub clean_filename {
1.831 albertel 2023: my ($fname,$args)=@_;
1.315 www 2024: # Replace Windows backslashes by forward slashes
1.257 www 2025: $fname=~s/\\/\//g;
1.831 albertel 2026: if (!$args->{'keep_path'}) {
2027: # Get rid of everything but the actual filename
2028: $fname=~s/^.*\/([^\/]+)$/$1/;
2029: }
1.315 www 2030: # Replace spaces by underscores
2031: $fname=~s/\s+/\_/g;
2032: # Replace all other weird characters by nothing
1.831 albertel 2033: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2034: # Replace all .\d. sequences with _\d. so they no longer look like version
2035: # numbers
2036: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2037: return $fname;
2038: }
1.984 neumanie 2039: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2040: sub resizeImage {
2041: my($img_url) = @_;
2042: my $ima = Image::Magick->new;
2043: $ima->Read($img_url);
2044: if($ima->Get('width') > 400)
2045: {
2046: my $factor = $ima->Get('width')/400;
2047: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2048: }
2049: if($ima->Get('height') > 500)
2050: {
2051: my $factor = $ima->Get('height')/500;
2052: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2053: }
2054:
2055: $ima->Write($img_url);
2056: }
1.531 albertel 2057:
1.977 amueller 2058: #Wrapper function for userphotoupload
2059: sub userphotoupload
2060: {
2061: my($formname,$subdir) = @_;
2062: $upload_photo_form = 1;
2063: return &userfileupload($formname,undef,$subdir);
2064: }
2065:
1.608 albertel 2066: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2067: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2068: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2069: # $coursedoc - if true up to the current course
2070: # if false
2071: # $subdir - directory in userfile to store the file into
1.858 raeburn 2072: # $parser - instruction to parse file for objects ($parser = parse)
2073: # $allfiles - reference to hash for embedded objects
2074: # $codebase - reference to hash for codebase of java objects
2075: # $desuname - username for permanent storage of uploaded file
2076: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2077: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2078: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2079: #
1.686 albertel 2080: # output: url of file in userspace, or error: <message>
2081: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2082:
2083:
1.531 albertel 2084: sub userfileupload {
1.860 raeburn 2085: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2086: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2087: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2088: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2089: $fname=&clean_filename($fname);
1.315 www 2090: # See if there is anything left
1.257 www 2091: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2092: chop($env{'form.'.$formname});
1.523 raeburn 2093: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2094: my $now = time;
2095: my $filepath = 'tmp/helprequests/'.$now;
2096: my @parts=split(/\//,$filepath);
2097: my $fullpath = $perlvar{'lonDaemons'};
2098: for (my $i=0;$i<@parts;$i++) {
2099: $fullpath .= '/'.$parts[$i];
2100: if ((-e $fullpath)!=1) {
2101: mkdir($fullpath,0777);
2102: }
2103: }
2104: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2105: print $fh $env{'form.'.$formname};
1.523 raeburn 2106: close($fh);
1.741 raeburn 2107: return $fullpath.'/'.$fname;
2108: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2109: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2110: '_'.$env{'user.domain'}.'/pending';
2111: my @parts=split(/\//,$filepath);
2112: my $fullpath = $perlvar{'lonDaemons'};
2113: for (my $i=0;$i<@parts;$i++) {
2114: $fullpath .= '/'.$parts[$i];
2115: if ((-e $fullpath)!=1) {
2116: mkdir($fullpath,0777);
2117: }
2118: }
2119: open(my $fh,'>'.$fullpath.'/'.$fname);
2120: print $fh $env{'form.'.$formname};
2121: close($fh);
2122: return $fullpath.'/'.$fname;
1.523 raeburn 2123: }
1.719 banghart 2124:
1.258 www 2125: # Create the directory if not present
1.493 albertel 2126: $fname="$subdir/$fname";
1.259 www 2127: if ($coursedoc) {
1.638 albertel 2128: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2129: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2130: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2131: return &finishuserfileupload($docuname,$docudom,
2132: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2133: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2134: } else {
1.620 albertel 2135: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2136: return &process_coursefile('uploaddoc',$docuname,$docudom,
2137: $fname,$formname,$parser,
2138: $allfiles,$codebase);
1.481 raeburn 2139: }
1.719 banghart 2140: } elsif (defined($destuname)) {
2141: my $docuname=$destuname;
2142: my $docudom=$destudom;
1.860 raeburn 2143: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2144: $parser,$allfiles,$codebase,
2145: $thumbwidth,$thumbheight);
1.719 banghart 2146:
1.259 www 2147: } else {
1.638 albertel 2148: my $docuname=$env{'user.name'};
2149: my $docudom=$env{'user.domain'};
1.714 raeburn 2150: if (exists($env{'form.group'})) {
2151: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2152: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2153: }
1.860 raeburn 2154: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2155: $parser,$allfiles,$codebase,
2156: $thumbwidth,$thumbheight);
1.259 www 2157: }
1.271 www 2158: }
2159:
2160: sub finishuserfileupload {
1.860 raeburn 2161: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2162: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2163: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2164: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2165:
1.860 raeburn 2166: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2167: $file=$fname;
2168: if ($fname=~m|/|) {
2169: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2170: $path.=$fnamepath.'/';
2171: }
1.259 www 2172: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2173: my $count;
2174: for ($count=4;$count<=$#parts;$count++) {
2175: $filepath.="/$parts[$count]";
2176: if ((-e $filepath)!=1) {
2177: mkdir($filepath,0777);
2178: }
2179: }
1.984 neumanie 2180:
1.258 www 2181: # Save the file
2182: {
1.701 albertel 2183: if (!open(FH,'>'.$filepath.'/'.$file)) {
2184: &logthis('Failed to create '.$filepath.'/'.$file);
2185: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2186: return '/adm/notfound.html';
2187: }
2188: if (!print FH ($env{'form.'.$formname})) {
2189: &logthis('Failed to write to '.$filepath.'/'.$file);
2190: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2191: return '/adm/notfound.html';
2192: }
1.570 albertel 2193: close(FH);
1.977 amueller 2194: if($upload_photo_form==1)
2195: {
1.984 neumanie 2196: resizeImage($filepath.'/'.$file);
1.977 amueller 2197: $upload_photo_form = 0;
2198: }
1.258 www 2199: }
1.637 raeburn 2200: if ($parser eq 'parse') {
1.961 raeburn 2201: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2202: $codebase);
1.637 raeburn 2203: unless ($parse_result eq 'ok') {
1.638 albertel 2204: &logthis('Failed to parse '.$filepath.$file.
2205: ' for embedded media: '.$parse_result);
1.637 raeburn 2206: }
2207: }
1.860 raeburn 2208: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2209: my $input = $filepath.'/'.$file;
2210: my $output = $filepath.'/'.'tn-'.$file;
2211: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2212: system("convert -sample $thumbsize $input $output");
2213: if (-e $filepath.'/'.'tn-'.$file) {
2214: $fetchthumb = 1;
2215: }
2216: }
1.858 raeburn 2217:
1.259 www 2218: # Notify homeserver to grep it
2219: #
1.984 neumanie 2220: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2221: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2222: if ($fetchresult eq 'ok') {
1.860 raeburn 2223: if ($fetchthumb) {
2224: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2225: if ($thumbresult ne 'ok') {
2226: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2227: $docuhome.': '.$thumbresult);
2228: }
2229: }
1.259 www 2230: #
1.258 www 2231: # Return the URL to it
1.494 albertel 2232: return '/uploaded/'.$path.$file;
1.263 www 2233: } else {
1.494 albertel 2234: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2235: ': '.$fetchresult);
1.263 www 2236: return '/adm/notfound.html';
1.858 raeburn 2237: }
1.493 albertel 2238: }
2239:
1.637 raeburn 2240: sub extract_embedded_items {
1.961 raeburn 2241: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2242: my @state = ();
2243: my %javafiles = (
2244: codebase => '',
2245: code => '',
2246: archive => ''
2247: );
2248: my %mediafiles = (
2249: src => '',
2250: movie => '',
2251: );
1.648 raeburn 2252: my $p;
2253: if ($content) {
2254: $p = HTML::LCParser->new($content);
2255: } else {
1.961 raeburn 2256: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2257: }
1.641 albertel 2258: while (my $t=$p->get_token()) {
1.640 albertel 2259: if ($t->[0] eq 'S') {
2260: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2261: push(@state, $tagname);
1.648 raeburn 2262: if (lc($tagname) eq 'allow') {
2263: &add_filetype($allfiles,$attr->{'src'},'src');
2264: }
1.640 albertel 2265: if (lc($tagname) eq 'img') {
2266: &add_filetype($allfiles,$attr->{'src'},'src');
2267: }
1.886 albertel 2268: if (lc($tagname) eq 'a') {
2269: &add_filetype($allfiles,$attr->{'href'},'href');
2270: }
1.645 raeburn 2271: if (lc($tagname) eq 'script') {
2272: if ($attr->{'archive'} =~ /\.jar$/i) {
2273: &add_filetype($allfiles,$attr->{'archive'},'archive');
2274: } else {
2275: &add_filetype($allfiles,$attr->{'src'},'src');
2276: }
2277: }
2278: if (lc($tagname) eq 'link') {
2279: if (lc($attr->{'rel'}) eq 'stylesheet') {
2280: &add_filetype($allfiles,$attr->{'href'},'href');
2281: }
2282: }
1.640 albertel 2283: if (lc($tagname) eq 'object' ||
2284: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2285: foreach my $item (keys(%javafiles)) {
2286: $javafiles{$item} = '';
2287: }
2288: }
2289: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2290: my $name = lc($attr->{'name'});
2291: foreach my $item (keys(%javafiles)) {
2292: if ($name eq $item) {
2293: $javafiles{$item} = $attr->{'value'};
2294: last;
2295: }
2296: }
2297: foreach my $item (keys(%mediafiles)) {
2298: if ($name eq $item) {
2299: &add_filetype($allfiles, $attr->{'value'}, 'value');
2300: last;
2301: }
2302: }
2303: }
2304: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2305: foreach my $item (keys(%javafiles)) {
2306: if ($attr->{$item}) {
2307: $javafiles{$item} = $attr->{$item};
2308: last;
2309: }
2310: }
2311: foreach my $item (keys(%mediafiles)) {
2312: if ($attr->{$item}) {
2313: &add_filetype($allfiles,$attr->{$item},$item);
2314: last;
2315: }
2316: }
2317: }
2318: } elsif ($t->[0] eq 'E') {
2319: my ($tagname) = ($t->[1]);
2320: if ($javafiles{'codebase'} ne '') {
2321: $javafiles{'codebase'} .= '/';
2322: }
2323: if (lc($tagname) eq 'applet' ||
2324: lc($tagname) eq 'object' ||
2325: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2326: ) {
2327: foreach my $item (keys(%javafiles)) {
2328: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2329: my $file=$javafiles{'codebase'}.$javafiles{$item};
2330: &add_filetype($allfiles,$file,$item);
2331: }
2332: }
2333: }
2334: pop @state;
2335: }
2336: }
1.637 raeburn 2337: return 'ok';
2338: }
2339:
1.639 albertel 2340: sub add_filetype {
2341: my ($allfiles,$file,$type)=@_;
2342: if (exists($allfiles->{$file})) {
2343: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2344: push(@{$allfiles->{$file}}, &escape($type));
2345: }
2346: } else {
2347: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2348: }
2349: }
2350:
1.493 albertel 2351: sub removeuploadedurl {
1.984 neumanie 2352: my ($url)=@_;
2353: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2354: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2355: }
2356:
2357: sub removeuserfile {
2358: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2359: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2360: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2361: if ($result eq 'ok') {
1.798 raeburn 2362: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2363: my $metafile = $fname.'.meta';
2364: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2365: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2366: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2367: my $sqlresult =
1.823 albertel 2368: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2369: 'portfolio_metadata',$group,
2370: 'delete');
1.798 raeburn 2371: }
2372: }
2373: return $result;
1.257 www 2374: }
1.15 www 2375:
1.530 albertel 2376: sub mkdiruserfile {
2377: my ($docuname,$docudom,$dir)=@_;
2378: my $home=&homeserver($docuname,$docudom);
2379: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2380: }
2381:
1.531 albertel 2382: sub renameuserfile {
2383: my ($docuname,$docudom,$old,$new)=@_;
2384: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2385: my $result = &reply("renameuserfile:$docudom:$docuname:".
2386: &escape("$old").':'.&escape("$new"),$home);
2387: if ($result eq 'ok') {
2388: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2389: my $oldmeta = $old.'.meta';
2390: my $newmeta = $new.'.meta';
2391: my $metaresult =
2392: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2393: my $url = "/uploaded/$docudom/$docuname/$old";
2394: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2395: my $sqlresult =
1.823 albertel 2396: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2397: 'portfolio_metadata',$group,
2398: 'delete');
1.798 raeburn 2399: }
2400: }
2401: return $result;
1.531 albertel 2402: }
2403:
1.14 www 2404: # ------------------------------------------------------------------------- Log
2405:
2406: sub log {
2407: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2408: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2409: }
2410:
2411: # ------------------------------------------------------------------ Course Log
1.352 www 2412: #
2413: # This routine flushes several buffers of non-mission-critical nature
2414: #
1.157 www 2415:
2416: sub flushcourselogs {
1.352 www 2417: &logthis('Flushing log buffers');
2418: #
2419: # course logs
2420: # This is a log of all transactions in a course, which can be used
2421: # for data mining purposes
2422: #
2423: # It also collects the courseid database, which lists last transaction
2424: # times and course titles for all courseids
2425: #
2426: my %courseidbuffer=();
1.921 raeburn 2427: foreach my $crsid (keys(%courselogs)) {
1.352 www 2428: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2429: &escape($courselogs{$crsid}),
2430: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2431: delete $courselogs{$crsid};
2432: } else {
2433: &logthis('Failed to flush log buffer for '.$crsid);
2434: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2435: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2436: " exceeded maximum size, deleting.</font>");
2437: delete $courselogs{$crsid};
2438: }
1.352 www 2439: }
1.920 raeburn 2440: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2441: 'description' => $coursedescrbuf{$crsid},
2442: 'inst_code' => $courseinstcodebuf{$crsid},
2443: 'type' => $coursetypebuf{$crsid},
2444: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2445: };
1.191 harris41 2446: }
1.352 www 2447: #
2448: # Write course id database (reverse lookup) to homeserver of courses
2449: # Is used in pickcourse
2450: #
1.840 albertel 2451: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2452: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2453: $courseidbuffer{$crs_home},
2454: $crs_home,'timeonly');
1.352 www 2455: }
2456: #
2457: # File accesses
2458: # Writes to the dynamic metadata of resources to get hit counts, etc.
2459: #
1.449 matthew 2460: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2461: if ($entry =~ /___count$/) {
2462: my ($dom,$name);
1.807 albertel 2463: ($dom,$name,undef)=
1.811 albertel 2464: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2465: if (! defined($dom) || $dom eq '' ||
2466: ! defined($name) || $name eq '') {
1.620 albertel 2467: my $cid = $env{'request.course.id'};
2468: $dom = $env{'request.'.$cid.'.domain'};
2469: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2470: }
1.450 matthew 2471: my $value = $accesshash{$entry};
2472: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2473: my %temphash=($url => $value);
1.449 matthew 2474: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2475: if ($result eq 'ok') {
2476: delete $accesshash{$entry};
2477: } elsif ($result eq 'unknown_cmd') {
2478: # Target server has old code running on it.
1.450 matthew 2479: my %temphash=($entry => $value);
1.449 matthew 2480: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2481: delete $accesshash{$entry};
2482: }
2483: }
2484: } else {
1.811 albertel 2485: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2486: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2487: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2488: delete $accesshash{$entry};
2489: }
1.185 www 2490: }
1.191 harris41 2491: }
1.352 www 2492: #
2493: # Roles
2494: # Reverse lookup of user roles for course faculty/staff and co-authorship
2495: #
1.800 albertel 2496: foreach my $entry (keys(%userrolehash)) {
1.351 www 2497: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2498: split(/\:/,$entry);
2499: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2500: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2501: $rudom,$runame) eq 'ok') {
2502: delete $userrolehash{$entry};
2503: }
2504: }
1.662 raeburn 2505: #
2506: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2507: #
2508: my %domrolebuffer = ();
2509: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2510: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2511: if ($domrolebuffer{$rudom}) {
2512: $domrolebuffer{$rudom}.='&'.&escape($entry).
2513: '='.&escape($domainrolehash{$entry});
2514: } else {
2515: $domrolebuffer{$rudom}.=&escape($entry).
2516: '='.&escape($domainrolehash{$entry});
2517: }
2518: delete $domainrolehash{$entry};
2519: }
2520: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2521: my %servers = &get_servers($dom,'library');
2522: foreach my $tryserver (keys(%servers)) {
2523: unless (&reply('domroleput:'.$dom.':'.
2524: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2525: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2526: }
1.662 raeburn 2527: }
2528: }
1.186 www 2529: $dumpcount++;
1.157 www 2530: }
2531:
2532: sub courselog {
2533: my $what=shift;
1.158 www 2534: $what=time.':'.$what;
1.620 albertel 2535: unless ($env{'request.course.id'}) { return ''; }
2536: $coursedombuf{$env{'request.course.id'}}=
2537: $env{'course.'.$env{'request.course.id'}.'.domain'};
2538: $coursenumbuf{$env{'request.course.id'}}=
2539: $env{'course.'.$env{'request.course.id'}.'.num'};
2540: $coursehombuf{$env{'request.course.id'}}=
2541: $env{'course.'.$env{'request.course.id'}.'.home'};
2542: $coursedescrbuf{$env{'request.course.id'}}=
2543: $env{'course.'.$env{'request.course.id'}.'.description'};
2544: $courseinstcodebuf{$env{'request.course.id'}}=
2545: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2546: $courseownerbuf{$env{'request.course.id'}}=
2547: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2548: $coursetypebuf{$env{'request.course.id'}}=
2549: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2550: if (defined $courselogs{$env{'request.course.id'}}) {
2551: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2552: } else {
1.620 albertel 2553: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2554: }
1.620 albertel 2555: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2556: &flushcourselogs();
2557: }
1.158 www 2558: }
2559:
2560: sub courseacclog {
2561: my $fnsymb=shift;
1.620 albertel 2562: unless ($env{'request.course.id'}) { return ''; }
2563: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2564: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2565: $what.=':POST';
1.583 matthew 2566: # FIXME: Probably ought to escape things....
1.800 albertel 2567: foreach my $key (keys(%env)) {
2568: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2569: my $formitem = $1;
2570: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2571: $what.=':'.$formitem.'='.$env{$key};
2572: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2573: $what.=':'.$formitem.'='.$env{$key};
2574: }
1.158 www 2575: }
1.191 harris41 2576: }
1.583 matthew 2577: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2578: # FIXME: We should not be depending on a form parameter that someone
2579: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2580: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2581: $what.= ':POST';
2582: # FIXME: Probably ought to escape things....
2583: foreach my $element ('courseexp','crsfulltext','crsrelated',
2584: 'crsdiscuss') {
1.620 albertel 2585: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2586: }
2587: }
1.158 www 2588: }
2589: &courselog($what);
1.149 www 2590: }
2591:
1.185 www 2592: sub countacc {
2593: my $url=&declutter(shift);
1.458 matthew 2594: return if (! defined($url) || $url eq '');
1.620 albertel 2595: unless ($env{'request.course.id'}) { return ''; }
2596: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2597: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2598: $accesshash{$key}++;
1.185 www 2599: }
1.349 www 2600:
1.361 www 2601: sub linklog {
2602: my ($from,$to)=@_;
2603: $from=&declutter($from);
2604: $to=&declutter($to);
2605: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2606: $accesshash{$to.'___'.$from.'___goto'}=1;
2607: }
2608:
1.349 www 2609: sub userrolelog {
2610: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2611: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2612: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2613: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2614: ($trole=~/^ta/)) {
1.350 www 2615: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2616: $userrolehash
2617: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2618: =$tend.':'.$tstart;
1.662 raeburn 2619: }
1.898 albertel 2620: if (($env{'request.role'} =~ /dc\./) &&
2621: (($trole=~/^au/) || ($trole=~/^in/) ||
2622: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2623: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2624: $userrolehash
2625: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2626: =$tend.':'.$tstart;
2627: }
1.662 raeburn 2628: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2629: ($trole=~/^li/) || ($trole=~/^li/) ||
2630: ($trole=~/^au/) || ($trole=~/^dg/) ||
2631: ($trole=~/^sc/)) {
2632: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2633: $domainrolehash
2634: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2635: = $tend.':'.$tstart;
2636: }
1.351 www 2637: }
2638:
1.957 raeburn 2639: sub courserolelog {
2640: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2641: if (($trole eq 'cc') || ($trole eq 'in') ||
2642: ($trole eq 'ep') || ($trole eq 'ad') ||
2643: ($trole eq 'ta') || ($trole eq 'st') ||
2644: ($trole=~/^cr/) || ($trole eq 'gr')) {
2645: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2646: my $cdom = $1;
2647: my $cnum = $2;
2648: my $sec = $3;
2649: my $namespace = 'rolelog';
2650: my %storehash = (
2651: role => $trole,
2652: start => $tstart,
2653: end => $tend,
2654: selfenroll => $selfenroll,
2655: context => $context,
2656: );
2657: if ($trole eq 'gr') {
2658: $namespace = 'groupslog';
2659: $storehash{'group'} = $sec;
2660: } else {
2661: $storehash{'section'} = $sec;
2662: }
2663: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2664: }
2665: }
2666: return;
2667: }
2668:
1.351 www 2669: sub get_course_adv_roles {
1.948 raeburn 2670: my ($cid,$codes) = @_;
1.620 albertel 2671: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2672: my %coursehash=&coursedescription($cid);
1.470 www 2673: my %nothide=();
1.800 albertel 2674: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2675: if ($user !~ /:/) {
2676: $nothide{join(':',split(/[\@]/,$user))}=1;
2677: } else {
2678: $nothide{$user}=1;
2679: }
1.470 www 2680: }
1.351 www 2681: my %returnhash=();
2682: my %dumphash=
2683: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2684: my $now=time;
1.800 albertel 2685: foreach my $entry (keys %dumphash) {
2686: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2687: if (($tstart) && ($tstart<0)) { next; }
2688: if (($tend) && ($tend<$now)) { next; }
2689: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2690: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2691: if ($username eq '' || $domain eq '') { next; }
1.470 www 2692: if ((&privileged($username,$domain)) &&
2693: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2694: if ($role eq 'cr') { next; }
1.948 raeburn 2695: if ($codes) {
2696: if ($section) { $role .= ':'.$section; }
2697: if ($returnhash{$role}) {
2698: $returnhash{$role}.=','.$username.':'.$domain;
2699: } else {
2700: $returnhash{$role}=$username.':'.$domain;
2701: }
1.351 www 2702: } else {
1.948 raeburn 2703: my $key=&plaintext($role);
1.973 bisitz 2704: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2705: if ($returnhash{$key}) {
2706: $returnhash{$key}.=','.$username.':'.$domain;
2707: } else {
2708: $returnhash{$key}=$username.':'.$domain;
2709: }
1.351 www 2710: }
1.948 raeburn 2711: }
1.400 www 2712: return %returnhash;
2713: }
2714:
2715: sub get_my_roles {
1.937 raeburn 2716: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2717: unless (defined($uname)) { $uname=$env{'user.name'}; }
2718: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2719: my (%dumphash,%nothide);
1.858 raeburn 2720: if ($context eq 'userroles') {
2721: %dumphash = &dump('roles',$udom,$uname);
2722: } else {
2723: %dumphash=
1.400 www 2724: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2725: if ($hidepriv) {
2726: my %coursehash=&coursedescription($udom.'_'.$uname);
2727: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2728: if ($user !~ /:/) {
2729: $nothide{join(':',split(/[\@]/,$user))} = 1;
2730: } else {
2731: $nothide{$user} = 1;
2732: }
2733: }
2734: }
1.858 raeburn 2735: }
1.400 www 2736: my %returnhash=();
2737: my $now=time;
1.800 albertel 2738: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2739: my ($role,$tend,$tstart);
2740: if ($context eq 'userroles') {
2741: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2742: } else {
2743: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2744: }
1.400 www 2745: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2746: my $status = 'active';
1.939 raeburn 2747: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2748: $status = 'previous';
2749: }
2750: if (($tstart) && ($now<$tstart)) {
2751: $status = 'future';
2752: }
2753: if (ref($types) eq 'ARRAY') {
2754: if (!grep(/^\Q$status\E$/,@{$types})) {
2755: next;
2756: }
2757: } else {
2758: if ($status ne 'active') {
2759: next;
2760: }
2761: }
1.867 raeburn 2762: my ($rolecode,$username,$domain,$section,$area);
2763: if ($context eq 'userroles') {
2764: ($area,$rolecode) = split(/_/,$entry);
2765: (undef,$domain,$username,$section) = split(/\//,$area);
2766: } else {
2767: ($role,$username,$domain,$section) = split(/\:/,$entry);
2768: }
1.832 raeburn 2769: if (ref($roledoms) eq 'ARRAY') {
2770: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2771: next;
2772: }
2773: }
2774: if (ref($roles) eq 'ARRAY') {
2775: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2776: if ($role =~ /^cr\//) {
2777: if (!grep(/^cr$/,@{$roles})) {
2778: next;
2779: }
2780: } else {
2781: next;
2782: }
1.832 raeburn 2783: }
1.867 raeburn 2784: }
1.937 raeburn 2785: if ($hidepriv) {
2786: if ((&privileged($username,$domain)) &&
2787: (!$nothide{$username.':'.$domain})) {
2788: next;
2789: }
2790: }
1.933 raeburn 2791: if ($withsec) {
2792: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2793: $tstart.':'.$tend;
2794: } else {
2795: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2796: }
1.832 raeburn 2797: }
1.373 www 2798: return %returnhash;
1.399 www 2799: }
2800:
2801: # ----------------------------------------------------- Frontpage Announcements
2802: #
2803: #
2804:
2805: sub postannounce {
2806: my ($server,$text)=@_;
1.844 albertel 2807: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2808: unless ($text=~/\w/) { $text=''; }
2809: return &reply('setannounce:'.&escape($text),$server);
2810: }
2811:
2812: sub getannounce {
1.448 albertel 2813:
2814: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2815: my $announcement='';
1.800 albertel 2816: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2817: close($fh);
1.399 www 2818: if ($announcement=~/\w/) {
2819: return
2820: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2821: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2822: } else {
2823: return '';
2824: }
2825: } else {
2826: return '';
2827: }
1.351 www 2828: }
1.353 www 2829:
2830: # ---------------------------------------------------------- Course ID routines
2831: # Deal with domain's nohist_courseid.db files
2832: #
2833:
2834: sub courseidput {
1.921 raeburn 2835: my ($domain,$storehash,$coursehome,$caller) = @_;
2836: my $outcome;
2837: if ($caller eq 'timeonly') {
2838: my $cids = '';
2839: foreach my $item (keys(%$storehash)) {
2840: $cids.=&escape($item).'&';
2841: }
2842: $cids=~s/\&$//;
2843: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2844: $coursehome);
2845: } else {
2846: my $items = '';
2847: foreach my $item (keys(%$storehash)) {
2848: $items.= &escape($item).'='.
2849: &freeze_escape($$storehash{$item}).'&';
2850: }
2851: $items=~s/\&$//;
2852: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2853: $coursehome);
1.918 raeburn 2854: }
2855: if ($outcome eq 'unknown_cmd') {
2856: my $what;
2857: foreach my $cid (keys(%$storehash)) {
2858: $what .= &escape($cid).'=';
1.921 raeburn 2859: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2860: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2861: }
2862: $what =~ s/\:$/&/;
2863: }
2864: $what =~ s/\&$//;
2865: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2866: } else {
2867: return $outcome;
2868: }
1.353 www 2869: }
2870:
2871: sub courseiddump {
1.921 raeburn 2872: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2873: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 raeburn 2874: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2875: my $as_hash = 1;
2876: my %returnhash;
2877: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2878: my %libserv = &all_library();
2879: foreach my $tryserver (keys(%libserv)) {
2880: if ( ( $hostidflag == 1
2881: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2882: || (!defined($hostidflag)) ) {
2883:
1.918 raeburn 2884: if (($domfilter eq '') ||
2885: (&host_domain($tryserver) eq $domfilter)) {
2886: my $rep =
2887: &reply('courseiddump:'.&host_domain($tryserver).':'.
2888: $sincefilter.':'.&escape($descfilter).':'.
2889: &escape($instcodefilter).':'.&escape($ownerfilter).
2890: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2891: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2892: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2893: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2894: my @pairs=split(/\&/,$rep);
2895: foreach my $item (@pairs) {
2896: my ($key,$value)=split(/\=/,$item,2);
2897: $key = &unescape($key);
2898: next if ($key =~ /^error: 2 /);
2899: my $result = &thaw_unescape($value);
2900: if (ref($result) eq 'HASH') {
2901: $returnhash{$key}=$result;
2902: } else {
1.921 raeburn 2903: my @responses = split(/:/,$value);
2904: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2905: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2906: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2907: }
2908: }
1.353 www 2909: }
2910: }
2911: }
2912: }
2913: return %returnhash;
2914: }
2915:
1.658 raeburn 2916: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2917:
2918: sub dcmailput {
1.685 raeburn 2919: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2920: my $status = &Apache::lonnet::critical(
1.740 www 2921: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2922: &escape($message),$server);
1.662 raeburn 2923: return $status;
2924: }
2925:
1.658 raeburn 2926: sub dcmaildump {
2927: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2928: my %returnhash=();
1.846 albertel 2929:
2930: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2931: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2932: &escape($enddate).':';
2933: my @esc_senders=map { &escape($_)} @$senders;
2934: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2935: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2936: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2937: if (($key) && ($value)) {
2938: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2939: }
2940: }
2941: }
2942: return %returnhash;
2943: }
1.662 raeburn 2944: # ---------------------------------------------------------- Domain roles
2945:
2946: sub get_domain_roles {
2947: my ($dom,$roles,$startdate,$enddate)=@_;
2948: if (undef($startdate) || $startdate eq '') {
2949: $startdate = '.';
2950: }
2951: if (undef($enddate) || $enddate eq '') {
2952: $enddate = '.';
2953: }
1.922 raeburn 2954: my $rolelist;
2955: if (ref($roles) eq 'ARRAY') {
2956: $rolelist = join(':',@{$roles});
2957: }
1.662 raeburn 2958: my %personnel = ();
1.841 albertel 2959:
2960: my %servers = &get_servers($dom,'library');
2961: foreach my $tryserver (keys(%servers)) {
2962: %{$personnel{$tryserver}}=();
2963: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2964: &escape($startdate).':'.
2965: &escape($enddate).':'.
2966: &escape($rolelist), $tryserver))) {
2967: my ($key,$value) = split(/\=/,$line,2);
2968: if (($key) && ($value)) {
2969: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2970: }
2971: }
1.662 raeburn 2972: }
2973: return %personnel;
2974: }
1.658 raeburn 2975:
1.149 www 2976: # ----------------------------------------------------------- Check out an item
2977:
1.504 albertel 2978: sub get_first_access {
2979: my ($type,$argsymb)=@_;
1.790 albertel 2980: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2981: if ($argsymb) { $symb=$argsymb; }
2982: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2983: if ($type eq 'course') {
2984: $res='course';
2985: } elsif ($type eq 'map') {
1.588 albertel 2986: $res=&symbread($map);
2987: } else {
2988: $res=$symb;
2989: }
2990: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2991: return $times{"$courseid\0$res"};
1.504 albertel 2992: }
2993:
2994: sub set_first_access {
2995: my ($type)=@_;
1.790 albertel 2996: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2997: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 2998: if ($type eq 'course') {
2999: $res='course';
3000: } elsif ($type eq 'map') {
1.588 albertel 3001: $res=&symbread($map);
3002: } else {
3003: $res=$symb;
3004: }
3005: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3006: if (!$firstaccess) {
1.588 albertel 3007: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3008: }
3009: return 'already_set';
1.504 albertel 3010: }
3011:
1.149 www 3012: sub checkout {
3013: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3014: my $now=time;
3015: my $lonhost=$perlvar{'lonHostID'};
3016: my $infostr=&escape(
1.234 www 3017: 'CHECKOUTTOKEN&'.
1.149 www 3018: $tuname.'&'.
3019: $tudom.'&'.
3020: $tcrsid.'&'.
3021: $symb.'&'.
3022: $now.'&'.$ENV{'REMOTE_ADDR'});
3023: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3024: if ($token=~/^error\:/) {
1.672 albertel 3025: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3026: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3027: "</font>");
3028: return '';
3029: }
3030:
1.149 www 3031: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3032: $token=~tr/a-z/A-Z/;
3033:
1.153 www 3034: my %infohash=('resource.0.outtoken' => $token,
3035: 'resource.0.checkouttime' => $now,
3036: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3037:
3038: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3039: return '';
1.151 www 3040: } else {
1.672 albertel 3041: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3042: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3043: "</font>");
1.149 www 3044: }
3045:
3046: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3047: &escape('Checkout '.$infostr.' - '.
3048: $token)) ne 'ok') {
3049: return '';
1.151 www 3050: } else {
1.672 albertel 3051: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3052: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3053: "</font>");
1.149 www 3054: }
1.151 www 3055: return $token;
1.149 www 3056: }
3057:
3058: # ------------------------------------------------------------ Check in an item
3059:
3060: sub checkin {
3061: my $token=shift;
1.150 www 3062: my $now=time;
3063: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3064: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3065: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3066: $dtoken=~s/\W/\_/g;
1.234 www 3067: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3068: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3069:
1.154 www 3070: unless (($tuname) && ($tudom)) {
3071: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3072: return '';
3073: }
3074:
3075: unless (&allowed('mgr',$tcrsid)) {
3076: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3077: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3078: return '';
3079: }
3080:
1.153 www 3081: my %infohash=('resource.0.intoken' => $token,
3082: 'resource.0.checkintime' => $now,
3083: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3084:
3085: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3086: return '';
3087: }
3088:
3089: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3090: &escape('Checkin - '.$token)) ne 'ok') {
3091: return '';
3092: }
3093:
3094: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3095: }
3096:
3097: # --------------------------------------------- Set Expire Date for Spreadsheet
3098:
3099: sub expirespread {
3100: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3101: my $cid=$env{'request.course.id'};
1.110 www 3102: if ($cid) {
3103: my $now=time;
3104: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3105: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3106: $env{'course.'.$cid.'.num'}.
1.110 www 3107: ':nohist_expirationdates:'.
3108: &escape($key).'='.$now,
1.620 albertel 3109: $env{'course.'.$cid.'.home'})
1.110 www 3110: }
3111: return 'ok';
1.14 www 3112: }
3113:
1.109 www 3114: # ----------------------------------------------------- Devalidate Spreadsheets
3115:
3116: sub devalidate {
1.325 www 3117: my ($symb,$uname,$udom)=@_;
1.620 albertel 3118: my $cid=$env{'request.course.id'};
1.109 www 3119: if ($cid) {
1.391 matthew 3120: # delete the stored spreadsheets for
3121: # - the student level sheet of this user in course's homespace
3122: # - the assessment level sheet for this resource
3123: # for this user in user's homespace
1.553 albertel 3124: # - current conditional state info
1.325 www 3125: my $key=$uname.':'.$udom.':';
1.109 www 3126: my $status=
1.299 matthew 3127: &del('nohist_calculatedsheets',
1.391 matthew 3128: [$key.'studentcalc:'],
1.620 albertel 3129: $env{'course.'.$cid.'.domain'},
3130: $env{'course.'.$cid.'.num'})
1.133 albertel 3131: .' '.
3132: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3133: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3134: unless ($status eq 'ok ok') {
3135: &logthis('Could not devalidate spreadsheet '.
1.325 www 3136: $uname.' at '.$udom.' for '.
1.109 www 3137: $symb.': '.$status);
1.133 albertel 3138: }
1.553 albertel 3139: &delenv('user.state.'.$cid);
1.109 www 3140: }
3141: }
3142:
1.265 albertel 3143: sub get_scalar {
3144: my ($string,$end) = @_;
3145: my $value;
3146: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3147: $value = $1;
3148: } elsif ($$string =~ s/^([^&]*?)&//) {
3149: $value = $1;
3150: }
3151: return &unescape($value);
3152: }
3153:
3154: sub array2str {
3155: my (@array) = @_;
3156: my $result=&arrayref2str(\@array);
3157: $result=~s/^__ARRAY_REF__//;
3158: $result=~s/__END_ARRAY_REF__$//;
3159: return $result;
3160: }
3161:
1.204 albertel 3162: sub arrayref2str {
3163: my ($arrayref) = @_;
1.265 albertel 3164: my $result='__ARRAY_REF__';
1.204 albertel 3165: foreach my $elem (@$arrayref) {
1.265 albertel 3166: if(ref($elem) eq 'ARRAY') {
3167: $result.=&arrayref2str($elem).'&';
3168: } elsif(ref($elem) eq 'HASH') {
3169: $result.=&hashref2str($elem).'&';
3170: } elsif(ref($elem)) {
3171: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3172: } else {
3173: $result.=&escape($elem).'&';
3174: }
3175: }
3176: $result=~s/\&$//;
1.265 albertel 3177: $result .= '__END_ARRAY_REF__';
1.204 albertel 3178: return $result;
3179: }
3180:
1.168 albertel 3181: sub hash2str {
1.204 albertel 3182: my (%hash) = @_;
3183: my $result=&hashref2str(\%hash);
1.265 albertel 3184: $result=~s/^__HASH_REF__//;
3185: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3186: return $result;
3187: }
3188:
3189: sub hashref2str {
3190: my ($hashref)=@_;
1.265 albertel 3191: my $result='__HASH_REF__';
1.800 albertel 3192: foreach my $key (sort(keys(%$hashref))) {
3193: if (ref($key) eq 'ARRAY') {
3194: $result.=&arrayref2str($key).'=';
3195: } elsif (ref($key) eq 'HASH') {
3196: $result.=&hashref2str($key).'=';
3197: } elsif (ref($key)) {
1.265 albertel 3198: $result.='=';
1.800 albertel 3199: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3200: } else {
1.800 albertel 3201: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3202: }
3203:
1.800 albertel 3204: if(ref($hashref->{$key}) eq 'ARRAY') {
3205: $result.=&arrayref2str($hashref->{$key}).'&';
3206: } elsif(ref($hashref->{$key}) eq 'HASH') {
3207: $result.=&hashref2str($hashref->{$key}).'&';
3208: } elsif(ref($hashref->{$key})) {
1.265 albertel 3209: $result.='&';
1.800 albertel 3210: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3211: } else {
1.800 albertel 3212: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3213: }
3214: }
1.168 albertel 3215: $result=~s/\&$//;
1.265 albertel 3216: $result .= '__END_HASH_REF__';
1.168 albertel 3217: return $result;
3218: }
3219:
3220: sub str2hash {
1.265 albertel 3221: my ($string)=@_;
3222: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3223: return %$hash;
3224: }
3225:
3226: sub str2hashref {
1.168 albertel 3227: my ($string) = @_;
1.265 albertel 3228:
3229: my %hash;
3230:
3231: if($string !~ /^__HASH_REF__/) {
3232: if (! ($string eq '' || !defined($string))) {
3233: $hash{'error'}='Not hash reference';
3234: }
3235: return (\%hash, $string);
3236: }
3237:
3238: $string =~ s/^__HASH_REF__//;
3239:
3240: while($string !~ /^__END_HASH_REF__/) {
3241: #key
3242: my $key='';
3243: if($string =~ /^__HASH_REF__/) {
3244: ($key, $string)=&str2hashref($string);
3245: if(defined($key->{'error'})) {
3246: $hash{'error'}='Bad data';
3247: return (\%hash, $string);
3248: }
3249: } elsif($string =~ /^__ARRAY_REF__/) {
3250: ($key, $string)=&str2arrayref($string);
3251: if($key->[0] eq 'Array reference error') {
3252: $hash{'error'}='Bad data';
3253: return (\%hash, $string);
3254: }
3255: } else {
3256: $string =~ s/^(.*?)=//;
1.267 albertel 3257: $key=&unescape($1);
1.265 albertel 3258: }
3259: $string =~ s/^=//;
3260:
3261: #value
3262: my $value='';
3263: if($string =~ /^__HASH_REF__/) {
3264: ($value, $string)=&str2hashref($string);
3265: if(defined($value->{'error'})) {
3266: $hash{'error'}='Bad data';
3267: return (\%hash, $string);
3268: }
3269: } elsif($string =~ /^__ARRAY_REF__/) {
3270: ($value, $string)=&str2arrayref($string);
3271: if($value->[0] eq 'Array reference error') {
3272: $hash{'error'}='Bad data';
3273: return (\%hash, $string);
3274: }
3275: } else {
3276: $value=&get_scalar(\$string,'__END_HASH_REF__');
3277: }
3278: $string =~ s/^&//;
3279:
3280: $hash{$key}=$value;
1.204 albertel 3281: }
1.265 albertel 3282:
3283: $string =~ s/^__END_HASH_REF__//;
3284:
3285: return (\%hash, $string);
1.204 albertel 3286: }
3287:
3288: sub str2array {
1.265 albertel 3289: my ($string)=@_;
3290: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3291: return @$array;
3292: }
3293:
3294: sub str2arrayref {
1.204 albertel 3295: my ($string) = @_;
1.265 albertel 3296: my @array;
3297:
3298: if($string !~ /^__ARRAY_REF__/) {
3299: if (! ($string eq '' || !defined($string))) {
3300: $array[0]='Array reference error';
3301: }
3302: return (\@array, $string);
3303: }
3304:
3305: $string =~ s/^__ARRAY_REF__//;
3306:
3307: while($string !~ /^__END_ARRAY_REF__/) {
3308: my $value='';
3309: if($string =~ /^__HASH_REF__/) {
3310: ($value, $string)=&str2hashref($string);
3311: if(defined($value->{'error'})) {
3312: $array[0] ='Array reference error';
3313: return (\@array, $string);
3314: }
3315: } elsif($string =~ /^__ARRAY_REF__/) {
3316: ($value, $string)=&str2arrayref($string);
3317: if($value->[0] eq 'Array reference error') {
3318: $array[0] ='Array reference error';
3319: return (\@array, $string);
3320: }
3321: } else {
3322: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3323: }
3324: $string =~ s/^&//;
3325:
3326: push(@array, $value);
1.191 harris41 3327: }
1.265 albertel 3328:
3329: $string =~ s/^__END_ARRAY_REF__//;
3330:
3331: return (\@array, $string);
1.168 albertel 3332: }
3333:
1.167 albertel 3334: # -------------------------------------------------------------------Temp Store
3335:
1.168 albertel 3336: sub tmpreset {
3337: my ($symb,$namespace,$domain,$stuname) = @_;
3338: if (!$symb) {
3339: $symb=&symbread();
1.620 albertel 3340: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3341: }
3342: $symb=escape($symb);
3343:
1.620 albertel 3344: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3345: $namespace=~s/\//\_/g;
3346: $namespace=~s/\W//g;
3347:
1.620 albertel 3348: if (!$domain) { $domain=$env{'user.domain'}; }
3349: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3350: if ($domain eq 'public' && $stuname eq 'public') {
3351: $stuname=$ENV{'REMOTE_ADDR'};
3352: }
1.168 albertel 3353: my $path=$perlvar{'lonDaemons'}.'/tmp';
3354: my %hash;
3355: if (tie(%hash,'GDBM_File',
3356: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3357: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3358: foreach my $key (keys %hash) {
1.180 albertel 3359: if ($key=~ /:$symb/) {
1.168 albertel 3360: delete($hash{$key});
3361: }
3362: }
3363: }
3364: }
3365:
1.167 albertel 3366: sub tmpstore {
1.168 albertel 3367: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3368:
3369: if (!$symb) {
3370: $symb=&symbread();
1.620 albertel 3371: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3372: }
3373: $symb=escape($symb);
3374:
3375: if (!$namespace) {
3376: # I don't think we would ever want to store this for a course.
3377: # it seems this will only be used if we don't have a course.
1.620 albertel 3378: #$namespace=$env{'request.course.id'};
1.168 albertel 3379: #if (!$namespace) {
1.620 albertel 3380: $namespace=$env{'request.state'};
1.168 albertel 3381: #}
3382: }
3383: $namespace=~s/\//\_/g;
3384: $namespace=~s/\W//g;
1.620 albertel 3385: if (!$domain) { $domain=$env{'user.domain'}; }
3386: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3387: if ($domain eq 'public' && $stuname eq 'public') {
3388: $stuname=$ENV{'REMOTE_ADDR'};
3389: }
1.168 albertel 3390: my $now=time;
3391: my %hash;
3392: my $path=$perlvar{'lonDaemons'}.'/tmp';
3393: if (tie(%hash,'GDBM_File',
3394: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3395: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3396: $hash{"version:$symb"}++;
3397: my $version=$hash{"version:$symb"};
3398: my $allkeys='';
3399: foreach my $key (keys(%$storehash)) {
3400: $allkeys.=$key.':';
1.591 albertel 3401: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3402: }
3403: $hash{"$version:$symb:timestamp"}=$now;
3404: $allkeys.='timestamp';
3405: $hash{"$version:keys:$symb"}=$allkeys;
3406: if (untie(%hash)) {
3407: return 'ok';
3408: } else {
3409: return "error:$!";
3410: }
3411: } else {
3412: return "error:$!";
3413: }
3414: }
1.167 albertel 3415:
1.168 albertel 3416: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3417:
1.168 albertel 3418: sub tmprestore {
3419: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3420:
1.168 albertel 3421: if (!$symb) {
3422: $symb=&symbread();
1.620 albertel 3423: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3424: }
3425: $symb=escape($symb);
3426:
1.620 albertel 3427: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3428:
1.620 albertel 3429: if (!$domain) { $domain=$env{'user.domain'}; }
3430: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3431: if ($domain eq 'public' && $stuname eq 'public') {
3432: $stuname=$ENV{'REMOTE_ADDR'};
3433: }
1.168 albertel 3434: my %returnhash;
3435: $namespace=~s/\//\_/g;
3436: $namespace=~s/\W//g;
3437: my %hash;
3438: my $path=$perlvar{'lonDaemons'}.'/tmp';
3439: if (tie(%hash,'GDBM_File',
3440: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3441: &GDBM_READER(),0640)) {
1.168 albertel 3442: my $version=$hash{"version:$symb"};
3443: $returnhash{'version'}=$version;
3444: my $scope;
3445: for ($scope=1;$scope<=$version;$scope++) {
3446: my $vkeys=$hash{"$scope:keys:$symb"};
3447: my @keys=split(/:/,$vkeys);
3448: my $key;
3449: $returnhash{"$scope:keys"}=$vkeys;
3450: foreach $key (@keys) {
1.591 albertel 3451: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3452: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3453: }
3454: }
1.168 albertel 3455: if (!(untie(%hash))) {
3456: return "error:$!";
3457: }
3458: } else {
3459: return "error:$!";
3460: }
3461: return %returnhash;
1.167 albertel 3462: }
3463:
1.9 www 3464: # ----------------------------------------------------------------------- Store
3465:
3466: sub store {
1.124 www 3467: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3468: my $home='';
3469:
1.168 albertel 3470: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3471:
1.213 www 3472: $symb=&symbclean($symb);
1.122 albertel 3473: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3474:
1.620 albertel 3475: if (!$domain) { $domain=$env{'user.domain'}; }
3476: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3477:
3478: &devalidate($symb,$stuname,$domain);
1.109 www 3479:
3480: $symb=escape($symb);
1.187 www 3481: if (!$namespace) {
1.620 albertel 3482: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3483: return '';
3484: }
3485: }
1.620 albertel 3486: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3487:
3488: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3489: $$storehash{'host'}=$perlvar{'lonHostID'};
3490:
1.12 www 3491: my $namevalue='';
1.800 albertel 3492: foreach my $key (keys(%$storehash)) {
3493: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3494: }
1.12 www 3495: $namevalue=~s/\&$//;
1.187 www 3496: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3497: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3498: }
3499:
1.47 www 3500: # -------------------------------------------------------------- Critical Store
3501:
3502: sub cstore {
1.124 www 3503: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3504: my $home='';
3505:
1.168 albertel 3506: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3507:
1.213 www 3508: $symb=&symbclean($symb);
1.122 albertel 3509: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3510:
1.620 albertel 3511: if (!$domain) { $domain=$env{'user.domain'}; }
3512: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3513:
3514: &devalidate($symb,$stuname,$domain);
1.109 www 3515:
3516: $symb=escape($symb);
1.187 www 3517: if (!$namespace) {
1.620 albertel 3518: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3519: return '';
3520: }
3521: }
1.620 albertel 3522: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3523:
3524: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3525: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3526:
1.47 www 3527: my $namevalue='';
1.800 albertel 3528: foreach my $key (keys(%$storehash)) {
3529: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3530: }
1.47 www 3531: $namevalue=~s/\&$//;
1.187 www 3532: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3533: return critical
3534: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3535: }
3536:
1.9 www 3537: # --------------------------------------------------------------------- Restore
3538:
3539: sub restore {
1.124 www 3540: my ($symb,$namespace,$domain,$stuname) = @_;
3541: my $home='';
3542:
1.168 albertel 3543: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3544:
1.122 albertel 3545: if (!$symb) {
3546: unless ($symb=escape(&symbread())) { return ''; }
3547: } else {
1.213 www 3548: $symb=&escape(&symbclean($symb));
1.122 albertel 3549: }
1.188 www 3550: if (!$namespace) {
1.620 albertel 3551: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3552: return '';
3553: }
3554: }
1.620 albertel 3555: if (!$domain) { $domain=$env{'user.domain'}; }
3556: if (!$stuname) { $stuname=$env{'user.name'}; }
3557: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3558: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3559:
1.12 www 3560: my %returnhash=();
1.800 albertel 3561: foreach my $line (split(/\&/,$answer)) {
3562: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3563: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3564: }
1.75 www 3565: my $version;
3566: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3567: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3568: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3569: }
1.75 www 3570: }
1.13 www 3571: return %returnhash;
1.34 www 3572: }
3573:
3574: # ---------------------------------------------------------- Course Description
3575:
3576: sub coursedescription {
1.731 albertel 3577: my ($courseid,$args)=@_;
1.34 www 3578: $courseid=~s/^\///;
1.49 www 3579: $courseid=~s/\_/\//g;
1.34 www 3580: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3581: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3582: my $normalid=$cdomain.'_'.$cnum;
3583: # need to always cache even if we get errors otherwise we keep
3584: # trying and trying and trying to get the course description.
3585: my %envhash=();
3586: my %returnhash=();
1.731 albertel 3587:
3588: my $expiretime=600;
3589: if ($env{'request.course.id'} eq $normalid) {
3590: $expiretime=120;
3591: }
3592:
3593: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3594: if (!$args->{'freshen_cache'}
3595: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3596: foreach my $key (keys(%env)) {
3597: next if ($key !~ /^\Q$prefix\E(.*)/);
3598: my ($setting) = $1;
3599: $returnhash{$setting} = $env{$key};
3600: }
3601: return %returnhash;
3602: }
3603:
3604: # get the data agin
3605: if (!$args->{'one_time'}) {
3606: $envhash{'course.'.$normalid.'.last_cache'}=time;
3607: }
1.811 albertel 3608:
1.34 www 3609: if ($chome ne 'no_host') {
1.302 albertel 3610: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3611: if (!exists($returnhash{'con_lost'})) {
3612: $returnhash{'home'}= $chome;
3613: $returnhash{'domain'} = $cdomain;
3614: $returnhash{'num'} = $cnum;
1.741 raeburn 3615: if (!defined($returnhash{'type'})) {
3616: $returnhash{'type'} = 'Course';
3617: }
1.130 albertel 3618: while (my ($name,$value) = each %returnhash) {
1.53 www 3619: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3620: }
1.270 www 3621: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3622: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3623: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3624: $envhash{'course.'.$normalid.'.home'}=$chome;
3625: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3626: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3627: }
3628: }
1.731 albertel 3629: if (!$args->{'one_time'}) {
1.949 raeburn 3630: &appenv(\%envhash);
1.731 albertel 3631: }
1.302 albertel 3632: return %returnhash;
1.461 www 3633: }
3634:
3635: # -------------------------------------------------See if a user is privileged
3636:
3637: sub privileged {
3638: my ($username,$domain)=@_;
3639: my $rolesdump=&reply("dump:$domain:$username:roles",
3640: &homeserver($username,$domain));
3641: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3642: my $now=time;
3643: if ($rolesdump ne '') {
1.800 albertel 3644: foreach my $entry (split(/&/,$rolesdump)) {
3645: if ($entry!~/^rolesdef_/) {
3646: my ($area,$role)=split(/=/,$entry);
1.461 www 3647: $area=~s/\_\w\w$//;
3648: my ($trole,$tend,$tstart)=split(/_/,$role);
3649: if (($trole eq 'dc') || ($trole eq 'su')) {
3650: my $active=1;
3651: if ($tend) {
3652: if ($tend<$now) { $active=0; }
3653: }
3654: if ($tstart) {
3655: if ($tstart>$now) { $active=0; }
3656: }
3657: if ($active) { return 1; }
3658: }
3659: }
3660: }
3661: }
3662: return 0;
1.9 www 3663: }
1.1 albertel 3664:
1.103 harris41 3665: # -------------------------------------------------------- Get user privileges
1.11 www 3666:
3667: sub rolesinit {
3668: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3669: my %userroles;
1.11 www 3670: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3671: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3672: my %allroles=();
1.678 raeburn 3673: my %allgroups=();
1.11 www 3674: my $now=time;
1.966 raeburn 3675: %userroles = ('user.login.time' => $now);
1.678 raeburn 3676: my $group_privs;
1.11 www 3677:
3678: if ($rolesdump ne '') {
1.800 albertel 3679: foreach my $entry (split(/&/,$rolesdump)) {
3680: if ($entry!~/^rolesdef_/) {
3681: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3682: $area=~s/\_\w\w$//;
1.678 raeburn 3683: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3684: if ($role=~/^cr/) {
1.807 albertel 3685: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3686: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3687: ($tend,$tstart)=split('_',$trest);
3688: } else {
3689: $trole=$role;
3690: }
1.678 raeburn 3691: } elsif ($role =~ m|^gr/|) {
3692: ($trole,$tend,$tstart) = split(/_/,$role);
3693: ($trole,$group_privs) = split(/\//,$trole);
3694: $group_privs = &unescape($group_privs);
1.587 albertel 3695: } else {
3696: ($trole,$tend,$tstart)=split(/_/,$role);
3697: }
1.743 albertel 3698: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3699: $username);
3700: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3701: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3702: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3703: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3704: my $spec=$trole.'.'.$area;
3705: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3706: if ($trole =~ /^cr\//) {
1.567 raeburn 3707: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3708: } elsif ($trole eq 'gr') {
3709: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3710: } else {
1.567 raeburn 3711: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3712: }
1.12 www 3713: }
1.662 raeburn 3714: }
1.191 harris41 3715: }
1.743 albertel 3716: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3717: $userroles{'user.adv'} = $adv;
3718: $userroles{'user.author'} = $author;
1.620 albertel 3719: $env{'user.adv'}=$adv;
1.11 www 3720: }
1.743 albertel 3721: return \%userroles;
1.11 www 3722: }
3723:
1.567 raeburn 3724: sub set_arearole {
3725: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3726: # log the associated role with the area
3727: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3728: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3729: }
3730:
3731: sub custom_roleprivs {
3732: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3733: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3734: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3735: if (&hostname($homsvr) ne '') {
1.567 raeburn 3736: my ($rdummy,$roledef)=
3737: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3738: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3739: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3740: if (defined($syspriv)) {
3741: $$allroles{'cm./'}.=':'.$syspriv;
3742: $$allroles{$spec.'./'}.=':'.$syspriv;
3743: }
3744: if ($tdomain ne '') {
3745: if (defined($dompriv)) {
3746: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3747: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3748: }
3749: if (($trest ne '') && (defined($coursepriv))) {
3750: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3751: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3752: }
3753: }
3754: }
3755: }
3756: }
3757:
1.678 raeburn 3758: sub group_roleprivs {
3759: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3760: my $access = 1;
3761: my $now = time;
3762: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3763: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3764: if ($access) {
1.811 albertel 3765: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3766: $$allgroups{$course}{$group} .=':'.$group_privs;
3767: }
3768: }
1.567 raeburn 3769:
3770: sub standard_roleprivs {
3771: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3772: if (defined($pr{$trole.':s'})) {
3773: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3774: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3775: }
3776: if ($tdomain ne '') {
3777: if (defined($pr{$trole.':d'})) {
3778: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3779: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3780: }
3781: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3782: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3783: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3784: }
3785: }
3786: }
3787:
3788: sub set_userprivs {
1.678 raeburn 3789: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3790: my $author=0;
3791: my $adv=0;
1.678 raeburn 3792: my %grouproles = ();
3793: if (keys(%{$allgroups}) > 0) {
3794: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3795: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3796: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3797: $trole = $1;
3798: $area = $2;
1.681 raeburn 3799: $sec = $3;
3800: $extendedarea = $area.$sec;
3801: if (exists($$allgroups{$area})) {
3802: foreach my $group (keys(%{$$allgroups{$area}})) {
3803: my $spec = $trole.'.'.$extendedarea;
3804: $grouproles{$spec.'.'.$area.'/'.$group} =
3805: $$allgroups{$area}{$group};
1.678 raeburn 3806: }
3807: }
3808: }
3809: }
3810: }
1.800 albertel 3811: foreach my $group (keys(%grouproles)) {
3812: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3813: }
1.800 albertel 3814: foreach my $role (keys(%{$allroles})) {
3815: my %thesepriv;
1.941 raeburn 3816: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3817: foreach my $item (split(/:/,$$allroles{$role})) {
3818: if ($item ne '') {
3819: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3820: if ($restrictions eq '') {
3821: $thesepriv{$privilege}='F';
3822: } elsif ($thesepriv{$privilege} ne 'F') {
3823: $thesepriv{$privilege}.=$restrictions;
3824: }
3825: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3826: }
3827: }
3828: my $thesestr='';
1.800 albertel 3829: foreach my $priv (keys(%thesepriv)) {
3830: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3831: }
3832: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3833: }
3834: return ($author,$adv);
3835: }
3836:
1.12 www 3837: # --------------------------------------------------------------- get interface
3838:
3839: sub get {
1.131 albertel 3840: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3841: my $items='';
1.800 albertel 3842: foreach my $item (@$storearr) {
3843: $items.=&escape($item).'&';
1.191 harris41 3844: }
1.12 www 3845: $items=~s/\&$//;
1.620 albertel 3846: if (!$udomain) { $udomain=$env{'user.domain'}; }
3847: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3848: my $uhome=&homeserver($uname,$udomain);
3849:
1.133 albertel 3850: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3851: my @pairs=split(/\&/,$rep);
1.273 albertel 3852: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3853: return @pairs;
3854: }
1.15 www 3855: my %returnhash=();
1.42 www 3856: my $i=0;
1.800 albertel 3857: foreach my $item (@$storearr) {
3858: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3859: $i++;
1.191 harris41 3860: }
1.15 www 3861: return %returnhash;
1.27 www 3862: }
3863:
3864: # --------------------------------------------------------------- del interface
3865:
3866: sub del {
1.133 albertel 3867: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3868: my $items='';
1.800 albertel 3869: foreach my $item (@$storearr) {
3870: $items.=&escape($item).'&';
1.191 harris41 3871: }
1.984 neumanie 3872:
1.27 www 3873: $items=~s/\&$//;
1.620 albertel 3874: if (!$udomain) { $udomain=$env{'user.domain'}; }
3875: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3876: my $uhome=&homeserver($uname,$udomain);
3877: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3878: }
3879:
3880: # -------------------------------------------------------------- dump interface
3881:
3882: sub dump {
1.755 albertel 3883: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3884: if (!$udomain) { $udomain=$env{'user.domain'}; }
3885: if (!$uname) { $uname=$env{'user.name'}; }
3886: my $uhome=&homeserver($uname,$udomain);
3887: if ($regexp) {
3888: $regexp=&escape($regexp);
3889: } else {
3890: $regexp='.';
3891: }
3892: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3893: my @pairs=split(/\&/,$rep);
3894: my %returnhash=();
3895: foreach my $item (@pairs) {
3896: my ($key,$value)=split(/=/,$item,2);
3897: $key = &unescape($key);
3898: next if ($key =~ /^error: 2 /);
3899: $returnhash{$key}=&thaw_unescape($value);
3900: }
3901: return %returnhash;
1.407 www 3902: }
3903:
1.717 albertel 3904: # --------------------------------------------------------- dumpstore interface
3905:
3906: sub dumpstore {
3907: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3908: if (!$udomain) { $udomain=$env{'user.domain'}; }
3909: if (!$uname) { $uname=$env{'user.name'}; }
3910: my $uhome=&homeserver($uname,$udomain);
3911: if ($regexp) {
3912: $regexp=&escape($regexp);
3913: } else {
3914: $regexp='.';
3915: }
3916: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3917: my @pairs=split(/\&/,$rep);
3918: my %returnhash=();
3919: foreach my $item (@pairs) {
3920: my ($key,$value)=split(/=/,$item,2);
3921: next if ($key =~ /^error: 2 /);
3922: $returnhash{$key}=&thaw_unescape($value);
3923: }
3924: return %returnhash;
1.717 albertel 3925: }
3926:
1.407 www 3927: # -------------------------------------------------------------- keys interface
3928:
3929: sub getkeys {
3930: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3931: if (!$udomain) { $udomain=$env{'user.domain'}; }
3932: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3933: my $uhome=&homeserver($uname,$udomain);
3934: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3935: my @keyarray=();
1.800 albertel 3936: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3937: next if ($key =~ /^error: 2 /);
1.800 albertel 3938: push(@keyarray,&unescape($key));
1.407 www 3939: }
3940: return @keyarray;
1.318 matthew 3941: }
3942:
1.319 matthew 3943: # --------------------------------------------------------------- currentdump
3944: sub currentdump {
1.328 matthew 3945: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3946: $courseid = $env{'request.course.id'} if (! defined($courseid));
3947: $sdom = $env{'user.domain'} if (! defined($sdom));
3948: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3949: my $uhome = &homeserver($sname,$sdom);
3950: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3951: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3952: #
1.318 matthew 3953: my %returnhash=();
1.319 matthew 3954: #
3955: if ($rep eq "unknown_cmd") {
3956: # an old lond will not know currentdump
3957: # Do a dump and make it look like a currentdump
1.822 albertel 3958: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3959: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3960: my %hash = @tmp;
3961: @tmp=();
1.424 matthew 3962: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3963: } else {
3964: my @pairs=split(/\&/,$rep);
1.800 albertel 3965: foreach my $pair (@pairs) {
3966: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3967: my ($symb,$param) = split(/:/,$key);
3968: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3969: &thaw_unescape($value);
1.319 matthew 3970: }
1.191 harris41 3971: }
1.12 www 3972: return %returnhash;
1.424 matthew 3973: }
3974:
3975: sub convert_dump_to_currentdump{
3976: my %hash = %{shift()};
3977: my %returnhash;
3978: # Code ripped from lond, essentially. The only difference
3979: # here is the unescaping done by lonnet::dump(). Conceivably
3980: # we might run in to problems with parameter names =~ /^v\./
3981: while (my ($key,$value) = each(%hash)) {
3982: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3983: $symb = &unescape($symb);
3984: $param = &unescape($param);
1.424 matthew 3985: next if ($v eq 'version' || $symb eq 'keys');
3986: next if (exists($returnhash{$symb}) &&
3987: exists($returnhash{$symb}->{$param}) &&
3988: $returnhash{$symb}->{'v.'.$param} > $v);
3989: $returnhash{$symb}->{$param}=$value;
3990: $returnhash{$symb}->{'v.'.$param}=$v;
3991: }
3992: #
3993: # Remove all of the keys in the hashes which keep track of
3994: # the version of the parameter.
3995: while (my ($symb,$param_hash) = each(%returnhash)) {
3996: # use a foreach because we are going to delete from the hash.
3997: foreach my $key (keys(%$param_hash)) {
3998: delete($param_hash->{$key}) if ($key =~ /^v\./);
3999: }
4000: }
4001: return \%returnhash;
1.12 www 4002: }
4003:
1.627 albertel 4004: # ------------------------------------------------------ critical inc interface
4005:
4006: sub cinc {
4007: return &inc(@_,'critical');
4008: }
4009:
1.449 matthew 4010: # --------------------------------------------------------------- inc interface
4011:
4012: sub inc {
1.627 albertel 4013: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4014: if (!$udomain) { $udomain=$env{'user.domain'}; }
4015: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4016: my $uhome=&homeserver($uname,$udomain);
4017: my $items='';
4018: if (! ref($store)) {
4019: # got a single value, so use that instead
4020: $items = &escape($store).'=&';
4021: } elsif (ref($store) eq 'SCALAR') {
4022: $items = &escape($$store).'=&';
4023: } elsif (ref($store) eq 'ARRAY') {
4024: $items = join('=&',map {&escape($_);} @{$store});
4025: } elsif (ref($store) eq 'HASH') {
4026: while (my($key,$value) = each(%{$store})) {
4027: $items.= &escape($key).'='.&escape($value).'&';
4028: }
4029: }
4030: $items=~s/\&$//;
1.627 albertel 4031: if ($critical) {
4032: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4033: } else {
4034: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4035: }
1.449 matthew 4036: }
4037:
1.12 www 4038: # --------------------------------------------------------------- put interface
4039:
4040: sub put {
1.134 albertel 4041: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4042: if (!$udomain) { $udomain=$env{'user.domain'}; }
4043: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4044: my $uhome=&homeserver($uname,$udomain);
1.12 www 4045: my $items='';
1.800 albertel 4046: foreach my $item (keys(%$storehash)) {
4047: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4048: }
1.12 www 4049: $items=~s/\&$//;
1.134 albertel 4050: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4051: }
4052:
1.631 albertel 4053: # ------------------------------------------------------------ newput interface
4054:
4055: sub newput {
4056: my ($namespace,$storehash,$udomain,$uname)=@_;
4057: if (!$udomain) { $udomain=$env{'user.domain'}; }
4058: if (!$uname) { $uname=$env{'user.name'}; }
4059: my $uhome=&homeserver($uname,$udomain);
4060: my $items='';
4061: foreach my $key (keys(%$storehash)) {
4062: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4063: }
4064: $items=~s/\&$//;
4065: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4066: }
4067:
4068: # --------------------------------------------------------- putstore interface
4069:
1.524 raeburn 4070: sub putstore {
1.715 albertel 4071: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4072: if (!$udomain) { $udomain=$env{'user.domain'}; }
4073: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4074: my $uhome=&homeserver($uname,$udomain);
4075: my $items='';
1.715 albertel 4076: foreach my $key (keys(%$storehash)) {
4077: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4078: }
1.715 albertel 4079: $items=~s/\&$//;
1.716 albertel 4080: my $esc_symb=&escape($symb);
4081: my $esc_v=&escape($version);
1.715 albertel 4082: my $reply =
1.716 albertel 4083: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4084: $uhome);
4085: if ($reply eq 'unknown_cmd') {
1.716 albertel 4086: # gfall back to way things use to be done
1.715 albertel 4087: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4088: $uname);
1.524 raeburn 4089: }
1.715 albertel 4090: return $reply;
4091: }
4092:
4093: sub old_putstore {
1.716 albertel 4094: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4095: if (!$udomain) { $udomain=$env{'user.domain'}; }
4096: if (!$uname) { $uname=$env{'user.name'}; }
4097: my $uhome=&homeserver($uname,$udomain);
4098: my %newstorehash;
1.800 albertel 4099: foreach my $item (keys(%$storehash)) {
4100: my $key = $version.':'.&escape($symb).':'.$item;
4101: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4102: }
4103: my $items='';
4104: my %allitems = ();
1.800 albertel 4105: foreach my $item (keys(%newstorehash)) {
4106: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4107: my $key = $1.':keys:'.$2;
4108: $allitems{$key} .= $3.':';
4109: }
1.800 albertel 4110: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4111: }
1.800 albertel 4112: foreach my $item (keys(%allitems)) {
4113: $allitems{$item} =~ s/\:$//;
4114: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4115: }
4116: $items=~s/\&$//;
4117: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4118: }
4119:
1.47 www 4120: # ------------------------------------------------------ critical put interface
4121:
4122: sub cput {
1.134 albertel 4123: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4124: if (!$udomain) { $udomain=$env{'user.domain'}; }
4125: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4126: my $uhome=&homeserver($uname,$udomain);
1.47 www 4127: my $items='';
1.800 albertel 4128: foreach my $item (keys(%$storehash)) {
4129: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4130: }
1.47 www 4131: $items=~s/\&$//;
1.134 albertel 4132: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4133: }
4134:
4135: # -------------------------------------------------------------- eget interface
4136:
4137: sub eget {
1.133 albertel 4138: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4139: my $items='';
1.800 albertel 4140: foreach my $item (@$storearr) {
4141: $items.=&escape($item).'&';
1.191 harris41 4142: }
1.12 www 4143: $items=~s/\&$//;
1.620 albertel 4144: if (!$udomain) { $udomain=$env{'user.domain'}; }
4145: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4146: my $uhome=&homeserver($uname,$udomain);
4147: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4148: my @pairs=split(/\&/,$rep);
4149: my %returnhash=();
1.42 www 4150: my $i=0;
1.800 albertel 4151: foreach my $item (@$storearr) {
4152: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4153: $i++;
1.191 harris41 4154: }
1.12 www 4155: return %returnhash;
4156: }
4157:
1.667 albertel 4158: # ------------------------------------------------------------ tmpput interface
4159: sub tmpput {
1.802 raeburn 4160: my ($storehash,$server,$context)=@_;
1.667 albertel 4161: my $items='';
1.800 albertel 4162: foreach my $item (keys(%$storehash)) {
4163: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4164: }
4165: $items=~s/\&$//;
1.802 raeburn 4166: if (defined($context)) {
4167: $items .= ':'.&escape($context);
4168: }
1.667 albertel 4169: return &reply("tmpput:$items",$server);
4170: }
4171:
4172: # ------------------------------------------------------------ tmpget interface
4173: sub tmpget {
1.688 albertel 4174: my ($token,$server)=@_;
4175: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4176: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4177: my %returnhash;
4178: foreach my $item (split(/\&/,$rep)) {
4179: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4180: next if ($key =~ /^error: 2 /);
1.667 albertel 4181: $returnhash{&unescape($key)}=&thaw_unescape($value);
4182: }
4183: return %returnhash;
4184: }
4185:
1.688 albertel 4186: # ------------------------------------------------------------ tmpget interface
4187: sub tmpdel {
4188: my ($token,$server)=@_;
4189: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4190: return &reply("tmpdel:$token",$server);
4191: }
4192:
1.765 albertel 4193: # -------------------------------------------------- portfolio access checking
4194:
4195: sub portfolio_access {
1.766 albertel 4196: my ($requrl) = @_;
1.765 albertel 4197: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4198: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4199: if ($result) {
4200: my %setters;
4201: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4202: my ($startblock,$endblock) =
4203: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4204: if ($startblock && $endblock) {
4205: return 'B';
4206: }
4207: } else {
4208: my ($startblock,$endblock) =
4209: &Apache::loncommon::blockcheck(\%setters,'port');
4210: if ($startblock && $endblock) {
4211: return 'B';
4212: }
4213: }
4214: }
1.765 albertel 4215: if ($result eq 'ok') {
1.766 albertel 4216: return 'F';
1.765 albertel 4217: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4218: return 'A';
1.765 albertel 4219: }
1.766 albertel 4220: return '';
1.765 albertel 4221: }
4222:
4223: sub get_portfolio_access {
1.767 albertel 4224: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4225:
4226: if (!ref($access_hash)) {
4227: my $current_perms = &get_portfile_permissions($udom,$unum);
4228: my %access_controls = &get_access_controls($current_perms,$group,
4229: $file_name);
4230: $access_hash = $access_controls{$file_name};
4231: }
4232:
1.765 albertel 4233: my ($public,$guest,@domains,@users,@courses,@groups);
4234: my $now = time;
4235: if (ref($access_hash) eq 'HASH') {
4236: foreach my $key (keys(%{$access_hash})) {
4237: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4238: if ($start > $now) {
4239: next;
4240: }
4241: if ($end && $end<$now) {
4242: next;
4243: }
4244: if ($scope eq 'public') {
4245: $public = $key;
4246: last;
4247: } elsif ($scope eq 'guest') {
4248: $guest = $key;
4249: } elsif ($scope eq 'domains') {
4250: push(@domains,$key);
4251: } elsif ($scope eq 'users') {
4252: push(@users,$key);
4253: } elsif ($scope eq 'course') {
4254: push(@courses,$key);
4255: } elsif ($scope eq 'group') {
4256: push(@groups,$key);
4257: }
4258: }
4259: if ($public) {
4260: return 'ok';
4261: }
4262: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4263: if ($guest) {
4264: return $guest;
4265: }
4266: } else {
4267: if (@domains > 0) {
4268: foreach my $domkey (@domains) {
4269: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4270: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4271: return 'ok';
4272: }
4273: }
4274: }
4275: }
4276: if (@users > 0) {
4277: foreach my $userkey (@users) {
1.865 raeburn 4278: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4279: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4280: if (ref($item) eq 'HASH') {
4281: if (($item->{'uname'} eq $env{'user.name'}) &&
4282: ($item->{'udom'} eq $env{'user.domain'})) {
4283: return 'ok';
4284: }
4285: }
4286: }
4287: }
1.765 albertel 4288: }
4289: }
4290: my %roleshash;
4291: my @courses_and_groups = @courses;
4292: push(@courses_and_groups,@groups);
4293: if (@courses_and_groups > 0) {
4294: my (%allgroups,%allroles);
4295: my ($start,$end,$role,$sec,$group);
4296: foreach my $envkey (%env) {
1.811 albertel 4297: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4298: my $cid = $2.'_'.$3;
4299: if ($1 eq 'gr') {
4300: $group = $4;
4301: $allgroups{$cid}{$group} = $env{$envkey};
4302: } else {
4303: if ($4 eq '') {
4304: $sec = 'none';
4305: } else {
4306: $sec = $4;
4307: }
4308: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4309: }
1.811 albertel 4310: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4311: my $cid = $2.'_'.$3;
4312: if ($4 eq '') {
4313: $sec = 'none';
4314: } else {
4315: $sec = $4;
4316: }
4317: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4318: }
4319: }
4320: if (keys(%allroles) == 0) {
4321: return;
4322: }
4323: foreach my $key (@courses_and_groups) {
4324: my %content = %{$$access_hash{$key}};
4325: my $cnum = $content{'number'};
4326: my $cdom = $content{'domain'};
4327: my $cid = $cdom.'_'.$cnum;
4328: if (!exists($allroles{$cid})) {
4329: next;
4330: }
4331: foreach my $role_id (keys(%{$content{'roles'}})) {
4332: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4333: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4334: my @status = @{$content{'roles'}{$role_id}{'access'}};
4335: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4336: foreach my $role (keys(%{$allroles{$cid}})) {
4337: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4338: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4339: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4340: if (grep/^all$/,@sections) {
4341: return 'ok';
4342: } else {
4343: if (grep/^$sec$/,@sections) {
4344: return 'ok';
4345: }
4346: }
4347: }
4348: }
4349: if (keys(%{$allgroups{$cid}}) == 0) {
4350: if (grep/^none$/,@groups) {
4351: return 'ok';
4352: }
4353: } else {
4354: if (grep/^all$/,@groups) {
4355: return 'ok';
4356: }
4357: foreach my $group (keys(%{$allgroups{$cid}})) {
4358: if (grep/^$group$/,@groups) {
4359: return 'ok';
4360: }
4361: }
4362: }
4363: }
4364: }
4365: }
4366: }
4367: }
4368: if ($guest) {
4369: return $guest;
4370: }
4371: }
4372: }
4373: return;
4374: }
4375:
4376: sub course_group_datechecker {
4377: my ($dates,$now,$status) = @_;
4378: my ($start,$end) = split(/\./,$dates);
4379: if (!$start && !$end) {
4380: return 'ok';
4381: }
4382: if (grep/^active$/,@{$status}) {
4383: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4384: return 'ok';
4385: }
4386: }
4387: if (grep/^previous$/,@{$status}) {
4388: if ($end > $now ) {
4389: return 'ok';
4390: }
4391: }
4392: if (grep/^future$/,@{$status}) {
4393: if ($start > $now) {
4394: return 'ok';
4395: }
4396: }
4397: return;
4398: }
4399:
4400: sub parse_portfolio_url {
4401: my ($url) = @_;
4402:
4403: my ($type,$udom,$unum,$group,$file_name);
4404:
1.823 albertel 4405: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4406: $type = 1;
4407: $udom = $1;
4408: $unum = $2;
4409: $file_name = $3;
1.823 albertel 4410: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4411: $type = 2;
4412: $udom = $1;
4413: $unum = $2;
4414: $group = $3;
4415: $file_name = $3.'/'.$4;
4416: }
4417: if (wantarray) {
4418: return ($type,$udom,$unum,$file_name,$group);
4419: }
4420: return $type;
4421: }
4422:
4423: sub is_portfolio_url {
4424: my ($url) = @_;
4425: return scalar(&parse_portfolio_url($url));
4426: }
4427:
1.798 raeburn 4428: sub is_portfolio_file {
4429: my ($file) = @_;
1.820 raeburn 4430: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4431: return 1;
4432: }
4433: return;
4434: }
4435:
1.976 raeburn 4436: sub usertools_access {
1.985 raeburn 4437: my ($uname,$udom,$tool,$action,$context) = @_;
4438: my ($access,%tools);
4439: if ($context eq '') {
4440: $context = 'tools';
4441: }
4442: if ($context eq 'requestcourses') {
4443: %tools = (
4444: official => 1,
4445: unofficial => 1,
4446: );
4447: } else {
4448: %tools = (
4449: aboutme => 1,
4450: blog => 1,
4451: portfolio => 1,
4452: );
4453: }
1.976 raeburn 4454: return if (!defined($tools{$tool}));
4455:
4456: if ((!defined($udom)) || (!defined($uname))) {
4457: $udom = $env{'user.domain'};
4458: $uname = $env{'user.name'};
4459: }
4460:
1.978 raeburn 4461: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4462: if ($action ne 'reload') {
1.985 raeburn 4463: if ($context eq 'requestcourses') {
4464: return $env{'environment.canrequest.'.$tool};
4465: } else {
4466: return $env{'environment.availabletools.'.$tool};
4467: }
4468: }
1.976 raeburn 4469: }
4470:
4471: my ($toolstatus,$inststatus);
4472:
1.985 raeburn 4473: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4474: ($action ne 'reload')) {
4475: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4476: $inststatus = $env{'environment.inststatus'};
4477: } else {
1.985 raeburn 4478: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
4479: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4480: $inststatus = $userenv{'inststatus'};
4481: }
4482:
4483: if ($toolstatus ne '') {
4484: if ($toolstatus) {
4485: $access = 1;
4486: } else {
4487: $access = 0;
4488: }
4489: return $access;
4490: }
4491:
4492: my $is_adv = &is_advanced_user($udom,$uname);
4493: my %domdef = &get_domain_defaults($udom);
4494: if (ref($domdef{$tool}) eq 'HASH') {
4495: if ($is_adv) {
4496: if ($domdef{$tool}{'_LC_adv'} ne '') {
4497: if ($domdef{$tool}{'_LC_adv'}) {
4498: $access = 1;
4499: } else {
4500: $access = 0;
4501: }
4502: return $access;
4503: }
4504: }
4505: if ($inststatus ne '') {
4506: my ($hasaccess,$hasnoaccess);
4507: foreach my $affiliation (split(/:/,$inststatus)) {
4508: if ($domdef{$tool}{$affiliation} ne '') {
4509: if ($domdef{$tool}{$affiliation}) {
4510: $hasaccess = 1;
4511: } else {
4512: $hasnoaccess = 1;
4513: }
4514: }
4515: }
4516: if ($hasaccess || $hasnoaccess) {
4517: if ($hasaccess) {
4518: $access = 1;
4519: } elsif ($hasnoaccess) {
4520: $access = 0;
4521: }
4522: return $access;
4523: }
4524: } else {
4525: if ($domdef{$tool}{'default'} ne '') {
4526: if ($domdef{$tool}{'default'}) {
4527: $access = 1;
4528: } elsif ($domdef{$tool}{'default'} == 0) {
4529: $access = 0;
4530: }
4531: return $access;
4532: }
4533: }
4534: } else {
1.985 raeburn 4535: if ($context eq 'tools') {
4536: $access = 1;
4537: } else {
4538: $access = 0;
4539: }
1.976 raeburn 4540: return $access;
4541: }
4542: }
4543:
4544: sub is_advanced_user {
4545: my ($udom,$uname) = @_;
4546: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4547: my %allroles;
4548: my $is_adv;
4549: foreach my $role (keys(%roleshash)) {
4550: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4551: my $area = '/'.$tdomain.'/'.$trest;
4552: if ($sec ne '') {
4553: $area .= '/'.$sec;
4554: }
4555: if (($area ne '') && ($trole ne '')) {
4556: my $spec=$trole.'.'.$area;
4557: if ($trole =~ /^cr\//) {
4558: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4559: } elsif ($trole ne 'gr') {
4560: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4561: }
4562: }
4563: }
4564: foreach my $role (keys(%allroles)) {
4565: last if ($is_adv);
4566: foreach my $item (split(/:/,$allroles{$role})) {
4567: if ($item ne '') {
4568: my ($privilege,$restrictions)=split(/&/,$item);
4569: if ($privilege eq 'adv') {
4570: $is_adv = 1;
4571: last;
4572: }
4573: }
4574: }
4575: }
4576: return $is_adv;
4577: }
1.798 raeburn 4578:
1.341 www 4579: # ---------------------------------------------- Custom access rule evaluation
4580:
4581: sub customaccess {
4582: my ($priv,$uri)=@_;
1.807 albertel 4583: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4584: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4585: $udom = &LONCAPA::clean_domain($udom);
4586: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4587: my $access=0;
1.800 albertel 4588: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4589: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4590: if ($type eq 'user') {
4591: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4592: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4593: if ($tdom) {
4594: if ($tdom ne $env{'user.domain'}) { next; }
4595: }
1.896 albertel 4596: if ($tuname) {
4597: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4598: }
4599: $access=($effect eq 'allow');
4600: last;
4601: }
4602: } else {
4603: if ($role) {
4604: if ($role ne $urole) { next; }
4605: }
4606: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4607: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4608: if ($tdom) {
4609: if ($tdom ne $udom) { next; }
4610: }
4611: if ($tcrs) {
4612: if ($tcrs ne $ucrs) { next; }
4613: }
4614: if ($tsec) {
4615: if ($tsec ne $usec) { next; }
4616: }
4617: $access=($effect eq 'allow');
4618: last;
4619: }
4620: if ($realm eq '' && $role eq '') {
4621: $access=($effect eq 'allow');
4622: }
1.402 bowersj2 4623: }
1.341 www 4624: }
4625: return $access;
4626: }
4627:
1.103 harris41 4628: # ------------------------------------------------- Check for a user privilege
1.12 www 4629:
4630: sub allowed {
1.810 raeburn 4631: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4632: my $ver_orguri=$uri;
1.439 www 4633: $uri=&deversion($uri);
1.152 www 4634: my $orguri=$uri;
1.52 www 4635: $uri=&declutter($uri);
1.809 raeburn 4636:
1.810 raeburn 4637: if ($priv eq 'evb') {
4638: # Evade communication block restrictions for specified role in a course
4639: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4640: return $1;
4641: } else {
4642: return;
4643: }
4644: }
4645:
1.620 albertel 4646: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4647: # Free bre access to adm and meta resources
1.775 albertel 4648: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4649: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4650: && ($priv eq 'bre')) {
1.14 www 4651: return 'F';
1.159 www 4652: }
4653:
1.545 banghart 4654: # Free bre access to user's own portfolio contents
1.714 raeburn 4655: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4656: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4657: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4658: my %setters;
4659: my ($startblock,$endblock) =
4660: &Apache::loncommon::blockcheck(\%setters,'port');
4661: if ($startblock && $endblock) {
4662: return 'B';
4663: } else {
4664: return 'F';
4665: }
1.545 banghart 4666: }
4667:
1.762 raeburn 4668: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4669: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4670: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4671: if (exists($env{'request.course.id'})) {
4672: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4673: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4674: if (($domain eq $cdom) && ($name eq $cnum)) {
4675: my $courseprivid=$env{'request.course.id'};
4676: $courseprivid=~s/\_/\//;
4677: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4678: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4679: return $1;
1.762 raeburn 4680: } else {
4681: if ($env{'request.course.sec'}) {
4682: $courseprivid.='/'.$env{'request.course.sec'};
4683: }
4684: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4685: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4686: return $2;
4687: }
1.714 raeburn 4688: }
4689: }
4690: }
4691: }
4692:
1.159 www 4693: # Free bre to public access
4694:
4695: if ($priv eq 'bre') {
1.238 www 4696: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4697: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4698: return 'F';
4699: }
1.238 www 4700: if ($copyright eq 'priv') {
4701: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4702: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4703: return '';
4704: }
4705: }
4706: if ($copyright eq 'domain') {
4707: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4708: unless (($env{'user.domain'} eq $1) ||
4709: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4710: return '';
4711: }
1.262 matthew 4712: }
1.620 albertel 4713: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4714: # Library role, so allow browsing of resources in this domain.
4715: return 'F';
1.238 www 4716: }
1.341 www 4717: if ($copyright eq 'custom') {
4718: unless (&customaccess($priv,$uri)) { return ''; }
4719: }
1.14 www 4720: }
1.264 matthew 4721: # Domain coordinator is trying to create a course
1.620 albertel 4722: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4723: # uri is the requested domain in this case.
4724: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4725: # a role of dc for the domain in question.
1.620 albertel 4726: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4727: }
1.29 www 4728:
1.52 www 4729: my $thisallowed='';
4730: my $statecond=0;
4731: my $courseprivid='';
4732:
4733: # Course
4734:
1.620 albertel 4735: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4736: $thisallowed.=$1;
4737: }
1.29 www 4738:
1.52 www 4739: # Domain
4740:
1.620 albertel 4741: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4742: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4743: $thisallowed.=$1;
4744: }
1.52 www 4745:
4746: # Course: uri itself is a course
1.66 www 4747: my $courseuri=$uri;
4748: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4749: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4750:
1.620 albertel 4751: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4752: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4753: $thisallowed.=$1;
4754: }
1.29 www 4755:
1.665 albertel 4756: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4757: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4758: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4759: $thisallowed='';
1.671 raeburn 4760: my ($match)=&is_on_map($uri);
4761: if ($match) {
4762: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4763: =~/\Q$priv\E\&([^\:]*)/) {
4764: $thisallowed.=$1;
4765: }
4766: } else {
1.705 albertel 4767: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4768: if ($refuri) {
4769: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4770: $thisallowed='F';
1.671 raeburn 4771: } else {
4772: $refuri=&declutter($refuri);
4773: my ($match) = &is_on_map($refuri);
4774: if ($match) {
4775: $thisallowed='F';
4776: }
1.669 raeburn 4777: }
1.671 raeburn 4778: }
4779: }
1.314 www 4780: }
1.492 albertel 4781:
1.766 albertel 4782: if ($priv eq 'bre'
4783: && $thisallowed ne 'F'
4784: && $thisallowed ne '2'
4785: && &is_portfolio_url($uri)) {
4786: $thisallowed = &portfolio_access($uri);
4787: }
4788:
1.52 www 4789: # Full access at system, domain or course-wide level? Exit.
1.29 www 4790: if ($thisallowed=~/F/) {
4791: return 'F';
4792: }
4793:
1.52 www 4794: # If this is generating or modifying users, exit with special codes
1.29 www 4795:
1.643 www 4796: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4797: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4798: my ($audom,$auname)=split('/',$uri);
1.643 www 4799: # no author name given, so this just checks on the general right to make a co-author in this domain
4800: unless ($auname) { return $thisallowed; }
4801: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4802: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4803: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4804: ($audom ne $env{'request.role.domain'}))) { return ''; }
4805: }
1.52 www 4806: return $thisallowed;
4807: }
4808: #
1.103 harris41 4809: # Gathered so far: system, domain and course wide privileges
1.52 www 4810: #
4811: # Course: See if uri or referer is an individual resource that is part of
4812: # the course
4813:
1.620 albertel 4814: if ($env{'request.course.id'}) {
1.232 www 4815:
1.620 albertel 4816: $courseprivid=$env{'request.course.id'};
4817: if ($env{'request.course.sec'}) {
4818: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4819: }
4820: $courseprivid=~s/\_/\//;
4821: my $checkreferer=1;
1.232 www 4822: my ($match,$cond)=&is_on_map($uri);
4823: if ($match) {
4824: $statecond=$cond;
1.620 albertel 4825: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4826: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4827: $thisallowed.=$1;
4828: $checkreferer=0;
4829: }
1.29 www 4830: }
1.83 www 4831:
1.148 www 4832: if ($checkreferer) {
1.620 albertel 4833: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4834: unless ($refuri) {
1.800 albertel 4835: foreach my $key (keys(%env)) {
4836: if ($key=~/^httpref\..*\*/) {
4837: my $pattern=$key;
1.156 www 4838: $pattern=~s/^httpref\.\/res\///;
1.148 www 4839: $pattern=~s/\*/\[\^\/\]\+/g;
4840: $pattern=~s/\//\\\//g;
1.152 www 4841: if ($orguri=~/$pattern/) {
1.800 albertel 4842: $refuri=$env{$key};
1.148 www 4843: }
4844: }
1.191 harris41 4845: }
1.148 www 4846: }
1.232 www 4847:
1.148 www 4848: if ($refuri) {
1.152 www 4849: $refuri=&declutter($refuri);
1.232 www 4850: my ($match,$cond)=&is_on_map($refuri);
4851: if ($match) {
4852: my $refstatecond=$cond;
1.620 albertel 4853: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4854: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4855: $thisallowed.=$1;
1.53 www 4856: $uri=$refuri;
4857: $statecond=$refstatecond;
1.52 www 4858: }
4859: }
1.148 www 4860: }
1.29 www 4861: }
1.52 www 4862: }
1.29 www 4863:
1.52 www 4864: #
1.103 harris41 4865: # Gathered now: all privileges that could apply, and condition number
1.52 www 4866: #
4867: #
4868: # Full or no access?
4869: #
1.29 www 4870:
1.52 www 4871: if ($thisallowed=~/F/) {
4872: return 'F';
4873: }
1.29 www 4874:
1.52 www 4875: unless ($thisallowed) {
4876: return '';
4877: }
1.29 www 4878:
1.52 www 4879: # Restrictions exist, deal with them
4880: #
4881: # C:according to course preferences
4882: # R:according to resource settings
4883: # L:unless locked
4884: # X:according to user session state
4885: #
4886:
4887: # Possibly locked functionality, check all courses
1.54 www 4888: # Locks might take effect only after 10 minutes cache expiration for other
4889: # courses, and 2 minutes for current course
1.52 www 4890:
4891: my $envkey;
4892: if ($thisallowed=~/L/) {
1.620 albertel 4893: foreach $envkey (keys %env) {
1.54 www 4894: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4895: my $courseid=$2;
4896: my $roleid=$1.'.'.$2;
1.92 www 4897: $courseid=~s/^\///;
1.54 www 4898: my $expiretime=600;
1.620 albertel 4899: if ($env{'request.role'} eq $roleid) {
1.54 www 4900: $expiretime=120;
4901: }
4902: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4903: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4904: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4905: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4906: }
1.620 albertel 4907: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4908: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4909: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4910: &log($env{'user.domain'},$env{'user.name'},
4911: $env{'user.home'},
1.57 www 4912: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4913: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4914: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4915: return '';
4916: }
4917: }
1.620 albertel 4918: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4919: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4920: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4921: &log($env{'user.domain'},$env{'user.name'},
4922: $env{'user.home'},
1.57 www 4923: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4924: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4925: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4926: return '';
4927: }
4928: }
4929: }
1.29 www 4930: }
1.52 www 4931: }
4932:
4933: #
4934: # Rest of the restrictions depend on selected course
4935: #
4936:
1.620 albertel 4937: unless ($env{'request.course.id'}) {
1.766 albertel 4938: if ($thisallowed eq 'A') {
4939: return 'A';
1.814 raeburn 4940: } elsif ($thisallowed eq 'B') {
4941: return 'B';
1.766 albertel 4942: } else {
4943: return '1';
4944: }
1.52 www 4945: }
1.29 www 4946:
1.52 www 4947: #
4948: # Now user is definitely in a course
4949: #
1.53 www 4950:
4951:
4952: # Course preferences
4953:
4954: if ($thisallowed=~/C/) {
1.620 albertel 4955: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4956: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4957: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4958: =~/\Q$rolecode\E/) {
1.689 albertel 4959: if ($priv ne 'pch') {
4960: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4961: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4962: $env{'request.course.id'});
4963: }
1.237 www 4964: return '';
4965: }
4966:
1.620 albertel 4967: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4968: =~/\Q$unamedom\E/) {
1.689 albertel 4969: if ($priv ne 'pch') {
4970: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4971: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4972: $env{'request.course.id'});
4973: }
1.54 www 4974: return '';
4975: }
1.53 www 4976: }
4977:
4978: # Resource preferences
4979:
4980: if ($thisallowed=~/R/) {
1.620 albertel 4981: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4982: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4983: if ($priv ne 'pch') {
4984: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4985: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4986: }
4987: return '';
1.54 www 4988: }
1.53 www 4989: }
1.30 www 4990:
1.246 www 4991: # Restricted by state or randomout?
1.30 www 4992:
1.52 www 4993: if ($thisallowed=~/X/) {
1.620 albertel 4994: if ($env{'acc.randomout'}) {
1.579 albertel 4995: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4996: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4997: return '';
4998: }
1.247 www 4999: }
5000: if (&condval($statecond)) {
1.52 www 5001: return '2';
5002: } else {
5003: return '';
5004: }
5005: }
1.30 www 5006:
1.766 albertel 5007: if ($thisallowed eq 'A') {
5008: return 'A';
1.814 raeburn 5009: } elsif ($thisallowed eq 'B') {
5010: return 'B';
1.766 albertel 5011: }
1.52 www 5012: return 'F';
1.232 www 5013: }
5014:
1.710 albertel 5015: sub split_uri_for_cond {
5016: my $uri=&deversion(&declutter(shift));
5017: my @uriparts=split(/\//,$uri);
5018: my $filename=pop(@uriparts);
5019: my $pathname=join('/',@uriparts);
5020: return ($pathname,$filename);
5021: }
1.232 www 5022: # --------------------------------------------------- Is a resource on the map?
5023:
5024: sub is_on_map {
1.710 albertel 5025: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5026: #Trying to find the conditional for the file
1.620 albertel 5027: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5028: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5029: if ($match) {
1.289 bowersj2 5030: return (1,$1);
5031: } else {
1.434 www 5032: return (0,0);
1.289 bowersj2 5033: }
1.12 www 5034: }
5035:
1.427 www 5036: # --------------------------------------------------------- Get symb from alias
5037:
5038: sub get_symb_from_alias {
5039: my $symb=shift;
5040: my ($map,$resid,$url)=&decode_symb($symb);
5041: # Already is a symb
5042: if ($url) { return $symb; }
5043: # Must be an alias
5044: my $aliassymb='';
5045: my %bighash;
1.620 albertel 5046: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5047: &GDBM_READER(),0640)) {
5048: my $rid=$bighash{'mapalias_'.$symb};
5049: if ($rid) {
5050: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5051: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5052: $resid,$bighash{'src_'.$rid});
1.427 www 5053: }
5054: untie %bighash;
5055: }
5056: return $aliassymb;
5057: }
5058:
1.12 www 5059: # ----------------------------------------------------------------- Define Role
5060:
5061: sub definerole {
5062: if (allowed('mcr','/')) {
5063: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5064: foreach my $role (split(':',$sysrole)) {
5065: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5066: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5067: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5068: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5069: return "refused:s:$crole&$cqual";
5070: }
5071: }
1.191 harris41 5072: }
1.800 albertel 5073: foreach my $role (split(':',$domrole)) {
5074: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5075: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5076: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5077: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5078: return "refused:d:$crole&$cqual";
5079: }
5080: }
1.191 harris41 5081: }
1.800 albertel 5082: foreach my $role (split(':',$courole)) {
5083: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5084: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5085: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5086: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5087: return "refused:c:$crole&$cqual";
5088: }
5089: }
1.191 harris41 5090: }
1.620 albertel 5091: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5092: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5093: "rolesdef_$rolename=".
5094: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5095: return reply($command,$env{'user.home'});
1.12 www 5096: } else {
5097: return 'refused';
5098: }
1.105 harris41 5099: }
5100:
5101: # ---------------- Make a metadata query against the network of library servers
5102:
5103: sub metadata_query {
1.244 matthew 5104: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5105: my %rhash;
1.845 albertel 5106: my %libserv = &all_library();
1.244 matthew 5107: my @server_list = (defined($server_array) ? @$server_array
5108: : keys(%libserv) );
5109: for my $server (@server_list) {
1.118 harris41 5110: unless ($custom or $customshow) {
5111: my $reply=&reply("querysend:".&escape($query),$server);
5112: $rhash{$server}=$reply;
5113: }
5114: else {
5115: my $reply=&reply("querysend:".&escape($query).':'.
5116: &escape($custom).':'.&escape($customshow),
5117: $server);
5118: $rhash{$server}=$reply;
5119: }
1.112 harris41 5120: }
1.118 harris41 5121: return \%rhash;
1.240 www 5122: }
5123:
5124: # ----------------------------------------- Send log queries and wait for reply
5125:
5126: sub log_query {
5127: my ($uname,$udom,$query,%filters)=@_;
5128: my $uhome=&homeserver($uname,$udom);
5129: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5130: my $uhost=&hostname($uhome);
1.800 albertel 5131: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5132: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5133: $uhome);
1.479 albertel 5134: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5135: return get_query_reply($queryid);
5136: }
5137:
1.818 raeburn 5138: # -------------------------- Update MySQL table for portfolio file
5139:
5140: sub update_portfolio_table {
1.821 raeburn 5141: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5142: if ($group ne '') {
5143: $file_name =~s /^\Q$group\E//;
5144: }
1.818 raeburn 5145: my $homeserver = &homeserver($uname,$udom);
5146: my $queryid=
1.821 raeburn 5147: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5148: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5149: my $reply = &get_query_reply($queryid);
5150: return $reply;
5151: }
5152:
1.899 raeburn 5153: # -------------------------- Update MySQL allusers table
5154:
5155: sub update_allusers_table {
5156: my ($uname,$udom,$names) = @_;
5157: my $homeserver = &homeserver($uname,$udom);
5158: my $queryid=
5159: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5160: 'lastname='.&escape($names->{'lastname'}).'%%'.
5161: 'firstname='.&escape($names->{'firstname'}).'%%'.
5162: 'middlename='.&escape($names->{'middlename'}).'%%'.
5163: 'generation='.&escape($names->{'generation'}).'%%'.
5164: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5165: 'id='.&escape($names->{'id'}),$homeserver);
5166: my $reply = &get_query_reply($queryid);
5167: return $reply;
5168: }
5169:
1.508 raeburn 5170: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5171:
5172: sub fetch_enrollment_query {
1.511 raeburn 5173: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5174: my $homeserver;
1.547 raeburn 5175: my $maxtries = 1;
1.508 raeburn 5176: if ($context eq 'automated') {
5177: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5178: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5179: } else {
5180: $homeserver = &homeserver($cnum,$dom);
5181: }
1.838 albertel 5182: my $host=&hostname($homeserver);
1.506 raeburn 5183: my $cmd = '';
1.800 albertel 5184: foreach my $affiliate (keys %{$affiliatesref}) {
5185: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5186: }
5187: $cmd =~ s/%%$//;
5188: $cmd = &escape($cmd);
5189: my $query = 'fetchenrollment';
1.620 albertel 5190: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5191: unless ($queryid=~/^\Q$host\E\_/) {
5192: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5193: return 'error: '.$queryid;
5194: }
1.506 raeburn 5195: my $reply = &get_query_reply($queryid);
1.547 raeburn 5196: my $tries = 1;
5197: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5198: $reply = &get_query_reply($queryid);
5199: $tries ++;
5200: }
1.526 raeburn 5201: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5202: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5203: } else {
1.901 albertel 5204: my @responses = split(/:/,$reply);
1.515 raeburn 5205: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5206: foreach my $line (@responses) {
5207: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5208: $$replyref{$key} = $value;
5209: }
5210: } else {
1.506 raeburn 5211: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5212: foreach my $line (@responses) {
5213: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5214: $$replyref{$key} = $value;
5215: if ($value > 0) {
1.800 albertel 5216: foreach my $item (@{$$affiliatesref{$key}}) {
5217: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5218: my $destname = $pathname.'/'.$filename;
5219: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5220: if ($xml_classlist =~ /^error/) {
5221: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5222: } else {
1.506 raeburn 5223: if ( open(FILE,">$destname") ) {
5224: print FILE &unescape($xml_classlist);
5225: close(FILE);
1.526 raeburn 5226: } else {
5227: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5228: }
5229: }
5230: }
5231: }
5232: }
5233: }
5234: return 'ok';
5235: }
5236: return 'error';
5237: }
5238:
1.242 www 5239: sub get_query_reply {
5240: my $queryid=shift;
1.240 www 5241: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5242: my $reply='';
5243: for (1..100) {
5244: sleep 2;
5245: if (-e $replyfile.'.end') {
1.448 albertel 5246: if (open(my $fh,$replyfile)) {
1.904 albertel 5247: $reply = join('',<$fh>);
5248: close($fh);
1.240 www 5249: } else { return 'error: reply_file_error'; }
1.242 www 5250: return &unescape($reply);
5251: }
1.240 www 5252: }
1.242 www 5253: return 'timeout:'.$queryid;
1.240 www 5254: }
5255:
5256: sub courselog_query {
1.241 www 5257: #
5258: # possible filters:
5259: # url: url or symb
5260: # username
5261: # domain
5262: # action: view, submit, grade
5263: # start: timestamp
5264: # end: timestamp
5265: #
1.240 www 5266: my (%filters)=@_;
1.620 albertel 5267: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5268: if ($filters{'url'}) {
5269: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5270: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5271: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5272: }
1.620 albertel 5273: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5274: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5275: return &log_query($cname,$cdom,'courselog',%filters);
5276: }
5277:
5278: sub userlog_query {
1.858 raeburn 5279: #
5280: # possible filters:
5281: # action: log check role
5282: # start: timestamp
5283: # end: timestamp
5284: #
1.240 www 5285: my ($uname,$udom,%filters)=@_;
5286: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5287: }
5288:
1.506 raeburn 5289: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5290:
5291: sub auto_run {
1.508 raeburn 5292: my ($cnum,$cdom) = @_;
1.876 raeburn 5293: my $response = 0;
5294: my $settings;
5295: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5296: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5297: $settings = $domconfig{'autoenroll'};
5298: if ($settings->{'run'} eq '1') {
5299: $response = 1;
5300: }
5301: } else {
1.934 raeburn 5302: my $homeserver;
5303: if (&is_course($cdom,$cnum)) {
5304: $homeserver = &homeserver($cnum,$cdom);
5305: } else {
5306: $homeserver = &domain($cdom,'primary');
5307: }
5308: if ($homeserver ne 'no_host') {
5309: $response = &reply('autorun:'.$cdom,$homeserver);
5310: }
1.876 raeburn 5311: }
1.506 raeburn 5312: return $response;
5313: }
1.776 albertel 5314:
1.506 raeburn 5315: sub auto_get_sections {
1.508 raeburn 5316: my ($cnum,$cdom,$inst_coursecode) = @_;
5317: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5318: my @secs = ();
1.511 raeburn 5319: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5320: unless ($response eq 'refused') {
1.901 albertel 5321: @secs = split(/:/,$response);
1.506 raeburn 5322: }
5323: return @secs;
5324: }
1.776 albertel 5325:
1.506 raeburn 5326: sub auto_new_course {
1.508 raeburn 5327: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5328: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5329: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5330: return $response;
5331: }
1.776 albertel 5332:
1.506 raeburn 5333: sub auto_validate_courseID {
1.508 raeburn 5334: my ($cnum,$cdom,$inst_course_id) = @_;
5335: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5336: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5337: return $response;
5338: }
1.776 albertel 5339:
1.506 raeburn 5340: sub auto_create_password {
1.873 raeburn 5341: my ($cnum,$cdom,$authparam,$udom) = @_;
5342: my ($homeserver,$response);
1.506 raeburn 5343: my $create_passwd = 0;
5344: my $authchk = '';
1.873 raeburn 5345: if ($udom =~ /^$match_domain$/) {
5346: $homeserver = &domain($udom,'primary');
5347: }
5348: if ($homeserver eq '') {
5349: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5350: $homeserver = &homeserver($cnum,$cdom);
5351: }
5352: }
5353: if ($homeserver eq '') {
5354: $authchk = 'nodomain';
1.506 raeburn 5355: } else {
1.873 raeburn 5356: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5357: if ($response eq 'refused') {
5358: $authchk = 'refused';
5359: } else {
1.901 albertel 5360: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5361: }
1.506 raeburn 5362: }
5363: return ($authparam,$create_passwd,$authchk);
5364: }
5365:
1.706 raeburn 5366: sub auto_photo_permission {
5367: my ($cnum,$cdom,$students) = @_;
5368: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5369: my ($outcome,$perm_reqd,$conditions) =
5370: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5371: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5372: return (undef,undef);
5373: }
1.706 raeburn 5374: return ($outcome,$perm_reqd,$conditions);
5375: }
5376:
5377: sub auto_checkphotos {
5378: my ($uname,$udom,$pid) = @_;
5379: my $homeserver = &homeserver($uname,$udom);
5380: my ($result,$resulttype);
5381: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5382: &escape($uname).':'.&escape($pid),
5383: $homeserver));
1.709 albertel 5384: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5385: return (undef,undef);
5386: }
1.706 raeburn 5387: if ($outcome) {
5388: ($result,$resulttype) = split(/:/,$outcome);
5389: }
5390: return ($result,$resulttype);
5391: }
5392:
5393: sub auto_photochoice {
5394: my ($cnum,$cdom) = @_;
5395: my $homeserver = &homeserver($cnum,$cdom);
5396: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5397: &escape($cdom),
5398: $homeserver)));
1.709 albertel 5399: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5400: return (undef,undef);
5401: }
1.706 raeburn 5402: return ($update,$comment);
5403: }
5404:
5405: sub auto_photoupdate {
5406: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5407: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5408: my $host=&hostname($homeserver);
1.706 raeburn 5409: my $cmd = '';
5410: my $maxtries = 1;
1.800 albertel 5411: foreach my $affiliate (keys(%{$affiliatesref})) {
5412: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5413: }
5414: $cmd =~ s/%%$//;
5415: $cmd = &escape($cmd);
5416: my $query = 'institutionalphotos';
5417: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5418: unless ($queryid=~/^\Q$host\E\_/) {
5419: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5420: return 'error: '.$queryid;
5421: }
5422: my $reply = &get_query_reply($queryid);
5423: my $tries = 1;
5424: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5425: $reply = &get_query_reply($queryid);
5426: $tries ++;
5427: }
5428: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5429: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5430: } else {
5431: my @responses = split(/:/,$reply);
5432: my $outcome = shift(@responses);
5433: foreach my $item (@responses) {
5434: my ($key,$value) = split(/=/,$item);
5435: $$photo{$key} = $value;
5436: }
5437: return $outcome;
5438: }
5439: return 'error';
5440: }
5441:
1.521 raeburn 5442: sub auto_instcode_format {
1.793 albertel 5443: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5444: $cat_order) = @_;
1.521 raeburn 5445: my $courses = '';
1.772 raeburn 5446: my @homeservers;
1.521 raeburn 5447: if ($caller eq 'global') {
1.841 albertel 5448: my %servers = &get_servers($codedom,'library');
5449: foreach my $tryserver (keys(%servers)) {
5450: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5451: push(@homeservers,$tryserver);
5452: }
1.584 raeburn 5453: }
1.521 raeburn 5454: } else {
1.772 raeburn 5455: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5456: }
1.793 albertel 5457: foreach my $code (keys(%{$instcodes})) {
5458: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5459: }
5460: chop($courses);
1.772 raeburn 5461: my $ok_response = 0;
5462: my $response;
5463: while (@homeservers > 0 && $ok_response == 0) {
5464: my $server = shift(@homeservers);
5465: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5466: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5467: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5468: split(/:/,$response);
1.772 raeburn 5469: %{$codes} = (%{$codes},&str2hash($codes_str));
5470: push(@{$codetitles},&str2array($codetitles_str));
5471: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5472: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5473: $ok_response = 1;
5474: }
5475: }
5476: if ($ok_response) {
1.521 raeburn 5477: return 'ok';
1.772 raeburn 5478: } else {
5479: return $response;
1.521 raeburn 5480: }
5481: }
5482:
1.792 raeburn 5483: sub auto_instcode_defaults {
5484: my ($domain,$returnhash,$code_order) = @_;
5485: my @homeservers;
1.841 albertel 5486:
5487: my %servers = &get_servers($domain,'library');
5488: foreach my $tryserver (keys(%servers)) {
5489: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5490: push(@homeservers,$tryserver);
5491: }
1.792 raeburn 5492: }
1.841 albertel 5493:
1.792 raeburn 5494: my $response;
1.841 albertel 5495: foreach my $server (@homeservers) {
1.792 raeburn 5496: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5497: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5498:
5499: foreach my $pair (split(/\&/,$response)) {
5500: my ($name,$value)=split(/\=/,$pair);
5501: if ($name eq 'code_order') {
5502: @{$code_order} = split(/\&/,&unescape($value));
5503: } else {
5504: $returnhash->{&unescape($name)}=&unescape($value);
5505: }
5506: }
5507: return 'ok';
1.792 raeburn 5508: }
1.841 albertel 5509:
5510: return $response;
1.792 raeburn 5511: }
5512:
1.777 albertel 5513: sub auto_validate_class_sec {
1.918 raeburn 5514: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5515: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5516: my $ownerlist;
5517: if (ref($owners) eq 'ARRAY') {
5518: $ownerlist = join(',',@{$owners});
5519: } else {
5520: $ownerlist = $owners;
5521: }
1.773 raeburn 5522: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5523: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5524: return $response;
5525: }
5526:
1.679 raeburn 5527: # ------------------------------------------------------- Course Group routines
5528:
5529: sub get_coursegroups {
1.809 raeburn 5530: my ($cdom,$cnum,$group,$namespace) = @_;
5531: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5532: }
5533:
1.679 raeburn 5534: sub modify_coursegroup {
5535: my ($cdom,$cnum,$groupsettings) = @_;
5536: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5537: }
5538:
1.809 raeburn 5539: sub toggle_coursegroup_status {
5540: my ($cdom,$cnum,$group,$action) = @_;
5541: my ($from_namespace,$to_namespace);
5542: if ($action eq 'delete') {
5543: $from_namespace = 'coursegroups';
5544: $to_namespace = 'deleted_groups';
5545: } else {
5546: $from_namespace = 'deleted_groups';
5547: $to_namespace = 'coursegroups';
5548: }
5549: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5550: if (my $tmp = &error(%curr_group)) {
5551: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5552: return ('read error',$tmp);
5553: } else {
5554: my %savedsettings = %curr_group;
1.809 raeburn 5555: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5556: my $deloutcome;
5557: if ($result eq 'ok') {
1.809 raeburn 5558: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5559: } else {
5560: return ('write error',$result);
5561: }
5562: if ($deloutcome eq 'ok') {
5563: return 'ok';
5564: } else {
5565: return ('delete error',$deloutcome);
5566: }
5567: }
5568: }
5569:
1.679 raeburn 5570: sub modify_group_roles {
1.957 raeburn 5571: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5572: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5573: my $role = 'gr/'.&escape($userprivs);
5574: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5575: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5576: if ($result eq 'ok') {
5577: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5578: }
1.679 raeburn 5579: return $result;
5580: }
5581:
5582: sub modify_coursegroup_membership {
5583: my ($cdom,$cnum,$membership) = @_;
5584: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5585: return $result;
5586: }
5587:
1.682 raeburn 5588: sub get_active_groups {
5589: my ($udom,$uname,$cdom,$cnum) = @_;
5590: my $now = time;
5591: my %groups = ();
5592: foreach my $key (keys(%env)) {
1.811 albertel 5593: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5594: my ($start,$end) = split(/\./,$env{$key});
5595: if (($end!=0) && ($end<$now)) { next; }
5596: if (($start!=0) && ($start>$now)) { next; }
5597: if ($1 eq $cdom && $2 eq $cnum) {
5598: $groups{$3} = $env{$key} ;
5599: }
5600: }
5601: }
5602: return %groups;
5603: }
5604:
1.683 raeburn 5605: sub get_group_membership {
5606: my ($cdom,$cnum,$group) = @_;
5607: return(&dump('groupmembership',$cdom,$cnum,$group));
5608: }
5609:
5610: sub get_users_groups {
5611: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5612: my @usersgroups;
1.683 raeburn 5613: my $cachetime=1800;
5614:
5615: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5616: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5617: if (defined($cached)) {
1.734 albertel 5618: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5619: } else {
5620: $grouplist = '';
1.816 raeburn 5621: my $courseurl = &courseid_to_courseurl($courseid);
5622: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5623: my $access_end = $env{'course.'.$courseid.
5624: '.default_enrollment_end_date'};
5625: my $now = time;
5626: foreach my $key (keys(%roleshash)) {
5627: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5628: my $group = $1;
5629: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5630: my $start = $2;
5631: my $end = $1;
5632: if ($start == -1) { next; } # deleted from group
5633: if (($start!=0) && ($start>$now)) { next; }
5634: if (($end!=0) && ($end<$now)) {
5635: if ($access_end && $access_end < $now) {
5636: if ($access_end - $end < 86400) {
5637: push(@usersgroups,$group);
1.733 raeburn 5638: }
5639: }
1.817 raeburn 5640: next;
1.733 raeburn 5641: }
1.817 raeburn 5642: push(@usersgroups,$group);
1.683 raeburn 5643: }
5644: }
5645: }
1.817 raeburn 5646: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5647: $grouplist = join(':',@usersgroups);
5648: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5649: }
1.733 raeburn 5650: return @usersgroups;
1.683 raeburn 5651: }
5652:
5653: sub devalidate_getgroups_cache {
5654: my ($udom,$uname,$cdom,$cnum)=@_;
5655: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5656:
1.683 raeburn 5657: my $hashid="$udom:$uname:$courseid";
5658: &devalidate_cache_new('getgroups',$hashid);
5659: }
5660:
1.12 www 5661: # ------------------------------------------------------------------ Plain Text
5662:
5663: sub plaintext {
1.742 raeburn 5664: my ($short,$type,$cid) = @_;
1.758 albertel 5665: if ($short =~ /^cr/) {
5666: return (split('/',$short))[-1];
5667: }
1.742 raeburn 5668: if (!defined($cid)) {
5669: $cid = $env{'request.course.id'};
5670: }
5671: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5672: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5673: '.plaintext'});
5674: }
5675: my %rolenames = (
5676: Course => 'std',
5677: Group => 'alt1',
5678: );
5679: if (defined($type) &&
5680: defined($rolenames{$type}) &&
5681: defined($prp{$short}{$rolenames{$type}})) {
5682: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5683: } else {
5684: return &Apache::lonlocal::mt($prp{$short}{'std'});
5685: }
1.12 www 5686: }
5687:
5688: # ----------------------------------------------------------------- Assign Role
5689:
5690: sub assignrole {
1.957 raeburn 5691: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5692: $context)=@_;
1.21 www 5693: my $mrole;
5694: if ($role =~ /^cr\//) {
1.393 www 5695: my $cwosec=$url;
1.811 albertel 5696: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5697: unless (&allowed('ccr',$cwosec)) {
1.104 www 5698: &logthis('Refused custom assignrole: '.
5699: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5700: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5701: return 'refused';
5702: }
1.21 www 5703: $mrole='cr';
1.678 raeburn 5704: } elsif ($role =~ /^gr\//) {
5705: my $cwogrp=$url;
1.811 albertel 5706: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5707: unless (&allowed('mdg',$cwogrp)) {
5708: &logthis('Refused group assignrole: '.
5709: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5710: $env{'user.name'}.' at '.$env{'user.domain'});
5711: return 'refused';
5712: }
5713: $mrole='gr';
1.21 www 5714: } else {
1.82 www 5715: my $cwosec=$url;
1.811 albertel 5716: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5717: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5718: my $refused;
5719: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5720: if (!(&allowed('c'.$role,$url))) {
5721: $refused = 1;
5722: }
5723: } else {
5724: $refused = 1;
5725: }
1.947 raeburn 5726: if ($refused) {
5727: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5728: $refused = '';
5729: } else {
5730: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5731: ' '.$role.' '.$end.' '.$start.' by '.
5732: $env{'user.name'}.' at '.$env{'user.domain'});
5733: return 'refused';
5734: }
1.932 raeburn 5735: }
1.104 www 5736: }
1.21 www 5737: $mrole=$role;
5738: }
1.620 albertel 5739: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5740: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5741: if ($end) { $command.='_'.$end; }
1.21 www 5742: if ($start) {
5743: if ($end) {
1.81 www 5744: $command.='_'.$start;
1.21 www 5745: } else {
1.81 www 5746: $command.='_0_'.$start;
1.21 www 5747: }
5748: }
1.739 raeburn 5749: my $origstart = $start;
5750: my $origend = $end;
1.957 raeburn 5751: my $delflag;
1.357 www 5752: # actually delete
5753: if ($deleteflag) {
1.373 www 5754: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5755: # modify command to delete the role
1.620 albertel 5756: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5757: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5758: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5759: # set start and finish to negative values for userrolelog
5760: $start=-1;
5761: $end=-1;
1.957 raeburn 5762: $delflag = 1;
1.357 www 5763: }
5764: }
5765: # send command
1.349 www 5766: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5767: # log new user role if status is ok
1.349 www 5768: if ($answer eq 'ok') {
1.663 raeburn 5769: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5770: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5771: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5772: unless ($role =~ /^gr/) {
5773: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5774: $origstart,$selfenroll,$context);
1.739 raeburn 5775: }
1.349 www 5776: }
5777: return $answer;
1.169 harris41 5778: }
5779:
5780: # -------------------------------------------------- Modify user authentication
1.197 www 5781: # Overrides without validation
5782:
1.169 harris41 5783: sub modifyuserauth {
5784: my ($udom,$uname,$umode,$upass)=@_;
5785: my $uhome=&homeserver($uname,$udom);
1.197 www 5786: unless (&allowed('mau',$udom)) { return 'refused'; }
5787: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5788: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5789: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5790: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5791: &escape($upass),$uhome);
1.620 albertel 5792: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5793: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5794: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5795: &log($udom,,$uname,$uhome,
1.620 albertel 5796: 'Authentication changed by '.$env{'user.domain'}.', '.
5797: $env{'user.name'}.', '.$umode.
1.197 www 5798: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5799: unless ($reply eq 'ok') {
1.197 www 5800: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5801: return 'error: '.$reply;
5802: }
1.170 harris41 5803: return 'ok';
1.80 www 5804: }
5805:
1.81 www 5806: # --------------------------------------------------------------- Modify a user
1.80 www 5807:
1.81 www 5808: sub modifyuser {
1.206 matthew 5809: my ($udom, $uname, $uid,
5810: $umode, $upass, $first,
5811: $middle, $last, $gene,
1.963 raeburn 5812: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 5813: $udom= &LONCAPA::clean_domain($udom);
5814: $uname=&LONCAPA::clean_username($uname);
1.81 www 5815: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5816: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5817: $last.', '.$gene.'(forceid: '.$forceid.')'.
5818: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5819: ' desiredhome not specified').
1.620 albertel 5820: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5821: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5822: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5823: # ----------------------------------------------------------------- Create User
1.406 albertel 5824: if (($uhome eq 'no_host') &&
5825: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5826: my $unhome='';
1.844 albertel 5827: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5828: $unhome = $desiredhome;
1.620 albertel 5829: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5830: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5831: } else { # load balancing routine for determining $unhome
1.81 www 5832: my $loadm=10000000;
1.841 albertel 5833: my %servers = &get_servers($udom,'library');
5834: foreach my $tryserver (keys(%servers)) {
5835: my $answer=reply('load',$tryserver);
5836: if (($answer=~/\d+/) && ($answer<$loadm)) {
5837: $loadm=$answer;
5838: $unhome=$tryserver;
5839: }
1.80 www 5840: }
5841: }
5842: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5843: return 'error: unable to find a home server for '.$uname.
5844: ' in domain '.$udom;
1.80 www 5845: }
5846: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5847: &escape($upass),$unhome);
5848: unless ($reply eq 'ok') {
5849: return 'error: '.$reply;
5850: }
1.230 stredwic 5851: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5852: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5853: return 'error: unable verify users home machine.';
1.80 www 5854: }
1.209 matthew 5855: } # End of creation of new user
1.80 www 5856: # ---------------------------------------------------------------------- Add ID
5857: if ($uid) {
5858: $uid=~tr/A-Z/a-z/;
5859: my %uidhash=&idrget($udom,$uname);
1.196 www 5860: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5861: && (!$forceid)) {
1.80 www 5862: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5863: return 'error: user id "'.$uid.'" does not match '.
5864: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5865: }
5866: } else {
5867: &idput($udom,($uname => $uid));
5868: }
5869: }
5870: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5871: my @tmp=&get('environment',
1.899 raeburn 5872: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 5873: 'permanentemail','inststatus'],
1.134 albertel 5874: $udom,$uname);
1.313 matthew 5875: my %names;
5876: if ($tmp[0] =~ m/^error:.*/) {
5877: %names=();
5878: } else {
5879: %names = @tmp;
5880: }
1.388 www 5881: #
5882: # Make sure to not trash student environment if instructor does not bother
5883: # to supply name and email information
5884: #
5885: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5886: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5887: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5888: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5889: if ($email) {
5890: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 5891: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 5892: }
1.899 raeburn 5893: if ($uid) { $names{'id'} = $uid; }
1.963 raeburn 5894: if (defined($inststatus)) { $names{'inststatus'} = $inststatus; }
1.134 albertel 5895: my $reply = &put('environment', \%names, $udom,$uname);
5896: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5897: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5898: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 5899: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5900: $umode.', '.$first.', '.$middle.', '.
5901: $last.', '.$gene.', '.$email.', '.$inststatus;
5902: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
5903: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
5904: } else {
5905: $logmsg .= ' during self creation';
5906: }
5907: &logthis($logmsg);
1.134 albertel 5908: return 'ok';
1.80 www 5909: }
5910:
1.81 www 5911: # -------------------------------------------------------------- Modify student
1.80 www 5912:
1.81 www 5913: sub modifystudent {
5914: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 5915: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5916: $selfenroll,$context)=@_;
1.455 albertel 5917: if (!$cid) {
1.620 albertel 5918: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5919: return 'not_in_class';
5920: }
1.80 www 5921: }
5922: # --------------------------------------------------------------- Make the user
1.81 www 5923: my $reply=&modifyuser
1.209 matthew 5924: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5925: $desiredhome,$email);
1.80 www 5926: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5927: # This will cause &modify_student_enrollment to get the uid from the
5928: # students environment
5929: $uid = undef if (!$forceid);
1.455 albertel 5930: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 5931: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 5932: return $reply;
5933: }
5934:
5935: sub modify_student_enrollment {
1.957 raeburn 5936: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 5937: my ($cdom,$cnum,$chome);
5938: if (!$cid) {
1.620 albertel 5939: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5940: return 'not_in_class';
5941: }
1.620 albertel 5942: $cdom=$env{'course.'.$cid.'.domain'};
5943: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5944: } else {
5945: ($cdom,$cnum)=split(/_/,$cid);
5946: }
1.620 albertel 5947: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5948: if (!$chome) {
1.457 raeburn 5949: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5950: }
1.455 albertel 5951: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5952: # Make sure the user exists
1.81 www 5953: my $uhome=&homeserver($uname,$udom);
5954: if (($uhome eq '') || ($uhome eq 'no_host')) {
5955: return 'error: no such user';
5956: }
1.297 matthew 5957: # Get student data if we were not given enough information
5958: if (!defined($first) || $first eq '' ||
5959: !defined($last) || $last eq '' ||
5960: !defined($uid) || $uid eq '' ||
5961: !defined($middle) || $middle eq '' ||
5962: !defined($gene) || $gene eq '') {
1.294 matthew 5963: # They did not supply us with enough data to enroll the student, so
5964: # we need to pick up more information.
1.297 matthew 5965: my %tmp = &get('environment',
1.294 matthew 5966: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5967: ,$udom,$uname);
5968:
1.800 albertel 5969: #foreach my $key (keys(%tmp)) {
5970: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5971: #}
1.294 matthew 5972: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5973: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5974: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5975: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5976: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5977: }
1.556 albertel 5978: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5979: my $reply=cput('classlist',
5980: {"$uname:$udom" =>
1.515 raeburn 5981: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5982: $cdom,$cnum);
1.81 www 5983: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5984: return 'error: '.$reply;
1.652 albertel 5985: } else {
5986: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5987: }
1.297 matthew 5988: # Add student role to user
1.83 www 5989: my $uurl='/'.$cid;
1.81 www 5990: $uurl=~s/\_/\//g;
5991: if ($usec) {
5992: $uurl.='/'.$usec;
5993: }
1.957 raeburn 5994: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 5995: }
5996:
1.556 albertel 5997: sub format_name {
5998: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5999: my $name;
6000: if ($first ne 'lastname') {
6001: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6002: } else {
6003: if ($lastname=~/\S/) {
6004: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6005: $name=~s/\s+,/,/;
6006: } else {
6007: $name.= $firstname.' '.$middlename.' '.$generation;
6008: }
6009: }
6010: $name=~s/^\s+//;
6011: $name=~s/\s+$//;
6012: $name=~s/\s+/ /g;
6013: return $name;
6014: }
6015:
1.84 www 6016: # ------------------------------------------------- Write to course preferences
6017:
6018: sub writecoursepref {
6019: my ($courseid,%prefs)=@_;
6020: $courseid=~s/^\///;
6021: $courseid=~s/\_/\//g;
6022: my ($cdomain,$cnum)=split(/\//,$courseid);
6023: my $chome=homeserver($cnum,$cdomain);
6024: if (($chome eq '') || ($chome eq 'no_host')) {
6025: return 'error: no such course';
6026: }
6027: my $cstring='';
1.800 albertel 6028: foreach my $pref (keys(%prefs)) {
6029: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6030: }
1.84 www 6031: $cstring=~s/\&$//;
6032: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6033: }
6034:
6035: # ---------------------------------------------------------- Make/modify course
6036:
6037: sub createcourse {
1.741 raeburn 6038: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6039: $course_owner,$crstype)=@_;
1.84 www 6040: $url=&declutter($url);
6041: my $cid='';
1.264 matthew 6042: unless (&allowed('ccc',$udom)) {
1.84 www 6043: return 'refused';
6044: }
6045: # ------------------------------------------------------------------- Create ID
1.674 www 6046: my $uname=int(1+rand(9)).
6047: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6048: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 6049: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6050: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 6051: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6052: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6053: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
6054: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 6055: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6056: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6057: return 'error: unable to generate unique course-ID';
6058: }
6059: }
1.264 matthew 6060: # ------------------------------------------------ Check supplied server name
1.620 albertel 6061: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6062: if (! &is_library($course_server)) {
1.264 matthew 6063: return 'error:bad server name '.$course_server;
6064: }
1.84 www 6065: # ------------------------------------------------------------- Make the course
6066: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6067: $course_server);
1.84 www 6068: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 6069: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6070: if (($uhome eq '') || ($uhome eq 'no_host')) {
6071: return 'error: no such course';
6072: }
1.271 www 6073: # ----------------------------------------------------------------- Course made
1.516 raeburn 6074: # log existence
1.918 raeburn 6075: my $newcourse = {
6076: $udom.'_'.$uname => {
1.921 raeburn 6077: description => $description,
6078: inst_code => $inst_code,
6079: owner => $course_owner,
6080: type => $crstype,
1.918 raeburn 6081: },
6082: };
1.921 raeburn 6083: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6084: # set toplevel url
1.271 www 6085: my $topurl=$url;
6086: unless ($nonstandard) {
6087: # ------------------------------------------ For standard courses, make top url
6088: my $mapurl=&clutter($url);
1.278 www 6089: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6090: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6091: <map>
6092: <resource id="1" type="start"></resource>
6093: <resource id="2" src="$mapurl"></resource>
6094: <resource id="3" type="finish"></resource>
6095: <link index="1" from="1" to="2"></link>
6096: <link index="2" from="2" to="3"></link>
6097: </map>
6098: ENDINITMAP
6099: $topurl=&declutter(
1.638 albertel 6100: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6101: );
6102: }
6103: # ----------------------------------------------------------- Write preferences
1.84 www 6104: &writecoursepref($udom.'_'.$uname,
6105: ('description' => $description,
1.271 www 6106: 'url' => $topurl));
1.84 www 6107: return '/'.$udom.'/'.$uname;
6108: }
6109:
1.813 albertel 6110: sub is_course {
6111: my ($cdom,$cnum) = @_;
6112: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6113: undef,'.');
1.813 albertel 6114: if (exists($courses{$cdom.'_'.$cnum})) {
6115: return 1;
6116: }
6117: return 0;
6118: }
6119:
1.21 www 6120: # ---------------------------------------------------------- Assign Custom Role
6121:
6122: sub assigncustomrole {
1.957 raeburn 6123: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6124: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6125: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6126: }
6127:
6128: # ----------------------------------------------------------------- Revoke Role
6129:
6130: sub revokerole {
1.957 raeburn 6131: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6132: my $now=time;
1.965 raeburn 6133: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6134: }
6135:
6136: # ---------------------------------------------------------- Revoke Custom Role
6137:
6138: sub revokecustomrole {
1.957 raeburn 6139: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6140: my $now=time;
1.357 www 6141: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6142: $deleteflag,$selfenroll,$context);
1.17 www 6143: }
6144:
1.533 banghart 6145: # ------------------------------------------------------------ Disk usage
1.535 albertel 6146: sub diskusage {
1.955 raeburn 6147: my ($udom,$uname,$directorypath,$getpropath)=@_;
6148: $directorypath =~ s/\/$//;
6149: my $listing=&reply('du2:'.&escape($directorypath).':'
6150: .&escape($getpropath).':'.&escape($uname).':'
6151: .&escape($udom),homeserver($uname,$udom));
6152: if ($listing eq 'unknown_cmd') {
6153: if ($getpropath) {
6154: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6155: }
6156: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6157: }
1.514 albertel 6158: return $listing;
1.512 banghart 6159: }
6160:
1.566 banghart 6161: sub is_locked {
6162: my ($file_name, $domain, $user) = @_;
6163: my @check;
6164: my $is_locked;
6165: push @check, $file_name;
1.613 albertel 6166: my %locked = &get('file_permissions',\@check,
1.620 albertel 6167: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6168: my ($tmp)=keys(%locked);
6169: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6170:
1.566 banghart 6171: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6172: $is_locked = 'false';
6173: foreach my $entry (@{$locked{$file_name}}) {
6174: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6175: $is_locked = 'true';
6176: last;
1.745 raeburn 6177: }
6178: }
1.566 banghart 6179: } else {
6180: $is_locked = 'false';
6181: }
6182: }
6183:
1.759 albertel 6184: sub declutter_portfile {
6185: my ($file) = @_;
1.833 albertel 6186: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6187: return $file;
6188: }
6189:
1.559 banghart 6190: # ------------------------------------------------------------- Mark as Read Only
6191:
6192: sub mark_as_readonly {
6193: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6194: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6195: my ($tmp)=keys(%current_permissions);
6196: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6197: foreach my $file (@{$files}) {
1.759 albertel 6198: $file = &declutter_portfile($file);
1.561 banghart 6199: push(@{$current_permissions{$file}},$what);
1.559 banghart 6200: }
1.613 albertel 6201: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6202: return;
6203: }
6204:
1.572 banghart 6205: # ------------------------------------------------------------Save Selected Files
6206:
6207: sub save_selected_files {
6208: my ($user, $path, @files) = @_;
6209: my $filename = $user."savedfiles";
1.573 banghart 6210: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6211: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6212: foreach my $file (@files) {
1.620 albertel 6213: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6214: }
6215: foreach my $file (@other_files) {
1.574 banghart 6216: print (OUT $file."\n");
1.572 banghart 6217: }
1.574 banghart 6218: close (OUT);
1.572 banghart 6219: return 'ok';
6220: }
6221:
1.574 banghart 6222: sub clear_selected_files {
6223: my ($user) = @_;
6224: my $filename = $user."savedfiles";
6225: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6226: print (OUT undef);
6227: close (OUT);
6228: return ("ok");
6229: }
6230:
1.572 banghart 6231: sub files_in_path {
6232: my ($user, $path) = @_;
6233: my $filename = $user."savedfiles";
6234: my %return_files;
1.574 banghart 6235: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6236: while (my $line_in = <IN>) {
1.574 banghart 6237: chomp ($line_in);
6238: my @paths_and_file = split (m!/!, $line_in);
6239: my $file_part = pop (@paths_and_file);
6240: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6241: $path_part.='/';
6242: my $path_and_file = $path_part.$file_part;
6243: if ($path_part eq $path) {
6244: $return_files{$file_part}= 'selected';
6245: }
6246: }
1.574 banghart 6247: close (IN);
6248: return (\%return_files);
1.572 banghart 6249: }
6250:
6251: # called in portfolio select mode, to show files selected NOT in current directory
6252: sub files_not_in_path {
6253: my ($user, $path) = @_;
6254: my $filename = $user."savedfiles";
6255: my @return_files;
6256: my $path_part;
1.800 albertel 6257: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6258: while (my $line = <IN>) {
1.572 banghart 6259: #ok, I know it's clunky, but I want it to work
1.800 albertel 6260: my @paths_and_file = split(m|/|, $line);
6261: my $file_part = pop(@paths_and_file);
6262: chomp($file_part);
6263: my $path_part = join('/', @paths_and_file);
1.572 banghart 6264: $path_part .= '/';
6265: my $path_and_file = $path_part.$file_part;
6266: if ($path_part ne $path) {
1.800 albertel 6267: push(@return_files, ($path_and_file));
1.572 banghart 6268: }
6269: }
1.800 albertel 6270: close(OUT);
1.574 banghart 6271: return (@return_files);
1.572 banghart 6272: }
6273:
1.745 raeburn 6274: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6275:
1.745 raeburn 6276: sub get_portfile_permissions {
6277: my ($domain,$user) = @_;
1.613 albertel 6278: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6279: my ($tmp)=keys(%current_permissions);
6280: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6281: return \%current_permissions;
6282: }
6283:
6284: #---------------------------------------------Get portfolio file access controls
6285:
1.749 raeburn 6286: sub get_access_controls {
1.745 raeburn 6287: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6288: my %access;
6289: my $real_file = $file;
6290: $file =~ s/\.meta$//;
1.745 raeburn 6291: if (defined($file)) {
1.749 raeburn 6292: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6293: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6294: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6295: }
6296: }
1.745 raeburn 6297: } else {
1.749 raeburn 6298: foreach my $key (keys(%{$current_permissions})) {
6299: if ($key =~ /\0accesscontrol$/) {
6300: if (defined($group)) {
6301: if ($key !~ m-^\Q$group\E/-) {
6302: next;
6303: }
6304: }
6305: my ($fullpath) = split(/\0/,$key);
6306: if (ref($$current_permissions{$key}) eq 'HASH') {
6307: foreach my $control (keys(%{$$current_permissions{$key}})) {
6308: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6309: }
6310: }
6311: }
6312: }
6313: }
6314: return %access;
6315: }
6316:
6317: sub modify_access_controls {
6318: my ($file_name,$changes,$domain,$user)=@_;
6319: my ($outcome,$deloutcome);
6320: my %store_permissions;
6321: my %new_values;
6322: my %new_control;
6323: my %translation;
6324: my @deletions = ();
6325: my $now = time;
6326: if (exists($$changes{'activate'})) {
6327: if (ref($$changes{'activate'}) eq 'HASH') {
6328: my @newitems = sort(keys(%{$$changes{'activate'}}));
6329: my $numnew = scalar(@newitems);
6330: for (my $i=0; $i<$numnew; $i++) {
6331: my $newkey = $newitems[$i];
6332: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6333: if ($newkey =~ /^\d+:/) {
6334: $newkey =~ s/^(\d+)/$newid/;
6335: $translation{$1} = $newid;
6336: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6337: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6338: $translation{$1} = $newid;
6339: }
1.749 raeburn 6340: $new_values{$file_name."\0".$newkey} =
6341: $$changes{'activate'}{$newitems[$i]};
6342: $new_control{$newkey} = $now;
6343: }
6344: }
6345: }
6346: my %todelete;
6347: my %changed_items;
6348: foreach my $action ('delete','update') {
6349: if (exists($$changes{$action})) {
6350: if (ref($$changes{$action}) eq 'HASH') {
6351: foreach my $key (keys(%{$$changes{$action}})) {
6352: my ($itemnum) = ($key =~ /^([^:]+):/);
6353: if ($action eq 'delete') {
6354: $todelete{$itemnum} = 1;
6355: } else {
6356: $changed_items{$itemnum} = $key;
6357: }
6358: }
1.745 raeburn 6359: }
6360: }
1.749 raeburn 6361: }
6362: # get lock on access controls for file.
6363: my $lockhash = {
6364: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6365: ':'.$env{'user.domain'},
6366: };
6367: my $tries = 0;
6368: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6369:
6370: while (($gotlock ne 'ok') && $tries <3) {
6371: $tries ++;
6372: sleep 1;
6373: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6374: }
6375: if ($gotlock eq 'ok') {
6376: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6377: my ($tmp)=keys(%curr_permissions);
6378: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6379: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6380: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6381: if (ref($curr_controls) eq 'HASH') {
6382: foreach my $control_item (keys(%{$curr_controls})) {
6383: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6384: if (defined($todelete{$itemnum})) {
6385: push(@deletions,$file_name."\0".$control_item);
6386: } else {
6387: if (defined($changed_items{$itemnum})) {
6388: $new_control{$changed_items{$itemnum}} = $now;
6389: push(@deletions,$file_name."\0".$control_item);
6390: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6391: } else {
6392: $new_control{$control_item} = $$curr_controls{$control_item};
6393: }
6394: }
1.745 raeburn 6395: }
6396: }
6397: }
1.970 raeburn 6398: my ($group);
6399: if (&is_course($domain,$user)) {
6400: ($group,my $file) = split(/\//,$file_name,2);
6401: }
1.749 raeburn 6402: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6403: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6404: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6405: # remove lock
6406: my @del_lock = ($file_name."\0".'locked_access_records');
6407: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6408: my $sqlresult =
1.970 raeburn 6409: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6410: $group);
1.749 raeburn 6411: } else {
6412: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6413: }
1.749 raeburn 6414: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6415: }
6416:
1.827 raeburn 6417: sub make_public_indefinitely {
6418: my ($requrl) = @_;
6419: my $now = time;
6420: my $action = 'activate';
6421: my $aclnum = 0;
6422: if (&is_portfolio_url($requrl)) {
6423: my (undef,$udom,$unum,$file_name,$group) =
6424: &parse_portfolio_url($requrl);
6425: my $current_perms = &get_portfile_permissions($udom,$unum);
6426: my %access_controls = &get_access_controls($current_perms,
6427: $group,$file_name);
6428: foreach my $key (keys(%{$access_controls{$file_name}})) {
6429: my ($num,$scope,$end,$start) =
6430: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6431: if ($scope eq 'public') {
6432: if ($start <= $now && $end == 0) {
6433: $action = 'none';
6434: } else {
6435: $action = 'update';
6436: $aclnum = $num;
6437: }
6438: last;
6439: }
6440: }
6441: if ($action eq 'none') {
6442: return 'ok';
6443: } else {
6444: my %changes;
6445: my $newend = 0;
6446: my $newstart = $now;
6447: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6448: $changes{$action}{$newkey} = {
6449: type => 'public',
6450: time => {
6451: start => $newstart,
6452: end => $newend,
6453: },
6454: };
6455: my ($outcome,$deloutcome,$new_values,$translation) =
6456: &modify_access_controls($file_name,\%changes,$udom,$unum);
6457: return $outcome;
6458: }
6459: } else {
6460: return 'invalid';
6461: }
6462: }
6463:
1.745 raeburn 6464: #------------------------------------------------------Get Marked as Read Only
6465:
6466: sub get_marked_as_readonly {
6467: my ($domain,$user,$what,$group) = @_;
6468: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6469: my @readonly_files;
1.629 banghart 6470: my $cmp1=$what;
6471: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6472: while (my ($file_name,$value) = each(%{$current_permissions})) {
6473: if (defined($group)) {
6474: if ($file_name !~ m-^\Q$group\E/-) {
6475: next;
6476: }
6477: }
1.561 banghart 6478: if (ref($value) eq "ARRAY"){
6479: foreach my $stored_what (@{$value}) {
1.629 banghart 6480: my $cmp2=$stored_what;
1.759 albertel 6481: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6482: $cmp2=join('',@{$stored_what});
1.745 raeburn 6483: }
1.629 banghart 6484: if ($cmp1 eq $cmp2) {
1.561 banghart 6485: push(@readonly_files, $file_name);
1.745 raeburn 6486: last;
1.563 banghart 6487: } elsif (!defined($what)) {
6488: push(@readonly_files, $file_name);
1.745 raeburn 6489: last;
1.561 banghart 6490: }
6491: }
1.745 raeburn 6492: }
1.561 banghart 6493: }
6494: return @readonly_files;
6495: }
1.577 banghart 6496: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6497:
1.577 banghart 6498: sub get_marked_as_readonly_hash {
1.745 raeburn 6499: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6500: my %readonly_files;
1.745 raeburn 6501: while (my ($file_name,$value) = each(%{$current_permissions})) {
6502: if (defined($group)) {
6503: if ($file_name !~ m-^\Q$group\E/-) {
6504: next;
6505: }
6506: }
1.577 banghart 6507: if (ref($value) eq "ARRAY"){
6508: foreach my $stored_what (@{$value}) {
1.745 raeburn 6509: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6510: foreach my $lock_descriptor(@{$stored_what}) {
6511: if ($lock_descriptor eq 'graded') {
6512: $readonly_files{$file_name} = 'graded';
6513: } elsif ($lock_descriptor eq 'handback') {
6514: $readonly_files{$file_name} = 'handback';
6515: } else {
6516: if (!exists($readonly_files{$file_name})) {
6517: $readonly_files{$file_name} = 'locked';
6518: }
6519: }
1.745 raeburn 6520: }
1.750 banghart 6521: }
1.577 banghart 6522: }
6523: }
6524: }
6525: return %readonly_files;
6526: }
1.559 banghart 6527: # ------------------------------------------------------------ Unmark as Read Only
6528:
6529: sub unmark_as_readonly {
1.629 banghart 6530: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6531: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6532: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6533: $file_name = &declutter_portfile($file_name);
1.634 albertel 6534: my $symb_crs = $what;
6535: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6536: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6537: my ($tmp)=keys(%current_permissions);
6538: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6539: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6540: foreach my $file (@readonly_files) {
1.759 albertel 6541: my $clean_file = &declutter_portfile($file);
6542: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6543: my $current_locks = $current_permissions{$file};
1.563 banghart 6544: my @new_locks;
6545: my @del_keys;
6546: if (ref($current_locks) eq "ARRAY"){
6547: foreach my $locker (@{$current_locks}) {
1.632 albertel 6548: my $compare=$locker;
1.749 raeburn 6549: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6550: $compare=join('',@{$locker});
1.746 raeburn 6551: if ($compare ne $symb_crs) {
6552: push(@new_locks, $locker);
6553: }
1.563 banghart 6554: }
6555: }
1.650 albertel 6556: if (scalar(@new_locks) > 0) {
1.563 banghart 6557: $current_permissions{$file} = \@new_locks;
6558: } else {
6559: push(@del_keys, $file);
1.613 albertel 6560: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6561: delete($current_permissions{$file});
1.563 banghart 6562: }
6563: }
1.561 banghart 6564: }
1.613 albertel 6565: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6566: return;
6567: }
1.512 banghart 6568:
1.17 www 6569: # ------------------------------------------------------------ Directory lister
6570:
6571: sub dirlist {
1.955 raeburn 6572: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6573: $uri=~s/^\///;
6574: $uri=~s/\/$//;
1.253 stredwic 6575: my ($udom, $uname);
1.955 raeburn 6576: if ($getuserdir) {
1.253 stredwic 6577: $udom = $userdomain;
6578: $uname = $username;
1.955 raeburn 6579: } else {
6580: (undef,$udom,$uname)=split(/\//,$uri);
6581: if(defined($userdomain)) {
6582: $udom = $userdomain;
6583: }
6584: if(defined($username)) {
6585: $uname = $username;
6586: }
1.253 stredwic 6587: }
1.955 raeburn 6588: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6589:
1.955 raeburn 6590: $dirRoot = $perlvar{'lonDocRoot'};
6591: if (defined($getpropath)) {
6592: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6593: $dirRoot =~ s/\/$//;
1.955 raeburn 6594: } elsif (defined($getuserdir)) {
6595: my $subdir=$uname.'__';
6596: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6597: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6598: ."/$udom/$subdir/$uname";
6599: } elsif (defined($alternateRoot)) {
6600: $dirRoot = $alternateRoot;
1.751 banghart 6601: }
1.253 stredwic 6602:
6603: if($udom) {
6604: if($uname) {
1.955 raeburn 6605: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6606: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6607: .':'.&escape($uname).':'.&escape($udom),
6608: &homeserver($uname,$udom));
6609: if ($listing eq 'unknown_cmd') {
6610: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6611: &homeserver($uname,$udom));
6612: } else {
6613: @listing_results = map { &unescape($_); } split(/:/,$listing);
6614: }
1.605 matthew 6615: if ($listing eq 'unknown_cmd') {
1.800 albertel 6616: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6617: &homeserver($uname,$udom));
1.605 matthew 6618: @listing_results = split(/:/,$listing);
6619: } else {
6620: @listing_results = map { &unescape($_); } split(/:/,$listing);
6621: }
6622: return @listing_results;
1.955 raeburn 6623: } elsif(!$alternateRoot) {
1.800 albertel 6624: my %allusers;
1.841 albertel 6625: my %servers = &get_servers($udom,'library');
1.955 raeburn 6626: foreach my $tryserver (keys(%servers)) {
6627: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6628: &escape($udom),$tryserver);
6629: if ($listing eq 'unknown_cmd') {
6630: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6631: $udom, $tryserver);
6632: } else {
6633: @listing_results = map { &unescape($_); } split(/:/,$listing);
6634: }
1.841 albertel 6635: if ($listing eq 'unknown_cmd') {
6636: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6637: $udom, $tryserver);
6638: @listing_results = split(/:/,$listing);
6639: } else {
6640: @listing_results =
6641: map { &unescape($_); } split(/:/,$listing);
6642: }
6643: if ($listing_results[0] ne 'no_such_dir' &&
6644: $listing_results[0] ne 'empty' &&
6645: $listing_results[0] ne 'con_lost') {
6646: foreach my $line (@listing_results) {
6647: my ($entry) = split(/&/,$line,2);
6648: $allusers{$entry} = 1;
6649: }
6650: }
1.253 stredwic 6651: }
6652: my $alluserstr='';
1.800 albertel 6653: foreach my $user (sort(keys(%allusers))) {
6654: $alluserstr.=$user.'&user:';
1.253 stredwic 6655: }
6656: $alluserstr=~s/:$//;
6657: return split(/:/,$alluserstr);
6658: } else {
1.800 albertel 6659: return ('missing user name');
1.253 stredwic 6660: }
1.955 raeburn 6661: } elsif(!defined($getpropath)) {
1.841 albertel 6662: my @all_domains = sort(&all_domains());
1.955 raeburn 6663: foreach my $domain (@all_domains) {
6664: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6665: }
6666: return @all_domains;
6667: } else {
1.800 albertel 6668: return ('missing domain');
1.275 stredwic 6669: }
6670: }
6671:
6672: # --------------------------------------------- GetFileTimestamp
6673: # This function utilizes dirlist and returns the date stamp for
6674: # when it was last modified. It will also return an error of -1
6675: # if an error occurs
6676:
6677: sub GetFileTimestamp {
1.955 raeburn 6678: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6679: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6680: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6681: my ($fileStat) =
6682: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6683: undef,$getuserdir);
1.275 stredwic 6684: my @stats = split('&', $fileStat);
6685: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6686: # @stats contains first the filename, then the stat output
6687: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6688: } else {
6689: return -1;
1.253 stredwic 6690: }
1.26 www 6691: }
6692:
1.712 albertel 6693: sub stat_file {
6694: my ($uri) = @_;
1.787 albertel 6695: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6696:
1.955 raeburn 6697: my ($udom,$uname,$file);
1.712 albertel 6698: if ($uri =~ m-^/(uploaded|editupload)/-) {
6699: ($udom,$uname,$file) =
1.811 albertel 6700: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6701: $file = 'userfiles/'.$file;
6702: }
6703: if ($uri =~ m-^/res/-) {
6704: ($udom,$uname) =
1.807 albertel 6705: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6706: $file = $uri;
6707: }
6708:
6709: if (!$udom || !$uname || !$file) {
6710: # unable to handle the uri
6711: return ();
6712: }
1.956 raeburn 6713: my $getpropath;
6714: if ($file =~ /^userfiles\//) {
6715: $getpropath = 1;
6716: }
1.955 raeburn 6717: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6718: my @stats = split('&', $result);
1.721 banghart 6719:
1.712 albertel 6720: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6721: shift(@stats); #filename is first
6722: return @stats;
6723: }
6724: return ();
6725: }
6726:
1.26 www 6727: # -------------------------------------------------------- Value of a Condition
6728:
1.713 albertel 6729: # gets the value of a specific preevaluated condition
6730: # stored in the string $env{user.state.<cid>}
6731: # or looks up a condition reference in the bighash and if if hasn't
6732: # already been evaluated recurses into docondval to get the value of
6733: # the condition, then memoizing it to
6734: # $env{user.state.<cid>.<condition>}
1.40 www 6735: sub directcondval {
6736: my $number=shift;
1.620 albertel 6737: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6738: &Apache::lonuserstate::evalstate();
6739: }
1.713 albertel 6740: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6741: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6742: } elsif ($number =~ /^_/) {
6743: my $sub_condition;
6744: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6745: &GDBM_READER(),0640)) {
6746: $sub_condition=$bighash{'conditions'.$number};
6747: untie(%bighash);
6748: }
6749: my $value = &docondval($sub_condition);
1.949 raeburn 6750: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6751: return $value;
6752: }
1.620 albertel 6753: if ($env{'user.state.'.$env{'request.course.id'}}) {
6754: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6755: } else {
6756: return 2;
6757: }
6758: }
6759:
1.713 albertel 6760: # get the collection of conditions for this resource
1.26 www 6761: sub condval {
6762: my $condidx=shift;
1.54 www 6763: my $allpathcond='';
1.713 albertel 6764: foreach my $cond (split(/\|/,$condidx)) {
6765: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6766: $allpathcond.=
6767: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6768: }
1.191 harris41 6769: }
1.54 www 6770: $allpathcond=~s/\|$//;
1.713 albertel 6771: return &docondval($allpathcond);
6772: }
6773:
6774: #evaluates an expression of conditions
6775: sub docondval {
6776: my ($allpathcond) = @_;
6777: my $result=0;
6778: if ($env{'request.course.id'}
6779: && defined($allpathcond)) {
6780: my $operand='|';
6781: my @stack;
6782: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6783: if ($chunk eq '(') {
6784: push @stack,($operand,$result);
6785: } elsif ($chunk eq ')') {
6786: my $before=pop @stack;
6787: if (pop @stack eq '&') {
6788: $result=$result>$before?$before:$result;
6789: } else {
6790: $result=$result>$before?$result:$before;
6791: }
6792: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6793: $operand=$chunk;
6794: } else {
6795: my $new=directcondval($chunk);
6796: if ($operand eq '&') {
6797: $result=$result>$new?$new:$result;
6798: } else {
6799: $result=$result>$new?$result:$new;
6800: }
6801: }
6802: }
1.26 www 6803: }
6804: return $result;
1.421 albertel 6805: }
6806:
6807: # ---------------------------------------------------- Devalidate courseresdata
6808:
6809: sub devalidatecourseresdata {
6810: my ($coursenum,$coursedomain)=@_;
6811: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6812: &devalidate_cache_new('courseres',$hashid);
1.28 www 6813: }
6814:
1.763 www 6815:
1.200 www 6816: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6817: #
6818: # Parameters:
6819: # $coursenum - Number of the course.
6820: # $coursedomain - Domain at which the course was created.
6821: # Returns:
6822: # A hash of the course parameters along (I think) with timestamps
6823: # and version info.
1.877 foxr 6824:
1.624 albertel 6825: sub get_courseresdata {
6826: my ($coursenum,$coursedomain)=@_;
1.200 www 6827: my $coursehom=&homeserver($coursenum,$coursedomain);
6828: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6829: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6830: my %dumpreply;
1.417 albertel 6831: unless (defined($cached)) {
1.624 albertel 6832: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6833: $result=\%dumpreply;
1.251 albertel 6834: my ($tmp) = keys(%dumpreply);
6835: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6836: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6837: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6838: return $tmp;
1.416 albertel 6839: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6840: $result=undef;
1.599 albertel 6841: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6842: }
6843: }
1.624 albertel 6844: return $result;
6845: }
6846:
1.633 albertel 6847: sub devalidateuserresdata {
6848: my ($uname,$udom)=@_;
6849: my $hashid="$udom:$uname";
6850: &devalidate_cache_new('userres',$hashid);
6851: }
6852:
1.624 albertel 6853: sub get_userresdata {
6854: my ($uname,$udom)=@_;
6855: #most student don\'t have any data set, check if there is some data
6856: if (&EXT_cache_status($udom,$uname)) { return undef; }
6857:
6858: my $hashid="$udom:$uname";
6859: my ($result,$cached)=&is_cached_new('userres',$hashid);
6860: if (!defined($cached)) {
6861: my %resourcedata=&dump('resourcedata',$udom,$uname);
6862: $result=\%resourcedata;
6863: &do_cache_new('userres',$hashid,$result,600);
6864: }
6865: my ($tmp)=keys(%$result);
6866: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6867: return $result;
6868: }
6869: #error 2 occurs when the .db doesn't exist
6870: if ($tmp!~/error: 2 /) {
1.672 albertel 6871: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6872: " Trying to get resource data for ".
6873: $uname." at ".$udom.": ".
6874: $tmp."</font>");
6875: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6876: #&EXT_cache_set($udom,$uname);
6877: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6878: undef($tmp); # not really an error so don't send it back
1.624 albertel 6879: }
6880: return $tmp;
6881: }
1.879 foxr 6882: #----------------------------------------------- resdata - return resource data
6883: # Purpose:
6884: # Return resource data for either users or for a course.
6885: # Parameters:
6886: # $name - Course/user name.
6887: # $domain - Name of the domain the user/course is registered on.
6888: # $type - Type of thing $name is (must be 'course' or 'user'
6889: # @which - Array of names of resources desired.
6890: # Returns:
6891: # The value of the first reasource in @which that is found in the
6892: # resource hash.
6893: # Exceptional Conditions:
6894: # If the $type passed in is not valid (not the string 'course' or
6895: # 'user', an undefined reference is returned.
6896: # If none of the resources are found, an undef is returned
1.624 albertel 6897: sub resdata {
6898: my ($name,$domain,$type,@which)=@_;
6899: my $result;
6900: if ($type eq 'course') {
6901: $result=&get_courseresdata($name,$domain);
6902: } elsif ($type eq 'user') {
6903: $result=&get_userresdata($name,$domain);
6904: }
6905: if (!ref($result)) { return $result; }
1.251 albertel 6906: foreach my $item (@which) {
1.927 albertel 6907: if (defined($result->{$item->[0]})) {
6908: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6909: }
1.250 albertel 6910: }
1.291 albertel 6911: return undef;
1.200 www 6912: }
6913:
1.379 matthew 6914: #
6915: # EXT resource caching routines
6916: #
6917:
6918: sub clear_EXT_cache_status {
1.383 albertel 6919: &delenv('cache.EXT.');
1.379 matthew 6920: }
6921:
6922: sub EXT_cache_status {
6923: my ($target_domain,$target_user) = @_;
1.383 albertel 6924: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6925: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6926: # We know already the user has no data
6927: return 1;
6928: } else {
6929: return 0;
6930: }
6931: }
6932:
6933: sub EXT_cache_set {
6934: my ($target_domain,$target_user) = @_;
1.383 albertel 6935: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 6936: #&appenv({$cachename => time});
1.379 matthew 6937: }
6938:
1.28 www 6939: # --------------------------------------------------------- Value of a Variable
1.58 www 6940: sub EXT {
1.715 albertel 6941:
1.395 albertel 6942: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6943: unless ($varname) { return ''; }
1.218 albertel 6944: #get real user name/domain, courseid and symb
6945: my $courseid;
1.359 albertel 6946: my $publicuser;
1.427 www 6947: if ($symbparm) {
6948: $symbparm=&get_symb_from_alias($symbparm);
6949: }
1.218 albertel 6950: if (!($uname && $udom)) {
1.790 albertel 6951: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6952: if (!$symbparm) { $symbparm=$cursymb; }
6953: } else {
1.620 albertel 6954: $courseid=$env{'request.course.id'};
1.218 albertel 6955: }
1.48 www 6956: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6957: my $rest;
1.320 albertel 6958: if (defined($therest[0])) {
1.48 www 6959: $rest=join('.',@therest);
6960: } else {
6961: $rest='';
6962: }
1.320 albertel 6963:
1.57 www 6964: my $qualifierrest=$qualifier;
6965: if ($rest) { $qualifierrest.='.'.$rest; }
6966: my $spacequalifierrest=$space;
6967: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6968: if ($realm eq 'user') {
1.48 www 6969: # --------------------------------------------------------------- user.resource
6970: if ($space eq 'resource') {
1.651 albertel 6971: if ( (defined($Apache::lonhomework::parsing_a_problem)
6972: || defined($Apache::lonhomework::parsing_a_task))
6973: &&
1.744 albertel 6974: ($symbparm eq &symbread()) ) {
6975: # if we are in the middle of processing the resource the
6976: # get the value we are planning on committing
6977: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6978: return $Apache::lonhomework::results{$qualifierrest};
6979: } else {
6980: return $Apache::lonhomework::history{$qualifierrest};
6981: }
1.335 albertel 6982: } else {
1.359 albertel 6983: my %restored;
1.620 albertel 6984: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6985: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6986: } else {
6987: %restored=&restore($symbparm,$courseid,$udom,$uname);
6988: }
1.335 albertel 6989: return $restored{$qualifierrest};
6990: }
1.48 www 6991: # ----------------------------------------------------------------- user.access
6992: } elsif ($space eq 'access') {
1.218 albertel 6993: # FIXME - not supporting calls for a specific user
1.48 www 6994: return &allowed($qualifier,$rest);
6995: # ------------------------------------------ user.preferences, user.environment
6996: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6997: if (($uname eq $env{'user.name'}) &&
6998: ($udom eq $env{'user.domain'})) {
6999: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7000: } else {
1.359 albertel 7001: my %returnhash;
7002: if (!$publicuser) {
7003: %returnhash=&userenvironment($udom,$uname,
7004: $qualifierrest);
7005: }
1.218 albertel 7006: return $returnhash{$qualifierrest};
7007: }
1.48 www 7008: # ----------------------------------------------------------------- user.course
7009: } elsif ($space eq 'course') {
1.218 albertel 7010: # FIXME - not supporting calls for a specific user
1.620 albertel 7011: return $env{join('.',('request.course',$qualifier))};
1.48 www 7012: # ------------------------------------------------------------------- user.role
7013: } elsif ($space eq 'role') {
1.218 albertel 7014: # FIXME - not supporting calls for a specific user
1.620 albertel 7015: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7016: if ($qualifier eq 'value') {
7017: return $role;
7018: } elsif ($qualifier eq 'extent') {
7019: return $where;
7020: }
7021: # ----------------------------------------------------------------- user.domain
7022: } elsif ($space eq 'domain') {
1.218 albertel 7023: return $udom;
1.48 www 7024: # ------------------------------------------------------------------- user.name
7025: } elsif ($space eq 'name') {
1.218 albertel 7026: return $uname;
1.48 www 7027: # ---------------------------------------------------- Any other user namespace
1.29 www 7028: } else {
1.359 albertel 7029: my %reply;
7030: if (!$publicuser) {
7031: %reply=&get($space,[$qualifierrest],$udom,$uname);
7032: }
7033: return $reply{$qualifierrest};
1.48 www 7034: }
1.236 www 7035: } elsif ($realm eq 'query') {
7036: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7037: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7038: [$spacequalifierrest]);
1.620 albertel 7039: return $env{'form.'.$spacequalifierrest};
1.236 www 7040: } elsif ($realm eq 'request') {
1.48 www 7041: # ------------------------------------------------------------- request.browser
7042: if ($space eq 'browser') {
1.430 www 7043: if ($qualifier eq 'textremote') {
1.676 albertel 7044: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7045: return 1;
7046: } else {
7047: return 0;
7048: }
7049: } else {
1.620 albertel 7050: return $env{'browser.'.$qualifier};
1.430 www 7051: }
1.57 www 7052: # ------------------------------------------------------------ request.filename
7053: } else {
1.620 albertel 7054: return $env{'request.'.$spacequalifierrest};
1.29 www 7055: }
1.28 www 7056: } elsif ($realm eq 'course') {
1.48 www 7057: # ---------------------------------------------------------- course.description
1.620 albertel 7058: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7059: } elsif ($realm eq 'resource') {
1.165 www 7060:
1.620 albertel 7061: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7062: if (!$symbparm) { $symbparm=&symbread(); }
7063: }
1.693 albertel 7064:
7065: if ($space eq 'title') {
7066: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7067: return &gettitle($symbparm);
7068: }
7069:
7070: if ($space eq 'map') {
7071: my ($map) = &decode_symb($symbparm);
7072: return &symbread($map);
7073: }
1.905 albertel 7074: if ($space eq 'filename') {
7075: if ($symbparm) {
7076: return &clutter((&decode_symb($symbparm))[2]);
7077: }
7078: return &hreflocation('',$env{'request.filename'});
7079: }
1.693 albertel 7080:
7081: my ($section, $group, @groups);
1.593 albertel 7082: my ($courselevelm,$courselevel);
1.539 albertel 7083: if ($symbparm && defined($courseid) &&
1.620 albertel 7084: $courseid eq $env{'request.course.id'}) {
1.165 www 7085:
1.218 albertel 7086: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7087:
1.60 www 7088: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7089: my $symbp=$symbparm;
1.735 albertel 7090: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7091:
7092: my $symbparm=$symbp.'.'.$spacequalifierrest;
7093: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7094:
1.620 albertel 7095: if (($env{'user.name'} eq $uname) &&
7096: ($env{'user.domain'} eq $udom)) {
7097: $section=$env{'request.course.sec'};
1.733 raeburn 7098: @groups = split(/:/,$env{'request.course.groups'});
7099: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7100: } else {
1.539 albertel 7101: if (! defined($usection)) {
1.551 albertel 7102: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7103: } else {
7104: $section = $usection;
7105: }
1.733 raeburn 7106: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7107: }
7108:
7109: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7110: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7111: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7112:
1.593 albertel 7113: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7114: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7115: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7116:
1.60 www 7117: # ----------------------------------------------------------- first, check user
1.624 albertel 7118:
7119: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7120: ([$courselevelr,'resource'],
7121: [$courselevelm,'map' ],
7122: [$courselevel, 'course' ]));
1.931 albertel 7123: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7124:
1.594 albertel 7125: # ------------------------------------------------ second, check some of course
1.684 raeburn 7126: my $coursereply;
1.691 raeburn 7127: if (@groups > 0) {
7128: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7129: $mapparm,$spacequalifierrest);
1.927 albertel 7130: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7131: }
1.96 www 7132:
1.684 raeburn 7133: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7134: $env{'course.'.$courseid.'.domain'},
7135: 'course',
7136: ([$seclevelr, 'resource'],
7137: [$seclevelm, 'map' ],
7138: [$seclevel, 'course' ],
7139: [$courselevelr,'resource']));
7140: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7141:
1.60 www 7142: # ------------------------------------------------------ third, check map parms
1.218 albertel 7143: my %parmhash=();
7144: my $thisparm='';
7145: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7146: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7147: &GDBM_READER(),0640)) {
1.218 albertel 7148: $thisparm=$parmhash{$symbparm};
7149: untie(%parmhash);
7150: }
1.927 albertel 7151: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7152: }
1.594 albertel 7153: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7154:
1.218 albertel 7155: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7156: my $filename;
7157: if (!$symbparm) { $symbparm=&symbread(); }
7158: if ($symbparm) {
1.409 www 7159: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7160: } else {
1.620 albertel 7161: $filename=$env{'request.filename'};
1.282 albertel 7162: }
7163: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7164: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7165: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7166: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7167:
1.927 albertel 7168: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7169: if ($symbparm && defined($courseid) &&
1.620 albertel 7170: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7171: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7172: $env{'course.'.$courseid.'.domain'},
7173: 'course',
1.927 albertel 7174: ([$courselevelm,'map' ],
7175: [$courselevel, 'course']));
7176: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7177: }
1.145 www 7178: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7179: unless ($space eq '0') {
1.336 albertel 7180: my @parts=split(/_/,$space);
7181: my $id=pop(@parts);
7182: my $part=join('_',@parts);
7183: if ($part eq '') { $part='0'; }
1.927 albertel 7184: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7185: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7186: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7187: }
1.395 albertel 7188: if ($recurse) { return undef; }
7189: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7190: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7191: # ---------------------------------------------------- Any other user namespace
7192: } elsif ($realm eq 'environment') {
7193: # ----------------------------------------------------------------- environment
1.620 albertel 7194: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7195: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7196: } else {
1.770 albertel 7197: if ($uname eq 'anonymous' && $udom eq '') {
7198: return '';
7199: }
1.219 albertel 7200: my %returnhash=&userenvironment($udom,$uname,
7201: $spacequalifierrest);
7202: return $returnhash{$spacequalifierrest};
7203: }
1.28 www 7204: } elsif ($realm eq 'system') {
1.48 www 7205: # ----------------------------------------------------------------- system.time
7206: if ($space eq 'time') {
7207: return time;
7208: }
1.696 albertel 7209: } elsif ($realm eq 'server') {
7210: # ----------------------------------------------------------------- system.time
7211: if ($space eq 'name') {
7212: return $ENV{'SERVER_NAME'};
7213: }
1.28 www 7214: }
1.48 www 7215: return '';
1.61 www 7216: }
7217:
1.927 albertel 7218: sub get_reply {
7219: my ($reply_value) = @_;
1.940 raeburn 7220: if (ref($reply_value) eq 'ARRAY') {
7221: if (wantarray) {
7222: return @$reply_value;
7223: }
7224: return $reply_value->[0];
7225: } else {
7226: return $reply_value;
1.927 albertel 7227: }
7228: }
7229:
1.691 raeburn 7230: sub check_group_parms {
7231: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7232: my @groupitems = ();
7233: my $resultitem;
1.927 albertel 7234: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7235: foreach my $group (@{$groups}) {
7236: foreach my $level (@levels) {
1.927 albertel 7237: my $item = $courseid.'.['.$group.'].'.$level->[0];
7238: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7239: }
7240: }
7241: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7242: $env{'course.'.$courseid.'.domain'},
7243: 'course',@groupitems);
7244: return $coursereply;
7245: }
7246:
7247: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7248: my ($courseid,@groups) = @_;
7249: @groups = sort(@groups);
1.691 raeburn 7250: return @groups;
7251: }
7252:
1.395 albertel 7253: sub packages_tab_default {
7254: my ($uri,$varname)=@_;
7255: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7256:
7257: my (@extension,@specifics,$do_default);
7258: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7259: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7260: if ($pack_type eq 'default') {
7261: $do_default=1;
7262: } elsif ($pack_type eq 'extension') {
7263: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7264: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7265: # only look at packages defaults for packages that this id is
1.738 albertel 7266: push(@specifics,[$package,$pack_type,$pack_part]);
7267: }
7268: }
7269: # first look for a package that matches the requested part id
7270: foreach my $package (@specifics) {
7271: my (undef,$pack_type,$pack_part)=@{$package};
7272: next if ($pack_part ne $part);
7273: if (defined($packagetab{"$pack_type&$name&default"})) {
7274: return $packagetab{"$pack_type&$name&default"};
7275: }
7276: }
7277: # look for any possible matching non extension_ package
7278: foreach my $package (@specifics) {
7279: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7280: if (defined($packagetab{"$pack_type&$name&default"})) {
7281: return $packagetab{"$pack_type&$name&default"};
7282: }
1.585 albertel 7283: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7284: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7285: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7286: }
7287: }
1.738 albertel 7288: # look for any posible extension_ match
7289: foreach my $package (@extension) {
7290: my ($package,$pack_type)=@{$package};
7291: if (defined($packagetab{"$pack_type&$name&default"})) {
7292: return $packagetab{"$pack_type&$name&default"};
7293: }
7294: if (defined($packagetab{$package."&$name&default"})) {
7295: return $packagetab{$package."&$name&default"};
7296: }
7297: }
7298: # look for a global default setting
7299: if ($do_default && defined($packagetab{"default&$name&default"})) {
7300: return $packagetab{"default&$name&default"};
7301: }
1.395 albertel 7302: return undef;
7303: }
7304:
1.334 albertel 7305: sub add_prefix_and_part {
7306: my ($prefix,$part)=@_;
7307: my $keyroot;
7308: if (defined($prefix) && $prefix !~ /^__/) {
7309: # prefix that has a part already
7310: $keyroot=$prefix;
7311: } elsif (defined($prefix)) {
7312: # prefix that is missing a part
7313: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7314: } else {
7315: # no prefix at all
7316: if (defined($part)) { $keyroot='_'.$part; }
7317: }
7318: return $keyroot;
7319: }
7320:
1.71 www 7321: # ---------------------------------------------------------------- Get metadata
7322:
1.599 albertel 7323: my %metaentry;
1.71 www 7324: sub metadata {
1.176 www 7325: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7326: $uri=&declutter($uri);
1.288 albertel 7327: # if it is a non metadata possible uri return quickly
1.529 albertel 7328: if (($uri eq '') ||
7329: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7330: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7331: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7332: return undef;
7333: }
7334: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7335: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7336: return undef;
1.288 albertel 7337: }
1.73 www 7338: my $filename=$uri;
7339: $uri=~s/\.meta$//;
1.172 www 7340: #
7341: # Is the metadata already cached?
1.177 www 7342: # Look at timestamp of caching
1.172 www 7343: # Everything is cached by the main uri, libraries are never directly cached
7344: #
1.428 albertel 7345: if (!defined($liburi)) {
1.599 albertel 7346: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7347: if (defined($cached)) { return $result->{':'.$what}; }
7348: }
7349: {
1.172 www 7350: #
7351: # Is this a recursive call for a library?
7352: #
1.599 albertel 7353: # if (! exists($metacache{$uri})) {
7354: # $metacache{$uri}={};
7355: # }
1.924 albertel 7356: my $cachetime = 60*60;
1.171 www 7357: if ($liburi) {
7358: $liburi=&declutter($liburi);
7359: $filename=$liburi;
1.401 bowersj2 7360: } else {
1.599 albertel 7361: &devalidate_cache_new('meta',$uri);
7362: undef(%metaentry);
1.401 bowersj2 7363: }
1.140 www 7364: my %metathesekeys=();
1.73 www 7365: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7366: my $metastring;
1.924 albertel 7367: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7368: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7369: $metastring =
1.929 albertel 7370: &Apache::lonnet::ssi_body($which,
1.924 albertel 7371: ('grade_target' => 'meta'));
7372: $cachetime = 1; # only want this cached in the child not long term
7373: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7374: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7375: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7376: $metastring=&getfile($file);
1.489 albertel 7377: }
1.208 albertel 7378: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7379: my $token;
1.140 www 7380: undef %metathesekeys;
1.71 www 7381: while ($token=$parser->get_token) {
1.339 albertel 7382: if ($token->[0] eq 'S') {
7383: if (defined($token->[2]->{'package'})) {
1.172 www 7384: #
7385: # This is a package - get package info
7386: #
1.339 albertel 7387: my $package=$token->[2]->{'package'};
7388: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7389: if (defined($token->[2]->{'id'})) {
7390: $keyroot.='_'.$token->[2]->{'id'};
7391: }
1.599 albertel 7392: if ($metaentry{':packages'}) {
7393: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7394: } else {
1.599 albertel 7395: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7396: }
1.736 albertel 7397: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7398: my $part=$keyroot;
7399: $part=~s/^\_//;
1.736 albertel 7400: if ($pack_entry=~/^\Q$package\E\&/ ||
7401: $pack_entry=~/^\Q$package\E_0\&/) {
7402: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7403: # ignore package.tab specified default values
7404: # here &package_tab_default() will fetch those
7405: if ($subp eq 'default') { next; }
1.736 albertel 7406: my $value=$packagetab{$pack_entry};
1.432 albertel 7407: my $unikey;
7408: if ($pack =~ /_0$/) {
7409: $unikey='parameter_0_'.$name;
7410: $part=0;
7411: } else {
7412: $unikey='parameter'.$keyroot.'_'.$name;
7413: }
1.339 albertel 7414: if ($subp eq 'display') {
7415: $value.=' [Part: '.$part.']';
7416: }
1.599 albertel 7417: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7418: $metathesekeys{$unikey}=1;
1.599 albertel 7419: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7420: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7421: }
1.599 albertel 7422: if (defined($metaentry{':'.$unikey.'.default'})) {
7423: $metaentry{':'.$unikey}=
7424: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7425: }
1.339 albertel 7426: }
7427: }
7428: } else {
1.172 www 7429: #
7430: # This is not a package - some other kind of start tag
1.339 albertel 7431: #
7432: my $entry=$token->[1];
7433: my $unikey;
7434: if ($entry eq 'import') {
7435: $unikey='';
7436: } else {
7437: $unikey=$entry;
7438: }
7439: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7440:
7441: if (defined($token->[2]->{'id'})) {
7442: $unikey.='_'.$token->[2]->{'id'};
7443: }
1.175 www 7444:
1.339 albertel 7445: if ($entry eq 'import') {
1.175 www 7446: #
7447: # Importing a library here
1.339 albertel 7448: #
7449: if ($depthcount<20) {
7450: my $location=$parser->get_text('/import');
7451: my $dir=$filename;
7452: $dir=~s|[^/]*$||;
7453: $location=&filelocation($dir,$location);
1.736 albertel 7454: my $metadata =
7455: &metadata($uri,'keys', $location,$unikey,
7456: $depthcount+1);
7457: foreach my $meta (split(',',$metadata)) {
7458: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7459: $metathesekeys{$meta}=1;
1.339 albertel 7460: }
7461: }
7462: } else {
7463:
7464: if (defined($token->[2]->{'name'})) {
7465: $unikey.='_'.$token->[2]->{'name'};
7466: }
7467: $metathesekeys{$unikey}=1;
1.736 albertel 7468: foreach my $param (@{$token->[3]}) {
7469: $metaentry{':'.$unikey.'.'.$param} =
7470: $token->[2]->{$param};
1.339 albertel 7471: }
7472: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7473: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7474: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7475: # only ws inside the tag, and not in default, so use default
7476: # as value
1.599 albertel 7477: $metaentry{':'.$unikey}=$default;
1.908 albertel 7478: } elsif ( $internaltext =~ /\S/ ) {
7479: # something interesting inside the tag
7480: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7481: } else {
1.908 albertel 7482: # no interesting values, don't set a default
1.339 albertel 7483: }
1.172 www 7484: # end of not-a-package not-a-library import
1.339 albertel 7485: }
1.172 www 7486: # end of not-a-package start tag
1.339 albertel 7487: }
1.172 www 7488: # the next is the end of "start tag"
1.339 albertel 7489: }
7490: }
1.483 albertel 7491: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7492: $extension = lc($extension);
7493: if ($extension eq 'htm') { $extension='html'; }
7494:
1.737 albertel 7495: foreach my $key (keys(%packagetab)) {
1.483 albertel 7496: #no specific packages #how's our extension
7497: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7498: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7499: \%metathesekeys);
7500: }
1.883 albertel 7501:
7502: if (!exists($metaentry{':packages'})
7503: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7504: foreach my $key (keys(%packagetab)) {
1.483 albertel 7505: #no specific packages well let's get default then
7506: if ($key!~/^default&/) { next; }
1.488 albertel 7507: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7508: \%metathesekeys);
7509: }
7510: }
1.338 www 7511: # are there custom rights to evaluate
1.599 albertel 7512: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7513:
1.338 www 7514: #
7515: # Importing a rights file here
1.339 albertel 7516: #
7517: unless ($depthcount) {
1.599 albertel 7518: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7519: my $dir=$filename;
7520: $dir=~s|[^/]*$||;
7521: $location=&filelocation($dir,$location);
1.736 albertel 7522: my $rights_metadata =
7523: &metadata($uri,'keys',$location,'_rights',
7524: $depthcount+1);
7525: foreach my $rights (split(',',$rights_metadata)) {
7526: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7527: $metathesekeys{$rights}=1;
1.339 albertel 7528: }
7529: }
7530: }
1.737 albertel 7531: # uniqifiy package listing
7532: my %seen;
7533: my @uniq_packages =
7534: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7535: $metaentry{':packages'} = join(',',@uniq_packages);
7536:
7537: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7538: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7539: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7540: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7541: # this is the end of "was not already recently cached
1.71 www 7542: }
1.599 albertel 7543: return $metaentry{':'.$what};
1.261 albertel 7544: }
7545:
1.488 albertel 7546: sub metadata_create_package_def {
1.483 albertel 7547: my ($uri,$key,$package,$metathesekeys)=@_;
7548: my ($pack,$name,$subp)=split(/\&/,$key);
7549: if ($subp eq 'default') { next; }
7550:
1.599 albertel 7551: if (defined($metaentry{':packages'})) {
7552: $metaentry{':packages'}.=','.$package;
1.483 albertel 7553: } else {
1.599 albertel 7554: $metaentry{':packages'}=$package;
1.483 albertel 7555: }
7556: my $value=$packagetab{$key};
7557: my $unikey;
7558: $unikey='parameter_0_'.$name;
1.599 albertel 7559: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7560: $$metathesekeys{$unikey}=1;
1.599 albertel 7561: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7562: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7563: }
1.599 albertel 7564: if (defined($metaentry{':'.$unikey.'.default'})) {
7565: $metaentry{':'.$unikey}=
7566: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7567: }
7568: }
7569:
1.261 albertel 7570: sub metadata_generate_part0 {
7571: my ($metadata,$metacache,$uri) = @_;
7572: my %allnames;
1.737 albertel 7573: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7574: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7575: my $part=$$metacache{':'.$metakey.'.part'};
7576: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7577: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7578: $allnames{$name}=$part;
7579: }
7580: }
7581: }
7582: foreach my $name (keys(%allnames)) {
7583: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7584: my $key=":parameter_0_$name";
1.261 albertel 7585: $$metacache{"$key.part"}='0';
7586: $$metacache{"$key.name"}=$name;
1.428 albertel 7587: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7588: $allnames{$name}.'_'.$name.
7589: '.type'};
1.428 albertel 7590: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7591: '.display'};
1.644 www 7592: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7593: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7594: $$metacache{"$key.display"}=$olddis;
7595: }
1.71 www 7596: }
7597:
1.764 albertel 7598: # ------------------------------------------------------ Devalidate title cache
7599:
7600: sub devalidate_title_cache {
7601: my ($url)=@_;
7602: if (!$env{'request.course.id'}) { return; }
7603: my $symb=&symbread($url);
7604: if (!$symb) { return; }
7605: my $key=$env{'request.course.id'}."\0".$symb;
7606: &devalidate_cache_new('title',$key);
7607: }
7608:
1.301 www 7609: # ------------------------------------------------- Get the title of a resource
7610:
7611: sub gettitle {
7612: my $urlsymb=shift;
7613: my $symb=&symbread($urlsymb);
1.534 albertel 7614: if ($symb) {
1.620 albertel 7615: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7616: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7617: if (defined($cached)) {
7618: return $result;
7619: }
1.534 albertel 7620: my ($map,$resid,$url)=&decode_symb($symb);
7621: my $title='';
1.907 albertel 7622: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7623: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7624: } else {
7625: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7626: &GDBM_READER(),0640)) {
7627: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7628: $title=$bighash{'title_'.$mapid.'.'.$resid};
7629: untie(%bighash);
7630: }
1.534 albertel 7631: }
7632: $title=~s/\&colon\;/\:/gs;
7633: if ($title) {
1.599 albertel 7634: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7635: }
7636: $urlsymb=$url;
7637: }
7638: my $title=&metadata($urlsymb,'title');
7639: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7640: return $title;
1.301 www 7641: }
1.613 albertel 7642:
1.614 albertel 7643: sub get_slot {
7644: my ($which,$cnum,$cdom)=@_;
7645: if (!$cnum || !$cdom) {
1.790 albertel 7646: (undef,my $courseid)=&whichuser();
1.620 albertel 7647: $cdom=$env{'course.'.$courseid.'.domain'};
7648: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7649: }
1.703 albertel 7650: my $key=join("\0",'slots',$cdom,$cnum,$which);
7651: my %slotinfo;
7652: if (exists($remembered{$key})) {
7653: $slotinfo{$which} = $remembered{$key};
7654: } else {
7655: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7656: &Apache::lonhomework::showhash(%slotinfo);
7657: my ($tmp)=keys(%slotinfo);
7658: if ($tmp=~/^error:/) { return (); }
7659: $remembered{$key} = $slotinfo{$which};
7660: }
1.616 albertel 7661: if (ref($slotinfo{$which}) eq 'HASH') {
7662: return %{$slotinfo{$which}};
7663: }
7664: return $slotinfo{$which};
1.614 albertel 7665: }
1.31 www 7666: # ------------------------------------------------- Update symbolic store links
7667:
7668: sub symblist {
7669: my ($mapname,%newhash)=@_;
1.438 www 7670: $mapname=&deversion(&declutter($mapname));
1.31 www 7671: my %hash;
1.620 albertel 7672: if (($env{'request.course.fn'}) && (%newhash)) {
7673: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7674: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7675: foreach my $url (keys %newhash) {
7676: next if ($url eq 'last_known'
7677: && $env{'form.no_update_last_known'});
7678: $hash{declutter($url)}=&encode_symb($mapname,
7679: $newhash{$url}->[1],
7680: $newhash{$url}->[0]);
1.191 harris41 7681: }
1.31 www 7682: if (untie(%hash)) {
7683: return 'ok';
7684: }
7685: }
7686: }
7687: return 'error';
1.212 www 7688: }
7689:
7690: # --------------------------------------------------------------- Verify a symb
7691:
7692: sub symbverify {
1.510 www 7693: my ($symb,$thisurl)=@_;
7694: my $thisfn=$thisurl;
1.439 www 7695: $thisfn=&declutter($thisfn);
1.215 www 7696: # direct jump to resource in page or to a sequence - will construct own symbs
7697: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7698: # check URL part
1.409 www 7699: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7700:
1.431 www 7701: unless ($url eq $thisfn) { return 0; }
1.213 www 7702:
1.216 www 7703: $symb=&symbclean($symb);
1.510 www 7704: $thisurl=&deversion($thisurl);
1.439 www 7705: $thisfn=&deversion($thisfn);
1.213 www 7706:
7707: my %bighash;
7708: my $okay=0;
1.431 www 7709:
1.620 albertel 7710: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7711: &GDBM_READER(),0640)) {
1.510 www 7712: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7713: unless ($ids) {
1.510 www 7714: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7715: }
7716: if ($ids) {
7717: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7718: foreach my $id (split(/\,/,$ids)) {
7719: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7720: if (
7721: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7722: eq $symb) {
1.620 albertel 7723: if (($env{'request.role.adv'}) ||
1.800 albertel 7724: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7725: $okay=1;
7726: }
7727: }
1.216 www 7728: }
7729: }
1.213 www 7730: untie(%bighash);
7731: }
7732: return $okay;
1.31 www 7733: }
7734:
1.210 www 7735: # --------------------------------------------------------------- Clean-up symb
7736:
7737: sub symbclean {
7738: my $symb=shift;
1.568 albertel 7739: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7740: # remove version from map
7741: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7742:
1.210 www 7743: # remove version from URL
7744: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7745:
1.507 www 7746: # remove wrapper
7747:
1.510 www 7748: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7749: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7750: return $symb;
1.409 www 7751: }
7752:
7753: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7754:
7755: sub encode_symb {
7756: my ($map,$resid,$url)=@_;
7757: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7758: }
1.409 www 7759:
7760: sub decode_symb {
1.568 albertel 7761: my $symb=shift;
7762: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7763: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7764: return (&fixversion($map),$resid,&fixversion($url));
7765: }
7766:
7767: sub fixversion {
7768: my $fn=shift;
1.609 banghart 7769: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7770: my %bighash;
7771: my $uri=&clutter($fn);
1.620 albertel 7772: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7773: # is this cached?
1.599 albertel 7774: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7775: if (defined($cached)) { return $result; }
7776: # unfortunately not cached, or expired
1.620 albertel 7777: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7778: &GDBM_READER(),0640)) {
7779: if ($bighash{'version_'.$uri}) {
7780: my $version=$bighash{'version_'.$uri};
1.444 www 7781: unless (($version eq 'mostrecent') ||
7782: ($version==&getversion($uri))) {
1.440 www 7783: $uri=~s/\.(\w+)$/\.$version\.$1/;
7784: }
7785: }
7786: untie %bighash;
1.413 www 7787: }
1.599 albertel 7788: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7789: }
7790:
7791: sub deversion {
7792: my $url=shift;
7793: $url=~s/\.\d+\.(\w+)$/\.$1/;
7794: return $url;
1.210 www 7795: }
7796:
1.31 www 7797: # ------------------------------------------------------ Return symb list entry
7798:
7799: sub symbread {
1.249 www 7800: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7801: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7802: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7803: # no filename provided? try from environment
1.44 www 7804: unless ($thisfn) {
1.620 albertel 7805: if ($env{'request.symb'}) {
7806: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7807: }
1.620 albertel 7808: $thisfn=$env{'request.filename'};
1.44 www 7809: }
1.569 albertel 7810: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7811: # is that filename actually a symb? Verify, clean, and return
7812: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7813: if (&symbverify($thisfn,$1)) {
1.620 albertel 7814: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7815: }
1.242 www 7816: }
1.44 www 7817: $thisfn=declutter($thisfn);
1.31 www 7818: my %hash;
1.37 www 7819: my %bighash;
7820: my $syval='';
1.620 albertel 7821: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7822: my $targetfn = $thisfn;
1.609 banghart 7823: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7824: $targetfn = 'adm/wrapper/'.$thisfn;
7825: }
1.687 albertel 7826: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7827: $targetfn=$1;
7828: }
1.620 albertel 7829: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7830: &GDBM_READER(),0640)) {
1.481 raeburn 7831: $syval=$hash{$targetfn};
1.37 www 7832: untie(%hash);
7833: }
7834: # ---------------------------------------------------------- There was an entry
7835: if ($syval) {
1.601 albertel 7836: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7837: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 7838: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7839: #return $env{$cache_str}='';
1.601 albertel 7840: #}
7841: #$syval.=$1;
7842: #}
1.37 www 7843: } else {
7844: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7845: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7846: &GDBM_READER(),0640)) {
1.37 www 7847: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7848: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7849: unless ($ids) {
7850: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7851: }
7852: unless ($ids) {
7853: # alias?
7854: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7855: }
1.37 www 7856: if ($ids) {
7857: # ------------------------------------------------------------------- Has ID(s)
7858: my @possibilities=split(/\,/,$ids);
1.39 www 7859: if ($#possibilities==0) {
7860: # ----------------------------------------------- There is only one possibility
1.37 www 7861: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7862: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7863: $resid,$thisfn);
1.249 www 7864: } elsif (!$donotrecurse) {
1.39 www 7865: # ------------------------------------------ There is more than one possibility
7866: my $realpossible=0;
1.800 albertel 7867: foreach my $id (@possibilities) {
7868: my $file=$bighash{'src_'.$id};
1.39 www 7869: if (&allowed('bre',$file)) {
1.800 albertel 7870: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7871: if ($bighash{'map_type_'.$mapid} ne 'page') {
7872: $realpossible++;
1.626 albertel 7873: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7874: $resid,$thisfn);
1.39 www 7875: }
7876: }
1.191 harris41 7877: }
1.39 www 7878: if ($realpossible!=1) { $syval=''; }
1.249 www 7879: } else {
7880: $syval='';
1.37 www 7881: }
7882: }
7883: untie(%bighash)
1.481 raeburn 7884: }
1.31 www 7885: }
1.62 www 7886: if ($syval) {
1.620 albertel 7887: return $env{$cache_str}=$syval;
1.62 www 7888: }
1.31 www 7889: }
1.949 raeburn 7890: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7891: return $env{$cache_str}='';
1.31 www 7892: }
7893:
7894: # ---------------------------------------------------------- Return random seed
7895:
1.32 www 7896: sub numval {
7897: my $txt=shift;
7898: $txt=~tr/A-J/0-9/;
7899: $txt=~tr/a-j/0-9/;
7900: $txt=~tr/K-T/0-9/;
7901: $txt=~tr/k-t/0-9/;
7902: $txt=~tr/U-Z/0-5/;
7903: $txt=~tr/u-z/0-5/;
7904: $txt=~s/\D//g;
1.564 albertel 7905: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7906: return int($txt);
1.368 albertel 7907: }
7908:
1.484 albertel 7909: sub numval2 {
7910: my $txt=shift;
7911: $txt=~tr/A-J/0-9/;
7912: $txt=~tr/a-j/0-9/;
7913: $txt=~tr/K-T/0-9/;
7914: $txt=~tr/k-t/0-9/;
7915: $txt=~tr/U-Z/0-5/;
7916: $txt=~tr/u-z/0-5/;
7917: $txt=~s/\D//g;
7918: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7919: my $total;
7920: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7921: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7922: return int($total);
7923: }
7924:
1.575 albertel 7925: sub numval3 {
7926: use integer;
7927: my $txt=shift;
7928: $txt=~tr/A-J/0-9/;
7929: $txt=~tr/a-j/0-9/;
7930: $txt=~tr/K-T/0-9/;
7931: $txt=~tr/k-t/0-9/;
7932: $txt=~tr/U-Z/0-5/;
7933: $txt=~tr/u-z/0-5/;
7934: $txt=~s/\D//g;
7935: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7936: my $total;
7937: foreach my $val (@txts) { $total+=$val; }
7938: if ($_64bit) { $total=(($total<<32)>>32); }
7939: return $total;
7940: }
7941:
1.675 albertel 7942: sub digest {
7943: my ($data)=@_;
7944: my $digest=&Digest::MD5::md5($data);
7945: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7946: my ($e,$f);
7947: {
7948: use integer;
7949: $e=($a+$b);
7950: $f=($c+$d);
7951: if ($_64bit) {
7952: $e=(($e<<32)>>32);
7953: $f=(($f<<32)>>32);
7954: }
7955: }
7956: if (wantarray) {
7957: return ($e,$f);
7958: } else {
7959: my $g;
7960: {
7961: use integer;
7962: $g=($e+$f);
7963: if ($_64bit) {
7964: $g=(($g<<32)>>32);
7965: }
7966: }
7967: return $g;
7968: }
7969: }
7970:
1.368 albertel 7971: sub latest_rnd_algorithm_id {
1.675 albertel 7972: return '64bit5';
1.366 albertel 7973: }
1.32 www 7974:
1.503 albertel 7975: sub get_rand_alg {
7976: my ($courseid)=@_;
1.790 albertel 7977: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7978: if ($courseid) {
1.620 albertel 7979: return $env{"course.$courseid.rndseed"};
1.503 albertel 7980: }
7981: return &latest_rnd_algorithm_id();
7982: }
7983:
1.562 albertel 7984: sub validCODE {
7985: my ($CODE)=@_;
7986: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7987: return 0;
7988: }
7989:
1.491 albertel 7990: sub getCODE {
1.620 albertel 7991: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7992: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7993: defined($Apache::lonhomework::parsing_a_task) ) &&
7994: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7995: return $Apache::lonhomework::history{'resource.CODE'};
7996: }
7997: return undef;
7998: }
7999:
1.31 www 8000: sub rndseed {
1.155 albertel 8001: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8002: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8003: if (!defined($symb)) {
1.366 albertel 8004: unless ($symb=$wsymb) { return time; }
8005: }
8006: if (!$courseid) { $courseid=$wcourseid; }
8007: if (!$domain) { $domain=$wdomain; }
8008: if (!$username) { $username=$wusername }
1.503 albertel 8009: my $which=&get_rand_alg();
1.803 albertel 8010:
1.491 albertel 8011: if (defined(&getCODE())) {
1.675 albertel 8012: if ($which eq '64bit5') {
8013: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8014: } elsif ($which eq '64bit4') {
1.575 albertel 8015: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8016: } else {
8017: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8018: }
1.675 albertel 8019: } elsif ($which eq '64bit5') {
8020: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8021: } elsif ($which eq '64bit4') {
8022: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8023: } elsif ($which eq '64bit3') {
8024: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8025: } elsif ($which eq '64bit2') {
8026: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8027: } elsif ($which eq '64bit') {
8028: return &rndseed_64bit($symb,$courseid,$domain,$username);
8029: }
8030: return &rndseed_32bit($symb,$courseid,$domain,$username);
8031: }
8032:
8033: sub rndseed_32bit {
8034: my ($symb,$courseid,$domain,$username)=@_;
8035: {
8036: use integer;
8037: my $symbchck=unpack("%32C*",$symb) << 27;
8038: my $symbseed=numval($symb) << 22;
8039: my $namechck=unpack("%32C*",$username) << 17;
8040: my $nameseed=numval($username) << 12;
8041: my $domainseed=unpack("%32C*",$domain) << 7;
8042: my $courseseed=unpack("%32C*",$courseid);
8043: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8044: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8045: #&logthis("rndseed :$num:$symb");
1.564 albertel 8046: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8047: return $num;
8048: }
8049: }
8050:
8051: sub rndseed_64bit {
8052: my ($symb,$courseid,$domain,$username)=@_;
8053: {
8054: use integer;
8055: my $symbchck=unpack("%32S*",$symb) << 21;
8056: my $symbseed=numval($symb) << 10;
8057: my $namechck=unpack("%32S*",$username);
8058:
8059: my $nameseed=numval($username) << 21;
8060: my $domainseed=unpack("%32S*",$domain) << 10;
8061: my $courseseed=unpack("%32S*",$courseid);
8062:
8063: my $num1=$symbchck+$symbseed+$namechck;
8064: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8065: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8066: #&logthis("rndseed :$num:$symb");
1.564 albertel 8067: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8068: return "$num1,$num2";
1.155 albertel 8069: }
1.366 albertel 8070: }
8071:
1.443 albertel 8072: sub rndseed_64bit2 {
8073: my ($symb,$courseid,$domain,$username)=@_;
8074: {
8075: use integer;
8076: # strings need to be an even # of cahracters long, it it is odd the
8077: # last characters gets thrown away
8078: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8079: my $symbseed=numval($symb) << 10;
8080: my $namechck=unpack("%32S*",$username.' ');
8081:
8082: my $nameseed=numval($username) << 21;
1.501 albertel 8083: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8084: my $courseseed=unpack("%32S*",$courseid.' ');
8085:
8086: my $num1=$symbchck+$symbseed+$namechck;
8087: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8088: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8089: #&logthis("rndseed :$num:$symb");
1.803 albertel 8090: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8091: return "$num1,$num2";
8092: }
8093: }
8094:
8095: sub rndseed_64bit3 {
8096: my ($symb,$courseid,$domain,$username)=@_;
8097: {
8098: use integer;
8099: # strings need to be an even # of cahracters long, it it is odd the
8100: # last characters gets thrown away
8101: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8102: my $symbseed=numval2($symb) << 10;
8103: my $namechck=unpack("%32S*",$username.' ');
8104:
8105: my $nameseed=numval2($username) << 21;
1.443 albertel 8106: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8107: my $courseseed=unpack("%32S*",$courseid.' ');
8108:
8109: my $num1=$symbchck+$symbseed+$namechck;
8110: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8111: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8112: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8113: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8114:
1.503 albertel 8115: return "$num1:$num2";
1.443 albertel 8116: }
8117: }
8118:
1.575 albertel 8119: sub rndseed_64bit4 {
8120: my ($symb,$courseid,$domain,$username)=@_;
8121: {
8122: use integer;
8123: # strings need to be an even # of cahracters long, it it is odd the
8124: # last characters gets thrown away
8125: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8126: my $symbseed=numval3($symb) << 10;
8127: my $namechck=unpack("%32S*",$username.' ');
8128:
8129: my $nameseed=numval3($username) << 21;
8130: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8131: my $courseseed=unpack("%32S*",$courseid.' ');
8132:
8133: my $num1=$symbchck+$symbseed+$namechck;
8134: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8135: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8136: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8137: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8138:
8139: return "$num1:$num2";
8140: }
8141: }
8142:
1.675 albertel 8143: sub rndseed_64bit5 {
8144: my ($symb,$courseid,$domain,$username)=@_;
8145: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8146: return "$num1:$num2";
8147: }
8148:
1.366 albertel 8149: sub rndseed_CODE_64bit {
8150: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8151: {
1.366 albertel 8152: use integer;
1.443 albertel 8153: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8154: my $symbseed=numval2($symb);
1.491 albertel 8155: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8156: my $CODEseed=numval(&getCODE());
1.443 albertel 8157: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8158: my $num1=$symbseed+$CODEchck;
8159: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8160: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8161: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8162: if ($_64bit) { $num1=(($num1<<32)>>32); }
8163: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8164: return "$num1:$num2";
1.366 albertel 8165: }
8166: }
8167:
1.575 albertel 8168: sub rndseed_CODE_64bit4 {
8169: my ($symb,$courseid,$domain,$username)=@_;
8170: {
8171: use integer;
8172: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8173: my $symbseed=numval3($symb);
8174: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8175: my $CODEseed=numval3(&getCODE());
8176: my $courseseed=unpack("%32S*",$courseid.' ');
8177: my $num1=$symbseed+$CODEchck;
8178: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8179: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8180: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8181: if ($_64bit) { $num1=(($num1<<32)>>32); }
8182: if ($_64bit) { $num2=(($num2<<32)>>32); }
8183: return "$num1:$num2";
8184: }
8185: }
8186:
1.675 albertel 8187: sub rndseed_CODE_64bit5 {
8188: my ($symb,$courseid,$domain,$username)=@_;
8189: my $code = &getCODE();
8190: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8191: return "$num1:$num2";
8192: }
8193:
1.366 albertel 8194: sub setup_random_from_rndseed {
8195: my ($rndseed)=@_;
1.503 albertel 8196: if ($rndseed =~/([,:])/) {
8197: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8198: &Math::Random::random_set_seed(abs($num1),abs($num2));
8199: } else {
8200: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8201: }
1.36 albertel 8202: }
8203:
1.474 albertel 8204: sub latest_receipt_algorithm_id {
1.835 albertel 8205: return 'receipt3';
1.474 albertel 8206: }
8207:
1.480 www 8208: sub recunique {
8209: my $fucourseid=shift;
8210: my $unique;
1.835 albertel 8211: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8212: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8213: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8214: } else {
8215: $unique=$perlvar{'lonReceipt'};
8216: }
8217: return unpack("%32C*",$unique);
8218: }
8219:
8220: sub recprefix {
8221: my $fucourseid=shift;
8222: my $prefix;
1.835 albertel 8223: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8224: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8225: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8226: } else {
8227: $prefix=$perlvar{'lonHostID'};
8228: }
8229: return unpack("%32C*",$prefix);
8230: }
8231:
1.76 www 8232: sub ireceipt {
1.474 albertel 8233: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8234:
8235: my $return =&recprefix($fucourseid).'-';
8236:
8237: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8238: $env{'request.state'} eq 'construct') {
8239: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8240: return $return;
8241: }
8242:
1.76 www 8243: my $cuname=unpack("%32C*",$funame);
8244: my $cudom=unpack("%32C*",$fudom);
8245: my $cucourseid=unpack("%32C*",$fucourseid);
8246: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8247: my $cunique=&recunique($fucourseid);
1.474 albertel 8248: my $cpart=unpack("%32S*",$part);
1.835 albertel 8249: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8250:
1.790 albertel 8251: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8252:
8253: $return.= ($cunique%$cuname+
8254: $cunique%$cudom+
8255: $cusymb%$cuname+
8256: $cusymb%$cudom+
8257: $cucourseid%$cuname+
8258: $cucourseid%$cudom+
8259: $cpart%$cuname+
8260: $cpart%$cudom);
8261: } else {
8262: $return.= ($cunique%$cuname+
8263: $cunique%$cudom+
8264: $cusymb%$cuname+
8265: $cusymb%$cudom+
8266: $cucourseid%$cuname+
8267: $cucourseid%$cudom);
8268: }
8269: return $return;
1.76 www 8270: }
8271:
8272: sub receipt {
1.474 albertel 8273: my ($part)=@_;
1.790 albertel 8274: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8275: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8276: }
1.260 ng 8277:
1.790 albertel 8278: sub whichuser {
8279: my ($passedsymb)=@_;
8280: my ($symb,$courseid,$domain,$name,$publicuser);
8281: if (defined($env{'form.grade_symb'})) {
8282: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8283: my $allowed=&allowed('vgr',$tmp_courseid);
8284: if (!$allowed &&
8285: exists($env{'request.course.sec'}) &&
8286: $env{'request.course.sec'} !~ /^\s*$/) {
8287: $allowed=&allowed('vgr',$tmp_courseid.
8288: '/'.$env{'request.course.sec'});
8289: }
8290: if ($allowed) {
8291: ($symb)=&get_env_multiple('form.grade_symb');
8292: $courseid=$tmp_courseid;
8293: ($domain)=&get_env_multiple('form.grade_domain');
8294: ($name)=&get_env_multiple('form.grade_username');
8295: return ($symb,$courseid,$domain,$name,$publicuser);
8296: }
8297: }
8298: if (!$passedsymb) {
8299: $symb=&symbread();
8300: } else {
8301: $symb=$passedsymb;
8302: }
8303: $courseid=$env{'request.course.id'};
8304: $domain=$env{'user.domain'};
8305: $name=$env{'user.name'};
8306: if ($name eq 'public' && $domain eq 'public') {
8307: if (!defined($env{'form.username'})) {
8308: $env{'form.username'}.=time.rand(10000000);
8309: }
8310: $name.=$env{'form.username'};
8311: }
8312: return ($symb,$courseid,$domain,$name,$publicuser);
8313:
8314: }
8315:
1.36 albertel 8316: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8317: # returns either the contents of the file or
8318: # -1 if the file doesn't exist
1.481 raeburn 8319: #
8320: # if the target is a file that was uploaded via DOCS,
8321: # a check will be made to see if a current copy exists on the local server,
8322: # if it does this will be served, otherwise a copy will be retrieved from
8323: # the home server for the course and stored in /home/httpd/html/userfiles on
8324: # the local server.
1.472 albertel 8325:
1.36 albertel 8326: sub getfile {
1.538 albertel 8327: my ($file) = @_;
1.609 banghart 8328: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8329: &repcopy($file);
8330: return &readfile($file);
8331: }
8332:
8333: sub repcopy_userfile {
8334: my ($file)=@_;
1.609 banghart 8335: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8336: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8337: my ($cdom,$cnum,$filename) =
1.811 albertel 8338: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8339: my $uri="/uploaded/$cdom/$cnum/$filename";
8340: if (-e "$file") {
1.828 www 8341: # we already have a local copy, check it out
1.538 albertel 8342: my @fileinfo = stat($file);
1.828 www 8343: my $rtncode;
8344: my $info;
1.538 albertel 8345: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8346: if ($lwpresp ne 'ok') {
1.828 www 8347: # there is no such file anymore, even though we had a local copy
1.482 albertel 8348: if ($rtncode eq '404') {
1.538 albertel 8349: unlink($file);
1.482 albertel 8350: }
8351: return -1;
8352: }
8353: if ($info < $fileinfo[9]) {
1.828 www 8354: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8355: return 'ok';
1.828 www 8356: } else {
8357: # the file is outdated, get rid of it
8358: unlink($file);
1.482 albertel 8359: }
1.828 www 8360: }
8361: # one way or the other, at this point, we don't have the file
8362: # construct the correct path for the file
8363: my @parts = ($cdom,$cnum);
8364: if ($filename =~ m|^(.+)/[^/]+$|) {
8365: push @parts, split(/\//,$1);
8366: }
8367: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8368: foreach my $part (@parts) {
8369: $path .= '/'.$part;
8370: if (!-e $path) {
8371: mkdir($path,0770);
1.482 albertel 8372: }
8373: }
1.828 www 8374: # now the path exists for sure
8375: # get a user agent
8376: my $ua=new LWP::UserAgent;
8377: my $transferfile=$file.'.in.transfer';
8378: # FIXME: this should flock
8379: if (-e $transferfile) { return 'ok'; }
8380: my $request;
8381: $uri=~s/^\///;
1.980 raeburn 8382: my $homeserver = &homeserver($cnum,$cdom);
8383: my $protocol = $protocol{$homeserver};
8384: $protocol = 'http' if ($protocol ne 'https');
8385: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8386: my $response=$ua->request($request,$transferfile);
8387: # did it work?
8388: if ($response->is_error()) {
8389: unlink($transferfile);
8390: &logthis("Userfile repcopy failed for $uri");
8391: return -1;
8392: }
8393: # worked, rename the transfer file
8394: rename($transferfile,$file);
1.607 raeburn 8395: return 'ok';
1.481 raeburn 8396: }
8397:
1.517 albertel 8398: sub tokenwrapper {
8399: my $uri=shift;
1.980 raeburn 8400: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8401: $uri=~s|^/||;
1.620 albertel 8402: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8403: my $token=$1;
1.552 albertel 8404: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8405: if ($udom && $uname && $file) {
8406: $file=~s|(\?\.*)*$||;
1.949 raeburn 8407: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 8408: my $homeserver = &homeserver($uname,$udom);
8409: my $protocol = $protocol{$homeserver};
8410: $protocol = 'http' if ($protocol ne 'https');
8411: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8412: (($uri=~/\?/)?'&':'?').'token='.$token.
8413: '&tokenissued='.$perlvar{'lonHostID'};
8414: } else {
8415: return '/adm/notfound.html';
8416: }
8417: }
8418:
1.828 www 8419: # call with reqtype HEAD: get last modification time
8420: # call with reqtype GET: get the file contents
8421: # Do not call this with reqtype GET for large files! It loads everything into memory
8422: #
1.481 raeburn 8423: sub getuploaded {
8424: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8425: $uri=~s/^\///;
1.980 raeburn 8426: my $homeserver = &homeserver($cnum,$cdom);
8427: my $protocol = $protocol{$homeserver};
8428: $protocol = 'http' if ($protocol ne 'https');
8429: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8430: my $ua=new LWP::UserAgent;
8431: my $request=new HTTP::Request($reqtype,$uri);
8432: my $response=$ua->request($request);
8433: $$rtncode = $response->code;
1.482 albertel 8434: if (! $response->is_success()) {
8435: return 'failed';
8436: }
8437: if ($reqtype eq 'HEAD') {
1.486 www 8438: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8439: } elsif ($reqtype eq 'GET') {
8440: $$info = $response->content;
1.472 albertel 8441: }
1.482 albertel 8442: return 'ok';
1.36 albertel 8443: }
8444:
1.481 raeburn 8445: sub readfile {
8446: my $file = shift;
8447: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8448: my $fh;
8449: open($fh,"<$file");
8450: my $a='';
1.800 albertel 8451: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8452: return $a;
8453: }
8454:
1.36 albertel 8455: sub filelocation {
1.590 banghart 8456: my ($dir,$file) = @_;
8457: my $location;
8458: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8459:
8460: if ($file =~ m-^/adm/-) {
8461: $file=~s-^/adm/wrapper/-/-;
8462: $file=~s-^/adm/coursedocs/showdoc/-/-;
8463: }
1.882 albertel 8464:
1.590 banghart 8465: if ($file=~m:^/~:) { # is a contruction space reference
8466: $location = $file;
8467: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8468: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8469: # is a correct contruction space reference
8470: $location = $file;
1.956 raeburn 8471: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8472: $location = $file;
1.609 banghart 8473: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8474: my ($udom,$uname,$filename)=
1.811 albertel 8475: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8476: my $home=&homeserver($uname,$udom);
8477: my $is_me=0;
8478: my @ids=¤t_machine_ids();
8479: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8480: if ($is_me) {
1.955 raeburn 8481: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8482: } else {
8483: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8484: $udom.'/'.$uname.'/'.$filename;
8485: }
1.882 albertel 8486: } elsif ($file =~ m-^/adm/-) {
8487: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8488: } else {
8489: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8490: $file=~s:^/res/:/:;
8491: if ( !( $file =~ m:^/:) ) {
8492: $location = $dir. '/'.$file;
8493: } else {
8494: $location = '/home/httpd/html/res'.$file;
8495: }
1.59 albertel 8496: }
1.590 banghart 8497: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8498: while ($location=~m{/\.\./}) {
8499: if ($location =~ m{/[^/]+/\.\./}) {
8500: $location=~ s{/[^/]+/\.\./}{/}g;
8501: } else {
8502: $location=~ s{/\.\./}{/}g;
8503: }
8504: } #remove dir/..
1.590 banghart 8505: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8506: return $location;
1.46 www 8507: }
1.36 albertel 8508:
1.46 www 8509: sub hreflocation {
8510: my ($dir,$file)=@_;
1.980 raeburn 8511: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8512: $file=filelocation($dir,$file);
1.700 albertel 8513: } elsif ($file=~m-^/adm/-) {
8514: $file=~s-^/adm/wrapper/-/-;
8515: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8516: }
8517: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8518: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8519: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8520: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8521: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8522: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8523: -/uploaded/$1/$2/-x;
1.46 www 8524: }
1.913 albertel 8525: if ($file=~ m{^/userfiles/}) {
8526: $file =~ s{^/userfiles/}{/uploaded/};
8527: }
1.462 albertel 8528: return $file;
1.465 albertel 8529: }
8530:
8531: sub current_machine_domains {
1.853 albertel 8532: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8533: }
8534:
8535: sub machine_domains {
8536: my ($hostname) = @_;
1.465 albertel 8537: my @domains;
1.838 albertel 8538: my %hostname = &all_hostnames();
1.465 albertel 8539: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8540: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8541: if ($hostname eq $name) {
1.844 albertel 8542: push(@domains,&host_domain($id));
1.465 albertel 8543: }
8544: }
8545: return @domains;
8546: }
8547:
8548: sub current_machine_ids {
1.853 albertel 8549: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8550: }
8551:
8552: sub machine_ids {
8553: my ($hostname) = @_;
8554: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8555: my @ids;
1.888 albertel 8556: my %name_to_host = &all_names();
1.889 albertel 8557: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8558: return @{ $name_to_host{$hostname} };
8559: }
8560: return;
1.31 www 8561: }
8562:
1.824 raeburn 8563: sub additional_machine_domains {
8564: my @domains;
8565: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8566: while( my $line = <$fh>) {
8567: $line =~ s/\s//g;
8568: push(@domains,$line);
8569: }
8570: return @domains;
8571: }
8572:
8573: sub default_login_domain {
8574: my $domain = $perlvar{'lonDefDomain'};
8575: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8576: foreach my $posdom (¤t_machine_domains(),
8577: &additional_machine_domains()) {
8578: if (lc($posdom) eq lc($testdomain)) {
8579: $domain=$posdom;
8580: last;
8581: }
8582: }
8583: return $domain;
8584: }
8585:
1.31 www 8586: # ------------------------------------------------------------- Declutters URLs
8587:
8588: sub declutter {
8589: my $thisfn=shift;
1.569 albertel 8590: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8591: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8592: $thisfn=~s/^\///;
1.697 albertel 8593: $thisfn=~s|^adm/wrapper/||;
8594: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8595: $thisfn=~s/^res\///;
1.235 www 8596: $thisfn=~s/\?.+$//;
1.268 www 8597: return $thisfn;
8598: }
8599:
8600: # ------------------------------------------------------------- Clutter up URLs
8601:
8602: sub clutter {
8603: my $thisfn='/'.&declutter(shift);
1.887 albertel 8604: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8605: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8606: $thisfn='/res'.$thisfn;
8607: }
1.694 albertel 8608: if ($thisfn !~m|/adm|) {
1.695 albertel 8609: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8610: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8611: } else {
8612: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8613: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8614: if ($embstyle eq 'ssi'
8615: || ($embstyle eq 'hdn')
8616: || ($embstyle eq 'rat')
8617: || ($embstyle eq 'prv')
8618: || ($embstyle eq 'ign')) {
8619: #do nothing with these
8620: } elsif (($embstyle eq 'img')
1.695 albertel 8621: || ($embstyle eq 'emb')
8622: || ($embstyle eq 'wrp')) {
8623: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8624: } elsif ($embstyle eq 'unk'
8625: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8626: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8627: } else {
1.718 www 8628: # &logthis("Got a blank emb style");
1.695 albertel 8629: }
1.694 albertel 8630: }
8631: }
1.31 www 8632: return $thisfn;
1.12 www 8633: }
8634:
1.787 albertel 8635: sub clutter_with_no_wrapper {
8636: my $uri = &clutter(shift);
8637: if ($uri =~ m-^/adm/-) {
8638: $uri =~ s-^/adm/wrapper/-/-;
8639: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8640: }
8641: return $uri;
8642: }
8643:
1.557 albertel 8644: sub freeze_escape {
8645: my ($value)=@_;
8646: if (ref($value)) {
8647: $value=&nfreeze($value);
8648: return '__FROZEN__'.&escape($value);
8649: }
8650: return &escape($value);
8651: }
8652:
1.11 www 8653:
1.557 albertel 8654: sub thaw_unescape {
8655: my ($value)=@_;
8656: if ($value =~ /^__FROZEN__/) {
8657: substr($value,0,10,undef);
8658: $value=&unescape($value);
8659: return &thaw($value);
8660: }
8661: return &unescape($value);
8662: }
8663:
1.436 albertel 8664: sub correct_line_ends {
8665: my ($result)=@_;
8666: $$result =~s/\r\n/\n/mg;
8667: $$result =~s/\r/\n/mg;
1.415 albertel 8668: }
1.1 albertel 8669: # ================================================================ Main Program
8670:
1.184 www 8671: sub goodbye {
1.204 albertel 8672: &logthis("Starting Shut down");
1.443 albertel 8673: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8674: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8675: #converted
1.599 albertel 8676: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8677: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8678: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8679: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8680: #1.1 only
1.870 albertel 8681: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8682: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8683: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8684: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8685: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8686: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8687: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8688: &flushcourselogs();
8689: &logthis("Shutting down");
8690: }
8691:
1.852 albertel 8692: sub get_dns {
1.869 albertel 8693: my ($url,$func,$ignore_cache) = @_;
8694: if (!$ignore_cache) {
8695: my ($content,$cached)=
8696: &Apache::lonnet::is_cached_new('dns',$url);
8697: if ($cached) {
8698: &$func($content);
8699: return;
8700: }
8701: }
8702:
8703: my %alldns;
1.852 albertel 8704: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8705: foreach my $dns (<$config>) {
8706: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 8707: my $line = $1;
8708: my ($host,$protocol) = split(/:/,$line);
8709: if ($protocol ne 'https') {
8710: $protocol = 'http';
8711: }
8712: $alldns{$host} = $protocol;
1.869 albertel 8713: }
8714: while (%alldns) {
8715: my ($dns) = keys(%alldns);
1.852 albertel 8716: my $ua=new LWP::UserAgent;
1.979 raeburn 8717: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 8718: my $response=$ua->request($request);
1.979 raeburn 8719: delete($alldns{$dns});
1.852 albertel 8720: next if ($response->is_error());
8721: my @content = split("\n",$response->content);
1.869 albertel 8722: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8723: &$func(\@content);
1.869 albertel 8724: return;
1.852 albertel 8725: }
8726: close($config);
1.871 albertel 8727: my $which = (split('/',$url))[3];
8728: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8729: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8730: my @content = <$config>;
8731: &$func(\@content);
8732: return;
1.852 albertel 8733: }
1.327 albertel 8734: # ------------------------------------------------------------ Read domain file
8735: {
1.852 albertel 8736: my $loaded;
1.846 albertel 8737: my %domain;
8738:
1.852 albertel 8739: sub parse_domain_tab {
8740: my ($lines) = @_;
8741: foreach my $line (@$lines) {
8742: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8743:
1.846 albertel 8744: chomp($line);
1.852 albertel 8745: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8746: my %this_domain;
8747: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8748: 'lang_def', 'city', 'longi', 'lati',
8749: 'primary') {
8750: $this_domain{$field} = shift(@elements);
8751: }
8752: $domain{$name} = \%this_domain;
1.852 albertel 8753: }
8754: }
1.864 albertel 8755:
8756: sub reset_domain_info {
8757: undef($loaded);
8758: undef(%domain);
8759: }
8760:
1.852 albertel 8761: sub load_domain_tab {
1.869 albertel 8762: my ($ignore_cache) = @_;
8763: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8764: my $fh;
8765: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8766: my @lines = <$fh>;
8767: &parse_domain_tab(\@lines);
1.448 albertel 8768: }
1.852 albertel 8769: close($fh);
8770: $loaded = 1;
1.327 albertel 8771: }
1.846 albertel 8772:
8773: sub domain {
1.852 albertel 8774: &load_domain_tab() if (!$loaded);
8775:
1.846 albertel 8776: my ($name,$what) = @_;
8777: return if ( !exists($domain{$name}) );
8778:
8779: if (!$what) {
8780: return $domain{$name}{'description'};
8781: }
8782: return $domain{$name}{$what};
8783: }
1.974 raeburn 8784:
8785: sub domain_info {
8786: &load_domain_tab() if (!$loaded);
8787: return %domain;
8788: }
8789:
1.327 albertel 8790: }
8791:
8792:
1.1 albertel 8793: # ------------------------------------------------------------- Read hosts file
8794: {
1.838 albertel 8795: my %hostname;
1.844 albertel 8796: my %hostdom;
1.845 albertel 8797: my %libserv;
1.852 albertel 8798: my $loaded;
1.888 albertel 8799: my %name_to_host;
1.852 albertel 8800:
8801: sub parse_hosts_tab {
8802: my ($file) = @_;
8803: foreach my $configline (@$file) {
8804: next if ($configline =~ /^(\#|\s*$ )/x);
8805: next if ($configline =~ /^\^/);
8806: chomp($configline);
1.968 raeburn 8807: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 8808: $name=~s/\s//g;
8809: if ($id && $domain && $role && $name) {
8810: $hostname{$id}=$name;
1.888 albertel 8811: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8812: $hostdom{$id}=$domain;
8813: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 8814: if (defined($protocol)) {
8815: if ($protocol eq 'https') {
8816: $protocol{$id} = $protocol;
8817: } else {
8818: $protocol{$id} = 'http';
8819: }
1.968 raeburn 8820: } else {
1.969 raeburn 8821: $protocol{$id} = 'http';
1.968 raeburn 8822: }
1.852 albertel 8823: }
8824: }
8825: }
1.864 albertel 8826:
8827: sub reset_hosts_info {
1.897 albertel 8828: &purge_remembered();
1.864 albertel 8829: &reset_domain_info();
8830: &reset_hosts_ip_info();
1.892 albertel 8831: undef(%name_to_host);
1.864 albertel 8832: undef(%hostname);
8833: undef(%hostdom);
8834: undef(%libserv);
8835: undef($loaded);
8836: }
1.1 albertel 8837:
1.852 albertel 8838: sub load_hosts_tab {
1.869 albertel 8839: my ($ignore_cache) = @_;
8840: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8841: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8842: my @config = <$config>;
8843: &parse_hosts_tab(\@config);
8844: close($config);
8845: $loaded=1;
1.1 albertel 8846: }
1.852 albertel 8847:
1.838 albertel 8848: sub hostname {
1.852 albertel 8849: &load_hosts_tab() if (!$loaded);
8850:
1.838 albertel 8851: my ($lonid) = @_;
8852: return $hostname{$lonid};
8853: }
1.845 albertel 8854:
1.838 albertel 8855: sub all_hostnames {
1.852 albertel 8856: &load_hosts_tab() if (!$loaded);
8857:
1.838 albertel 8858: return %hostname;
8859: }
1.845 albertel 8860:
1.888 albertel 8861: sub all_names {
8862: &load_hosts_tab() if (!$loaded);
8863:
8864: return %name_to_host;
8865: }
8866:
1.974 raeburn 8867: sub all_host_domain {
8868: &load_hosts_tab() if (!$loaded);
8869: return %hostdom;
8870: }
8871:
1.845 albertel 8872: sub is_library {
1.852 albertel 8873: &load_hosts_tab() if (!$loaded);
8874:
1.845 albertel 8875: return exists($libserv{$_[0]});
8876: }
8877:
8878: sub all_library {
1.852 albertel 8879: &load_hosts_tab() if (!$loaded);
8880:
1.845 albertel 8881: return %libserv;
8882: }
8883:
1.841 albertel 8884: sub get_servers {
1.852 albertel 8885: &load_hosts_tab() if (!$loaded);
8886:
1.841 albertel 8887: my ($domain,$type) = @_;
8888: my %possible_hosts = ($type eq 'library') ? %libserv
8889: : %hostname;
8890: my %result;
1.842 albertel 8891: if (ref($domain) eq 'ARRAY') {
8892: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8893: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8894: $result{$host} = $hostname;
8895: }
8896: }
8897: } else {
8898: while ( my ($host,$hostname) = each(%possible_hosts)) {
8899: if ($hostdom{$host} eq $domain) {
8900: $result{$host} = $hostname;
8901: }
1.841 albertel 8902: }
8903: }
8904: return %result;
8905: }
1.845 albertel 8906:
1.844 albertel 8907: sub host_domain {
1.852 albertel 8908: &load_hosts_tab() if (!$loaded);
8909:
1.844 albertel 8910: my ($lonid) = @_;
8911: return $hostdom{$lonid};
8912: }
8913:
1.841 albertel 8914: sub all_domains {
1.852 albertel 8915: &load_hosts_tab() if (!$loaded);
8916:
1.841 albertel 8917: my %seen;
8918: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8919: return @uniq;
8920: }
1.1 albertel 8921: }
8922:
1.847 albertel 8923: {
8924: my %iphost;
1.856 albertel 8925: my %name_to_ip;
8926: my %lonid_to_ip;
1.869 albertel 8927:
1.847 albertel 8928: sub get_hosts_from_ip {
8929: my ($ip) = @_;
8930: my %iphosts = &get_iphost();
8931: if (ref($iphosts{$ip})) {
8932: return @{$iphosts{$ip}};
8933: }
8934: return;
1.839 albertel 8935: }
1.864 albertel 8936:
8937: sub reset_hosts_ip_info {
8938: undef(%iphost);
8939: undef(%name_to_ip);
8940: undef(%lonid_to_ip);
8941: }
1.856 albertel 8942:
8943: sub get_host_ip {
8944: my ($lonid) = @_;
8945: if (exists($lonid_to_ip{$lonid})) {
8946: return $lonid_to_ip{$lonid};
8947: }
8948: my $name=&hostname($lonid);
8949: my $ip = gethostbyname($name);
8950: return if (!$ip || length($ip) ne 4);
8951: $ip=inet_ntoa($ip);
8952: $name_to_ip{$name} = $ip;
8953: $lonid_to_ip{$lonid} = $ip;
8954: return $ip;
8955: }
1.847 albertel 8956:
8957: sub get_iphost {
1.869 albertel 8958: my ($ignore_cache) = @_;
1.894 albertel 8959:
1.869 albertel 8960: if (!$ignore_cache) {
8961: if (%iphost) {
8962: return %iphost;
8963: }
8964: my ($ip_info,$cached)=
8965: &Apache::lonnet::is_cached_new('iphost','iphost');
8966: if ($cached) {
8967: %iphost = %{$ip_info->[0]};
8968: %name_to_ip = %{$ip_info->[1]};
8969: %lonid_to_ip = %{$ip_info->[2]};
8970: return %iphost;
8971: }
8972: }
1.894 albertel 8973:
8974: # get yesterday's info for fallback
8975: my %old_name_to_ip;
8976: my ($ip_info,$cached)=
8977: &Apache::lonnet::is_cached_new('iphost','iphost');
8978: if ($cached) {
8979: %old_name_to_ip = %{$ip_info->[1]};
8980: }
8981:
1.888 albertel 8982: my %name_to_host = &all_names();
8983: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8984: my $ip;
8985: if (!exists($name_to_ip{$name})) {
8986: $ip = gethostbyname($name);
8987: if (!$ip || length($ip) ne 4) {
1.894 albertel 8988: if (defined($old_name_to_ip{$name})) {
8989: $ip = $old_name_to_ip{$name};
8990: &logthis("Can't find $name defaulting to old $ip");
8991: } else {
8992: &logthis("Name $name no IP found");
8993: next;
8994: }
8995: } else {
8996: $ip=inet_ntoa($ip);
1.847 albertel 8997: }
8998: $name_to_ip{$name} = $ip;
8999: } else {
9000: $ip = $name_to_ip{$name};
1.653 albertel 9001: }
1.888 albertel 9002: foreach my $id (@{ $name_to_host{$name} }) {
9003: $lonid_to_ip{$id} = $ip;
9004: }
9005: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9006: }
1.869 albertel 9007: &Apache::lonnet::do_cache_new('iphost','iphost',
9008: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9009: 48*60*60);
1.869 albertel 9010:
1.847 albertel 9011: return %iphost;
1.598 albertel 9012: }
9013: }
9014:
1.986 ! foxr 9015: #
! 9016: # Given a DNS returns the loncapa host name for that DNS
! 9017: #
! 9018: sub host_from_dns {
! 9019: my ($dns) = @_;
! 9020: my @hosts;
! 9021: my $ip;
! 9022:
! 9023: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
! 9024: if (length($ip) == 4) {
! 9025: $ip = &IO::Socket::inet_ntoa($ip);
! 9026: @hosts = get_hosts_from_ip($ip);
! 9027: return $hosts[0];
! 9028: }
! 9029: return undef;
! 9030: }
! 9031:
1.862 albertel 9032: BEGIN {
9033:
9034: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9035: unless ($readit) {
9036: {
9037: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9038: %perlvar = (%perlvar,%{$configvars});
9039: }
9040:
9041:
1.1 albertel 9042: # ------------------------------------------------------ Read spare server file
9043: {
1.448 albertel 9044: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9045:
9046: while (my $configline=<$config>) {
9047: chomp($configline);
1.284 matthew 9048: if ($configline) {
1.784 albertel 9049: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9050: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9051: push(@{ $spareid{$type} }, $host);
1.1 albertel 9052: }
9053: }
1.448 albertel 9054: close($config);
1.1 albertel 9055: }
1.11 www 9056: # ------------------------------------------------------------ Read permissions
9057: {
1.448 albertel 9058: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9059:
9060: while (my $configline=<$config>) {
1.448 albertel 9061: chomp($configline);
9062: if ($configline) {
9063: my ($role,$perm)=split(/ /,$configline);
9064: if ($perm ne '') { $pr{$role}=$perm; }
9065: }
1.11 www 9066: }
1.448 albertel 9067: close($config);
1.11 www 9068: }
9069:
9070: # -------------------------------------------- Read plain texts for permissions
9071: {
1.448 albertel 9072: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9073:
9074: while (my $configline=<$config>) {
1.448 albertel 9075: chomp($configline);
9076: if ($configline) {
1.742 raeburn 9077: my ($short,@plain)=split(/:/,$configline);
9078: %{$prp{$short}} = ();
9079: if (@plain > 0) {
9080: $prp{$short}{'std'} = $plain[0];
9081: for (my $i=1; $i<@plain; $i++) {
9082: $prp{$short}{'alt'.$i} = $plain[$i];
9083: }
9084: }
1.448 albertel 9085: }
1.135 www 9086: }
1.448 albertel 9087: close($config);
1.135 www 9088: }
9089:
9090: # ---------------------------------------------------------- Read package table
9091: {
1.448 albertel 9092: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9093:
9094: while (my $configline=<$config>) {
1.483 albertel 9095: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9096: chomp($configline);
9097: my ($short,$plain)=split(/:/,$configline);
9098: my ($pack,$name)=split(/\&/,$short);
9099: if ($plain ne '') {
9100: $packagetab{$pack.'&'.$name.'&name'}=$name;
9101: $packagetab{$short}=$plain;
9102: }
1.11 www 9103: }
1.448 albertel 9104: close($config);
1.329 matthew 9105: }
9106:
9107: # ------------- set up temporary directory
9108: {
9109: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9110:
1.11 www 9111: }
9112:
1.794 albertel 9113: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9114: 'compress_threshold'=> 20_000,
9115: });
1.185 www 9116:
1.281 www 9117: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9118: $dumpcount=0;
1.958 www 9119: $locknum=0;
1.22 www 9120:
1.163 harris41 9121: &logtouch();
1.672 albertel 9122: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9123: $readit=1;
1.564 albertel 9124: {
9125: use integer;
9126: my $test=(2**32)+1;
1.568 albertel 9127: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9128: &logthis(" Detected 64bit platform ($_64bit)");
9129: }
1.195 www 9130: }
1.1 albertel 9131: }
1.179 www 9132:
1.1 albertel 9133: 1;
1.191 harris41 9134: __END__
9135:
1.243 albertel 9136: =pod
9137:
1.191 harris41 9138: =head1 NAME
9139:
1.243 albertel 9140: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9141:
9142: =head1 SYNOPSIS
9143:
1.243 albertel 9144: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9145:
9146: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9147:
1.243 albertel 9148: Common parameters:
9149:
9150: =over 4
9151:
9152: =item *
9153:
9154: $uname : an internal username (if $cname expecting a course Id specifically)
9155:
9156: =item *
9157:
9158: $udom : a domain (if $cdom expecting a course's domain specifically)
9159:
9160: =item *
9161:
9162: $symb : a resource instance identifier
9163:
9164: =item *
9165:
9166: $namespace : the name of a .db file that contains the data needed or
9167: being set.
9168:
9169: =back
9170:
1.394 bowersj2 9171: =head1 OVERVIEW
1.191 harris41 9172:
1.394 bowersj2 9173: lonnet provides subroutines which interact with the
9174: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9175: about classes, users, and resources.
1.243 albertel 9176:
9177: For many of these objects you can also use this to store data about
9178: them or modify them in various ways.
1.191 harris41 9179:
1.394 bowersj2 9180: =head2 Symbs
1.191 harris41 9181:
1.394 bowersj2 9182: To identify a specific instance of a resource, LON-CAPA uses symbols
9183: or "symbs"X<symb>. These identifiers are built from the URL of the
9184: map, the resource number of the resource in the map, and the URL of
9185: the resource itself. The latter is somewhat redundant, but might help
9186: if maps change.
9187:
9188: An example is
9189:
9190: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9191:
9192: The respective map entry is
9193:
9194: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9195: title="Problem 2">
9196: </resource>
9197:
9198: Symbs are used by the random number generator, as well as to store and
9199: restore data specific to a certain instance of for example a problem.
9200:
9201: =head2 Storing And Retrieving Data
9202:
9203: X<store()>X<cstore()>X<restore()>Three of the most important functions
9204: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9205: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9206: is is the non-critical message twin of cstore. These functions are for
9207: handlers to store a perl hash to a user's permanent data space in an
9208: easy manner, and to retrieve it again on another call. It is expected
9209: that a handler would use this once at the beginning to retrieve data,
9210: and then again once at the end to send only the new data back.
9211:
9212: The data is stored in the user's data directory on the user's
9213: homeserver under the ID of the course.
9214:
9215: The hash that is returned by restore will have all of the previous
9216: value for all of the elements of the hash.
9217:
9218: Example:
9219:
9220: #creating a hash
9221: my %hash;
9222: $hash{'foo'}='bar';
9223:
9224: #storing it
9225: &Apache::lonnet::cstore(\%hash);
9226:
9227: #changing a value
9228: $hash{'foo'}='notbar';
9229:
9230: #adding a new value
9231: $hash{'bar'}='foo';
9232: &Apache::lonnet::cstore(\%hash);
9233:
9234: #retrieving the hash
9235: my %history=&Apache::lonnet::restore();
9236:
9237: #print the hash
9238: foreach my $key (sort(keys(%history))) {
9239: print("\%history{$key} = $history{$key}");
9240: }
9241:
9242: Will print out:
1.191 harris41 9243:
1.394 bowersj2 9244: %history{1:foo} = bar
9245: %history{1:keys} = foo:timestamp
9246: %history{1:timestamp} = 990455579
9247: %history{2:bar} = foo
9248: %history{2:foo} = notbar
9249: %history{2:keys} = foo:bar:timestamp
9250: %history{2:timestamp} = 990455580
9251: %history{bar} = foo
9252: %history{foo} = notbar
9253: %history{timestamp} = 990455580
9254: %history{version} = 2
9255:
9256: Note that the special hash entries C<keys>, C<version> and
9257: C<timestamp> were added to the hash. C<version> will be equal to the
9258: total number of versions of the data that have been stored. The
9259: C<timestamp> attribute will be the UNIX time the hash was
9260: stored. C<keys> is available in every historical section to list which
9261: keys were added or changed at a specific historical revision of a
9262: hash.
9263:
9264: B<Warning>: do not store the hash that restore returns directly. This
9265: will cause a mess since it will restore the historical keys as if the
9266: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9267:
1.394 bowersj2 9268: Calling convention:
1.191 harris41 9269:
1.394 bowersj2 9270: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9271: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9272:
1.394 bowersj2 9273: For more detailed information, see lonnet specific documentation.
1.191 harris41 9274:
1.394 bowersj2 9275: =head1 RETURN MESSAGES
1.191 harris41 9276:
1.394 bowersj2 9277: =over 4
1.191 harris41 9278:
1.394 bowersj2 9279: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9280:
1.394 bowersj2 9281: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9282: when the connection is brought back up
1.191 harris41 9283:
1.394 bowersj2 9284: =item * B<con_failed>: unable to contact remote host and unable to save message
9285: for later delivery
1.191 harris41 9286:
1.967 bisitz 9287: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9288:
1.394 bowersj2 9289: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9290: that was requested
1.191 harris41 9291:
1.243 albertel 9292: =back
1.191 harris41 9293:
1.243 albertel 9294: =head1 PUBLIC SUBROUTINES
1.191 harris41 9295:
1.243 albertel 9296: =head2 Session Environment Functions
1.191 harris41 9297:
1.243 albertel 9298: =over 4
1.191 harris41 9299:
1.394 bowersj2 9300: =item *
9301: X<appenv()>
1.949 raeburn 9302: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9303: the user envirnoment file, and will be restored for each access this
1.620 albertel 9304: user makes during this session, also modifies the %env for the current
1.949 raeburn 9305: process. Optional rolesarrayref - if defined contains a reference to an array
9306: of roles which are exempt from the restriction on modifying user.role entries
9307: in the user's environment.db and in %env.
1.191 harris41 9308:
9309: =item *
1.394 bowersj2 9310: X<delenv()>
9311: B<delenv($regexp)>: removes all items from the session
9312: environment file that matches the regular expression in $regexp. The
1.620 albertel 9313: values are also delted from the current processes %env.
1.191 harris41 9314:
1.795 albertel 9315: =item * get_env_multiple($name)
9316:
9317: gets $name from the %env hash, it seemlessly handles the cases where multiple
9318: values may be defined and end up as an array ref.
9319:
9320: returns an array of values
9321:
1.243 albertel 9322: =back
9323:
9324: =head2 User Information
1.191 harris41 9325:
1.243 albertel 9326: =over 4
1.191 harris41 9327:
9328: =item *
1.394 bowersj2 9329: X<queryauthenticate()>
9330: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9331: authentication scheme
9332:
9333: =item *
1.394 bowersj2 9334: X<authenticate()>
9335: B<authenticate($uname,$upass,$udom)>: try to
9336: authenticate user from domain's lib servers (first use the current
9337: one). C<$upass> should be the users password.
1.191 harris41 9338:
9339: =item *
1.394 bowersj2 9340: X<homeserver()>
9341: B<homeserver($uname,$udom)>: find the server which has
9342: the user's directory and files (there must be only one), this caches
9343: the answer, and also caches if there is a borken connection.
1.191 harris41 9344:
9345: =item *
1.394 bowersj2 9346: X<idget()>
9347: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9348: (IDs are a unique resource in a domain, there must be only 1 ID per
9349: username, and only 1 username per ID in a specific domain) (returns
9350: hash: id=>name,id=>name)
1.191 harris41 9351:
9352: =item *
1.394 bowersj2 9353: X<idrget()>
9354: B<idrget($udom,@unames)>: find the IDs behind a list of
9355: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9356:
9357: =item *
1.394 bowersj2 9358: X<idput()>
9359: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9360:
9361: =item *
1.394 bowersj2 9362: X<rolesinit()>
9363: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9364:
9365: =item *
1.551 albertel 9366: X<getsection()>
9367: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9368: course $cname, return section name/number or '' for "not in course"
9369: and '-1' for "no section"
9370:
9371: =item *
1.394 bowersj2 9372: X<userenvironment()>
9373: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9374: passed in @what from the requested user's environment, returns a hash
9375:
1.858 raeburn 9376: =item *
9377: X<userlog_query()>
1.859 albertel 9378: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9379: activity.log file. %filters defines filters applied when parsing the
9380: log file. These can be start or end timestamps, or the type of action
9381: - log to look for Login or Logout events, check for Checkin or
9382: Checkout, role for role selection. The response is in the form
9383: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9384: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9385:
1.243 albertel 9386: =back
9387:
9388: =head2 User Roles
9389:
9390: =over 4
9391:
9392: =item *
9393:
1.810 raeburn 9394: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9395: F: full access
9396: U,I,K: authentication modes (cxx only)
9397: '': forbidden
9398: 1: user needs to choose course
9399: 2: browse allowed
1.766 albertel 9400: A: passphrase authentication needed
1.243 albertel 9401:
9402: =item *
9403:
9404: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9405: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9406: and course level
9407:
9408: =item *
9409:
9410: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
9411: explanation of a user role term
9412:
1.832 raeburn 9413: =item *
9414:
1.935 raeburn 9415: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9416: All arguments are optional. Returns a hash of a roles, either for
9417: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9418: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9419: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9420: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9421: For each key, value is set to colon-separated start and end times for
9422: the role. If no username and domain are specified, will default to
1.934 raeburn 9423: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9424: of role statuses (active, future or previous), roles
9425: (e.g., cc,in, st etc.) and domains of the roles which can be used
9426: to restrict the list of roles reported. If no array ref is
9427: provided for types, will default to return only active roles.
1.834 albertel 9428:
1.243 albertel 9429: =back
9430:
9431: =head2 User Modification
9432:
9433: =over 4
9434:
9435: =item *
9436:
1.957 raeburn 9437: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9438: user for the level given by URL. Optional start and end dates (leave empty
9439: string or zero for "no date")
1.191 harris41 9440:
9441: =item *
9442:
1.243 albertel 9443: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9444: change a users, password, possible return values are: ok,
9445: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9446: refused
1.191 harris41 9447:
9448: =item *
9449:
1.243 albertel 9450: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9451:
9452: =item *
9453:
1.963 raeburn 9454: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9455: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9456: modify user
1.191 harris41 9457:
9458: =item *
9459:
1.286 matthew 9460: modifystudent
9461:
1.957 raeburn 9462: modify a student's enrollment and identification information.
1.286 matthew 9463: The course id is resolved based on the current users environment.
9464: This means the envoking user must be a course coordinator or otherwise
9465: associated with a course.
9466:
1.297 matthew 9467: This call is essentially a wrapper for lonnet::modifyuser and
9468: lonnet::modify_student_enrollment
1.286 matthew 9469:
9470: Inputs:
9471:
9472: =over 4
9473:
1.957 raeburn 9474: =item B<$udom> Student's loncapa domain
1.286 matthew 9475:
1.957 raeburn 9476: =item B<$uname> Student's loncapa login name
1.286 matthew 9477:
1.964 bisitz 9478: =item B<$uid> Student/Employee ID
1.286 matthew 9479:
1.957 raeburn 9480: =item B<$umode> Student's authentication mode
1.286 matthew 9481:
1.957 raeburn 9482: =item B<$upass> Student's password
1.286 matthew 9483:
1.957 raeburn 9484: =item B<$first> Student's first name
1.286 matthew 9485:
1.957 raeburn 9486: =item B<$middle> Student's middle name
1.286 matthew 9487:
1.957 raeburn 9488: =item B<$last> Student's last name
1.286 matthew 9489:
1.957 raeburn 9490: =item B<$gene> Student's generation
1.286 matthew 9491:
1.957 raeburn 9492: =item B<$usec> Student's section in course
1.286 matthew 9493:
9494: =item B<$end> Unix time of the roles expiration
9495:
9496: =item B<$start> Unix time of the roles start date
9497:
9498: =item B<$forceid> If defined, allow $uid to be changed
9499:
9500: =item B<$desiredhome> server to use as home server for student
9501:
1.957 raeburn 9502: =item B<$email> Student's permanent e-mail address
9503:
9504: =item B<$type> Type of enrollment (auto or manual)
9505:
1.963 raeburn 9506: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9507:
9508: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9509:
1.963 raeburn 9510: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9511:
1.963 raeburn 9512: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9513:
1.963 raeburn 9514: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9515:
1.286 matthew 9516: =back
1.297 matthew 9517:
9518: =item *
9519:
9520: modify_student_enrollment
9521:
9522: Change a students enrollment status in a class. The environment variable
9523: 'role.request.course' must be defined for this function to proceed.
9524:
9525: Inputs:
9526:
9527: =over 4
9528:
9529: =item $udom, students domain
9530:
9531: =item $uname, students name
9532:
9533: =item $uid, students user id
9534:
9535: =item $first, students first name
9536:
9537: =item $middle
9538:
9539: =item $last
9540:
9541: =item $gene
9542:
9543: =item $usec
9544:
9545: =item $end
9546:
9547: =item $start
9548:
1.957 raeburn 9549: =item $type
9550:
9551: =item $locktype
9552:
9553: =item $cid
9554:
9555: =item $selfenroll
9556:
9557: =item $context
9558:
1.297 matthew 9559: =back
9560:
1.191 harris41 9561:
9562: =item *
9563:
1.243 albertel 9564: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9565: custom role; give a custom role to a user for the level given by URL. Specify
9566: name and domain of role author, and role name
1.191 harris41 9567:
9568: =item *
9569:
1.243 albertel 9570: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9571:
9572: =item *
9573:
1.243 albertel 9574: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9575:
9576: =back
9577:
9578: =head2 Course Infomation
9579:
9580: =over 4
1.191 harris41 9581:
9582: =item *
9583:
1.631 albertel 9584: coursedescription($courseid) : returns a hash of information about the
9585: specified course id, including all environment settings for the
9586: course, the description of the course will be in the hash under the
9587: key 'description'
1.191 harris41 9588:
9589: =item *
9590:
1.624 albertel 9591: resdata($name,$domain,$type,@which) : request for current parameter
9592: setting for a specific $type, where $type is either 'course' or 'user',
9593: @what should be a list of parameters to ask about. This routine caches
9594: answers for 5 minutes.
1.243 albertel 9595:
1.877 foxr 9596: =item *
9597:
9598: get_courseresdata($courseid, $domain) : dump the entire course resource
9599: data base, returning a hash that is keyed by the resource name and has
9600: values that are the resource value. I believe that the timestamps and
9601: versions are also returned.
9602:
9603:
1.243 albertel 9604: =back
9605:
9606: =head2 Course Modification
9607:
9608: =over 4
1.191 harris41 9609:
9610: =item *
9611:
1.243 albertel 9612: writecoursepref($courseid,%prefs) : write preferences (environment
9613: database) for a course
1.191 harris41 9614:
9615: =item *
9616:
1.243 albertel 9617: createcourse($udom,$description,$url) : make/modify course
9618:
9619: =back
9620:
9621: =head2 Resource Subroutines
9622:
9623: =over 4
1.191 harris41 9624:
9625: =item *
9626:
1.243 albertel 9627: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9628:
9629: =item *
9630:
1.243 albertel 9631: repcopy($filename) : subscribes to the requested file, and attempts to
9632: replicate from the owning library server, Might return
1.607 raeburn 9633: 'unavailable', 'not_found', 'forbidden', 'ok', or
9634: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9635: resource. Expects the local filesystem pathname
9636: (/home/httpd/html/res/....)
9637:
9638: =back
9639:
9640: =head2 Resource Information
9641:
9642: =over 4
1.191 harris41 9643:
9644: =item *
9645:
1.243 albertel 9646: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9647: a vairety of different possible values, $varname should be a request
9648: string, and the other parameters can be used to specify who and what
9649: one is asking about.
9650:
9651: Possible values for $varname are environment.lastname (or other item
9652: from the envirnment hash), user.name (or someother aspect about the
9653: user), resource.0.maxtries (or some other part and parameter of a
9654: resource)
1.204 albertel 9655:
9656: =item *
9657:
1.243 albertel 9658: directcondval($number) : get current value of a condition; reads from a state
9659: string
1.204 albertel 9660:
9661: =item *
9662:
1.243 albertel 9663: condval($condidx) : value of condition index based on state
1.204 albertel 9664:
9665: =item *
9666:
1.243 albertel 9667: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9668: resource's metadata, $what should be either a specific key, or either
9669: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9670: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9671:
9672: this function automatically caches all requests
1.191 harris41 9673:
9674: =item *
9675:
1.243 albertel 9676: metadata_query($query,$custom,$customshow) : make a metadata query against the
9677: network of library servers; returns file handle of where SQL and regex results
9678: will be stored for query
1.191 harris41 9679:
9680: =item *
9681:
1.243 albertel 9682: symbread($filename) : return symbolic list entry (filename argument optional);
9683: returns the data handle
1.191 harris41 9684:
9685: =item *
9686:
1.243 albertel 9687: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9688: a possible symb for the URL in $thisfn, and if is an encryypted
9689: resource that the user accessed using /enc/ returns a 1 on success, 0
9690: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9691: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9692:
1.191 harris41 9693:
9694: =item *
9695:
1.243 albertel 9696: symbclean($symb) : removes versions numbers from a symb, returns the
9697: cleaned symb
1.191 harris41 9698:
9699: =item *
9700:
1.243 albertel 9701: is_on_map($uri) : checks if the $uri is somewhere on the current
9702: course map, user must be in a course for it to work.
1.191 harris41 9703:
9704: =item *
9705:
1.243 albertel 9706: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9707:
9708: =item *
9709:
1.243 albertel 9710: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9711: a random seed, all arguments are optional, if they aren't sent it uses the
9712: environment to derive them. Note: if symb isn't sent and it can't get one
9713: from &symbread it will use the current time as its return value
1.191 harris41 9714:
9715: =item *
9716:
1.243 albertel 9717: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9718: unfakeable, receipt
1.191 harris41 9719:
9720: =item *
9721:
1.620 albertel 9722: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9723:
9724: =item *
9725:
1.243 albertel 9726: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9727:
9728: =item *
9729:
1.243 albertel 9730: 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 9731:
9732: =item *
9733:
1.243 albertel 9734: 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 9735:
9736: =item *
9737:
1.243 albertel 9738: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9739:
9740: =item *
9741:
1.243 albertel 9742: devalidate($symb) : devalidate temporary spreadsheet calculations,
9743: forcing spreadsheet to reevaluate the resource scores next time.
9744:
9745: =back
9746:
9747: =head2 Storing/Retreiving Data
9748:
9749: =over 4
1.191 harris41 9750:
9751: =item *
9752:
1.243 albertel 9753: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9754: for this url; hashref needs to be given and should be a \%hashname; the
9755: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9756: be derived from the env
1.191 harris41 9757:
9758: =item *
9759:
1.243 albertel 9760: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9761: uses critical subroutine
1.191 harris41 9762:
9763: =item *
9764:
1.243 albertel 9765: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9766: all args are optional
1.191 harris41 9767:
9768: =item *
9769:
1.717 albertel 9770: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9771: dumps the complete (or key matching regexp) namespace into a hash
9772: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9773: normally &store()ed into
9774:
9775: $range should be either an integer '100' (give me the first 100
9776: matching records)
9777: or be two integers sperated by a - with no spaces
9778: '30-50' (give me the 30th through the 50th matching
9779: records)
9780:
9781:
9782: =item *
9783:
9784: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9785: replaces a &store() version of data with a replacement set of data
9786: for a particular resource in a namespace passed in the $storehash hash
9787: reference
9788:
9789: =item *
9790:
1.243 albertel 9791: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9792: works very similar to store/cstore, but all data is stored in a
9793: temporary location and can be reset using tmpreset, $storehash should
9794: be a hash reference, returns nothing on success
1.191 harris41 9795:
9796: =item *
9797:
1.243 albertel 9798: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9799: similar to restore, but all data is stored in a temporary location and
9800: can be reset using tmpreset. Returns a hash of values on success,
9801: error string otherwise.
1.191 harris41 9802:
9803: =item *
9804:
1.243 albertel 9805: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9806: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9807:
9808: =item *
9809:
1.243 albertel 9810: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9811: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9812:
9813: =item *
9814:
1.243 albertel 9815: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9816: namesp ($udom and $uname are optional)
1.191 harris41 9817:
9818: =item *
9819:
1.702 albertel 9820: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9821: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9822: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9823:
1.702 albertel 9824: $range should be either an integer '100' (give me the first 100
9825: matching records)
9826: or be two integers sperated by a - with no spaces
9827: '30-50' (give me the 30th through the 50th matching
9828: records)
1.449 matthew 9829: =item *
9830:
9831: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9832: $store can be a scalar, an array reference, or if the amount to be
9833: incremented is > 1, a hash reference.
9834:
9835: ($udom and $uname are optional)
1.191 harris41 9836:
9837: =item *
9838:
1.243 albertel 9839: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9840: ($udom and $uname are optional)
1.191 harris41 9841:
9842: =item *
9843:
1.243 albertel 9844: cput($namespace,$storehash,$udom,$uname) : critical put
9845: ($udom and $uname are optional)
1.191 harris41 9846:
9847: =item *
9848:
1.748 albertel 9849: newput($namespace,$storehash,$udom,$uname) :
9850:
9851: Attempts to store the items in the $storehash, but only if they don't
9852: currently exist, if this succeeds you can be certain that you have
9853: successfully created a new key value pair in the $namespace db.
9854:
9855:
9856: Args:
9857: $namespace: name of database to store values to
9858: $storehash: hashref to store to the db
9859: $udom: (optional) domain of user containing the db
9860: $uname: (optional) name of user caontaining the db
9861:
9862: Returns:
9863: 'ok' -> succeeded in storing all keys of $storehash
9864: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9865: least <key> already existed in the db (other
9866: requested keys may also already exist)
1.967 bisitz 9867: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 9868: 'con_lost' -> unable to contact request server
9869: 'refused' -> action was not allowed by remote machine
9870:
9871:
9872: =item *
9873:
1.243 albertel 9874: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9875: reference filled in from namesp (encrypts the return communication)
9876: ($udom and $uname are optional)
1.191 harris41 9877:
9878: =item *
9879:
1.243 albertel 9880: log($udom,$name,$home,$message) : write to permanent log for user; use
9881: critical subroutine
9882:
1.806 raeburn 9883: =item *
9884:
1.860 raeburn 9885: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9886: array reference filled in from namespace found in domain level on either
9887: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9888:
9889: =item *
9890:
1.860 raeburn 9891: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9892: domain level either on specified domain server ($uhome) or primary domain
9893: server ($udom and $uhome are optional)
1.806 raeburn 9894:
1.943 raeburn 9895: =item *
9896:
9897: get_domain_defaults($target_domain) : returns hash with defaults for
9898: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9899: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9900: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9901: Values are retrieved from cache (if current), or from domain's configuration.db
9902: (if available), or lastly from values in lonTabs/dns_domain,tab,
9903: or lonTabs/domain.tab.
9904:
9905: %domdefaults = &get_auth_defaults($target_domain);
9906:
1.243 albertel 9907: =back
9908:
9909: =head2 Network Status Functions
9910:
9911: =over 4
1.191 harris41 9912:
9913: =item *
9914:
9915: dirlist($uri) : return directory list based on URI
9916:
9917: =item *
9918:
1.243 albertel 9919: spareserver() : find server with least workload from spare.tab
9920:
1.986 ! foxr 9921:
! 9922: =item *
! 9923:
! 9924: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
! 9925: if there is no corresponding loncapa host.
! 9926:
1.243 albertel 9927: =back
9928:
1.986 ! foxr 9929:
1.243 albertel 9930: =head2 Apache Request
9931:
9932: =over 4
1.191 harris41 9933:
9934: =item *
9935:
1.243 albertel 9936: ssi($url,%hash) : server side include, does a complete request cycle on url to
9937: localhost, posts hash
9938:
9939: =back
9940:
9941: =head2 Data to String to Data
9942:
9943: =over 4
1.191 harris41 9944:
9945: =item *
9946:
1.243 albertel 9947: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9948: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9949:
9950: =item *
9951:
1.243 albertel 9952: hashref2str($hashref) : convert a hashref into a string complete with
9953: escaping and '=' and '&' separators, supports elements that are
9954: arrayrefs and hashrefs
1.191 harris41 9955:
9956: =item *
9957:
1.243 albertel 9958: arrayref2str($arrayref) : convert an arrayref into a string complete
9959: with escaping and '&' separators, supports elements that are arrayrefs
9960: and hashrefs
1.191 harris41 9961:
9962: =item *
9963:
1.243 albertel 9964: str2hash($string) : convert string to hash using unescaping and
9965: splitting on '=' and '&', supports elements that are arrayrefs and
9966: hashrefs
1.191 harris41 9967:
9968: =item *
9969:
1.243 albertel 9970: str2array($string) : convert string to hash using unescaping and
9971: splitting on '&', supports elements that are arrayrefs and hashrefs
9972:
9973: =back
9974:
9975: =head2 Logging Routines
9976:
9977: =over 4
9978:
9979: These routines allow one to make log messages in the lonnet.log and
9980: lonnet.perm logfiles.
1.191 harris41 9981:
9982: =item *
9983:
1.243 albertel 9984: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9985:
9986: =item *
9987:
1.243 albertel 9988: logthis() : append message to the normal lonnet.log file, it gets
9989: preiodically rolled over and deleted.
1.191 harris41 9990:
9991: =item *
9992:
1.243 albertel 9993: logperm() : append a permanent message to lonnet.perm.log, this log
9994: file never gets deleted by any automated portion of the system, only
9995: messages of critical importance should go in here.
9996:
9997: =back
9998:
9999: =head2 General File Helper Routines
10000:
10001: =over 4
1.191 harris41 10002:
10003: =item *
10004:
1.481 raeburn 10005: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10006: (a) files in /uploaded
10007: (i) If a local copy of the file exists -
10008: compares modification date of local copy with last-modified date for
10009: definitive version stored on home server for course. If local copy is
10010: stale, requests a new version from the home server and stores it.
10011: If the original has been removed from the home server, then local copy
10012: is unlinked.
10013: (ii) If local copy does not exist -
10014: requests the file from the home server and stores it.
10015:
10016: If $caller is 'uploadrep':
10017: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10018: for request for files originally uploaded via DOCS.
10019: - returns 'ok' if fresh local copy now available, -1 otherwise.
10020:
10021: Otherwise:
10022: This indicates a call from the content generation phase of the request.
10023: - returns the entire contents of the file or -1.
10024:
10025: (b) files in /res
10026: - returns the entire contents of a file or -1;
10027: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10028:
1.712 albertel 10029:
10030: =item *
10031:
10032: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10033: reference
10034:
10035: returns either a stat() list of data about the file or an empty list
10036: if the file doesn't exist or couldn't find out about it (connection
10037: problems or user unknown)
10038:
1.191 harris41 10039: =item *
10040:
1.243 albertel 10041: filelocation($dir,$file) : returns file system location of a file
10042: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10043: directory that relative $file lookups are to looked in ($dir of /a/dir
10044: and a file of ../bob will become /a/bob)
1.191 harris41 10045:
10046: =item *
10047:
10048: hreflocation($dir,$file) : returns file system location or a URL; same as
10049: filelocation except for hrefs
10050:
10051: =item *
10052:
10053: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10054:
1.243 albertel 10055: =back
10056:
1.608 albertel 10057: =head2 Usererfile file routines (/uploaded*)
10058:
10059: =over 4
10060:
10061: =item *
10062:
10063: userfileupload(): main rotine for putting a file in a user or course's
10064: filespace, arguments are,
10065:
1.620 albertel 10066: formname - required - this is the name of the element in $env where the
1.608 albertel 10067: filename, and the contents of the file to create/modifed exist
1.620 albertel 10068: the filename is in $env{'form.'.$formname.'.filename'} and the
10069: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10070: coursedoc - if true, store the file in the course of the active role
10071: of the current user
10072: subdir - required - subdirectory to put the file in under ../userfiles/
10073: if undefined, it will be placed in "unknown"
10074:
10075: (This routine calls clean_filename() to remove any dangerous
10076: characters from the filename, and then calls finuserfileupload() to
10077: complete the transaction)
10078:
10079: returns either the url of the uploaded file (/uploaded/....) if successful
10080: and /adm/notfound.html if unsuccessful
10081:
10082: =item *
10083:
10084: clean_filename(): routine for cleaing a filename up for storage in
10085: userfile space, argument is:
10086:
10087: filename - proposed filename
10088:
10089: returns: the new clean filename
10090:
10091: =item *
10092:
10093: finishuserfileupload(): routine that creaes and sends the file to
10094: userspace, probably shouldn't be called directly
10095:
10096: docuname: username or courseid of destination for the file
10097: docudom: domain of user/course of destination for the file
10098: formname: same as for userfileupload()
10099: fname: filename (inculding subdirectories) for the file
10100:
10101: returns either the url of the uploaded file (/uploaded/....) if successful
10102: and /adm/notfound.html if unsuccessful
10103:
10104: =item *
10105:
10106: renameuserfile(): renames an existing userfile to a new name
10107:
10108: Args:
10109: docuname: username or courseid of destination for the file
10110: docudom: domain of user/course of destination for the file
10111: old: current file name (including any subdirs under userfiles)
10112: new: desired file name (including any subdirs under userfiles)
10113:
10114: =item *
10115:
10116: mkdiruserfile(): creates a directory is a userfiles dir
10117:
10118: Args:
10119: docuname: username or courseid of destination for the file
10120: docudom: domain of user/course of destination for the file
10121: dir: dir to create (including any subdirs under userfiles)
10122:
10123: =item *
10124:
10125: removeuserfile(): removes a file that exists in userfiles
10126:
10127: Args:
10128: docuname: username or courseid of destination for the file
10129: docudom: domain of user/course of destination for the file
10130: fname: filname to delete (including any subdirs under userfiles)
10131:
10132: =item *
10133:
10134: removeuploadedurl(): convience function for removeuserfile()
10135:
10136: Args:
10137: url: a full /uploaded/... url to delete
10138:
1.747 albertel 10139: =item *
10140:
10141: get_portfile_permissions():
10142: Args:
10143: domain: domain of user or course contain the portfolio files
10144: user: name of user or num of course contain the portfolio files
10145: Returns:
10146: hashref of a dump of the proper file_permissions.db
10147:
10148:
10149: =item *
10150:
10151: get_access_controls():
10152:
10153: Args:
10154: current_permissions: the hash ref returned from get_portfile_permissions()
10155: group: (optional) the group you want the files associated with
10156: file: (optional) the file you want access info on
10157:
10158: Returns:
1.749 raeburn 10159: a hash (keys are file names) of hashes containing
10160: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10161: values are XML containing access control settings (see below)
1.747 albertel 10162:
10163: Internal notes:
10164:
1.749 raeburn 10165: access controls are stored in file_permissions.db as key=value pairs.
10166: key -> path to file/file_name\0uniqueID:scope_end_start
10167: where scope -> public,guest,course,group,domains or users.
10168: end -> UNIX time for end of access (0 -> no end date)
10169: start -> UNIX time for start of access
10170:
10171: value -> XML description of access control
10172: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10173: <start></start>
10174: <end></end>
10175:
10176: <password></password> for scope type = guest
10177:
10178: <domain></domain> for scope type = course or group
10179: <number></number>
10180: <roles id="">
10181: <role></role>
10182: <access></access>
10183: <section></section>
10184: <group></group>
10185: </roles>
10186:
10187: <dom></dom> for scope type = domains
10188:
10189: <users> for scope type = users
10190: <user>
10191: <uname></uname>
10192: <udom></udom>
10193: </user>
10194: </users>
10195: </scope>
10196:
10197: Access data is also aggregated for each file in an additional key=value pair:
10198: key -> path to file/file_name\0accesscontrol
10199: value -> reference to hash
10200: hash contains key = value pairs
10201: where key = uniqueID:scope_end_start
10202: value = UNIX time record was last updated
10203:
10204: Used to improve speed of look-ups of access controls for each file.
10205:
10206: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10207:
10208: modify_access_controls():
10209:
10210: Modifies access controls for a portfolio file
10211: Args
10212: 1. file name
10213: 2. reference to hash of required changes,
10214: 3. domain
10215: 4. username
10216: where domain,username are the domain of the portfolio owner
10217: (either a user or a course)
10218:
10219: Returns:
10220: 1. result of additions or updates ('ok' or 'error', with error message).
10221: 2. result of deletions ('ok' or 'error', with error message).
10222: 3. reference to hash of any new or updated access controls.
10223: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10224: key = integer (inbound ID)
10225: value = uniqueID
1.747 albertel 10226:
1.608 albertel 10227: =back
10228:
1.243 albertel 10229: =head2 HTTP Helper Routines
10230:
10231: =over 4
10232:
1.191 harris41 10233: =item *
10234:
10235: escape() : unpack non-word characters into CGI-compatible hex codes
10236:
10237: =item *
10238:
10239: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10240:
1.243 albertel 10241: =back
10242:
10243: =head1 PRIVATE SUBROUTINES
10244:
10245: =head2 Underlying communication routines (Shouldn't call)
10246:
10247: =over 4
10248:
10249: =item *
10250:
10251: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10252:
10253: =item *
10254:
10255: reply() : uses subreply to send a message to remote machine, logs all failures
10256:
10257: =item *
10258:
10259: critical() : passes a critical message to another server; if cannot
10260: get through then place message in connection buffer directory and
10261: returns con_delayed, if incapable of saving message, returns
10262: con_failed
10263:
10264: =item *
10265:
10266: reconlonc() : tries to reconnect lonc client processes.
10267:
10268: =back
10269:
10270: =head2 Resource Access Logging
10271:
10272: =over 4
10273:
10274: =item *
10275:
10276: flushcourselogs() : flush (save) buffer logs and access logs
10277:
10278: =item *
10279:
10280: courselog($what) : save message for course in hash
10281:
10282: =item *
10283:
10284: courseacclog($what) : save message for course using &courselog(). Perform
10285: special processing for specific resource types (problems, exams, quizzes, etc).
10286:
1.191 harris41 10287: =item *
10288:
10289: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10290: as a PerlChildExitHandler
1.243 albertel 10291:
10292: =back
10293:
10294: =head2 Other
10295:
10296: =over 4
10297:
10298: =item *
10299:
10300: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10301:
10302: =back
10303:
10304: =cut
1.877 foxr 10305:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>