Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.985
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.985 ! raeburn 4: # $Id: lonnet.pm,v 1.984 2009/02/05 14:56:55 neumanie Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.486 www 78: # use Date::Parse;
1.871 albertel 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 80: $_64bit %env %protocol);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.977 amueller 102: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
103:
1.619 albertel 104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
1.449 matthew 109:
1.1 albertel 110: # --------------------------------------------------------------------- Logging
1.729 www 111: {
112: my $logid;
113: sub instructor_log {
1.957 raeburn 114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
1.729 www 119: $logid++;
1.957 raeburn 120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 122: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 126: 'exe_time' => $now,
1.730 www 127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
1.957 raeburn 133: },$cdom,$cnum);
1.729 www 134: }
135: }
1.1 albertel 136:
1.163 harris41 137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
1.1 albertel 147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
1.448 albertel 152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
153: print $fh "$local ($$): $message\n";
154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.1 albertel 199: # -------------------------------------------------- Non-critical communication
200: sub subreply {
201: my ($cmd,$server)=@_;
1.838 albertel 202: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 203: #
204: # With loncnew process trimming, there's a timing hole between lonc server
205: # process exit and the master server picking up the listen on the AF_UNIX
206: # socket. In that time interval, a lock file will exist:
207:
208: my $lockfile=$peerfile.".lock";
209: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
210: sleep(1);
211: }
212: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 213: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 214: #
1.550 foxr 215: # We'll give the connection a few tries before abandoning it. If
216: # connection is not possible, we'll con_lost back to the client.
217: #
218: my $client;
219: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
220: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
221: Type => SOCK_STREAM,
222: Timeout => 10);
1.869 albertel 223: if ($client) {
1.550 foxr 224: last; # Connected!
1.850 albertel 225: } else {
1.853 albertel 226: &create_connection(&hostname($server),$server);
1.550 foxr 227: }
1.850 albertel 228: sleep(1); # Try again later if failed connection.
1.550 foxr 229: }
230: my $answer;
231: if ($client) {
1.704 albertel 232: print $client "sethost:$server:$cmd\n";
1.550 foxr 233: $answer=<$client>;
234: if (!$answer) { $answer="con_lost"; }
235: chomp($answer);
236: } else {
237: $answer = 'con_lost'; # Failed connection.
238: }
1.1 albertel 239: return $answer;
240: }
241:
242: sub reply {
243: my ($cmd,$server)=@_;
1.838 albertel 244: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 245: my $answer=subreply($cmd,$server);
1.65 www 246: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 247: &logthis("<font color=\"blue\">WARNING:".
1.12 www 248: " $cmd to $server returned $answer</font>");
249: }
1.1 albertel 250: return $answer;
251: }
252:
253: # ----------------------------------------------------------- Send USR1 to lonc
254:
255: sub reconlonc {
1.891 albertel 256: my ($lonid) = @_;
257: my $hostname = &hostname($lonid);
258: if ($lonid) {
259: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
260: if ($hostname && -e $peerfile) {
261: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
262: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
263: Type => SOCK_STREAM,
264: Timeout => 10);
265: if ($client) {
266: print $client ("reset_retries\n");
267: my $answer=<$client>;
268: #reset just this one.
269: }
270: }
271: return;
272: }
273:
1.836 www 274: &logthis("Trying to reconnect lonc");
1.1 albertel 275: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 276: if (open(my $fh,"<$loncfile")) {
1.1 albertel 277: my $loncpid=<$fh>;
278: chomp($loncpid);
279: if (kill 0 => $loncpid) {
280: &logthis("lonc at pid $loncpid responding, sending USR1");
281: kill USR1 => $loncpid;
282: sleep 1;
1.836 www 283: } else {
1.12 www 284: &logthis(
1.672 albertel 285: "<font color=\"blue\">WARNING:".
1.12 www 286: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 287: }
288: } else {
1.836 www 289: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 290: }
291: }
292:
293: # ------------------------------------------------------ Critical communication
1.12 www 294:
1.1 albertel 295: sub critical {
296: my ($cmd,$server)=@_;
1.838 albertel 297: unless (&hostname($server)) {
1.672 albertel 298: &logthis("<font color=\"blue\">WARNING:".
1.89 www 299: " Critical message to unknown server ($server)</font>");
300: return 'no_such_host';
301: }
1.1 albertel 302: my $answer=reply($cmd,$server);
303: if ($answer eq 'con_lost') {
304: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 305: my $answer=reply($cmd,$server);
1.1 albertel 306: if ($answer eq 'con_lost') {
307: my $now=time;
308: my $middlename=$cmd;
1.5 www 309: $middlename=substr($middlename,0,16);
1.1 albertel 310: $middlename=~s/\W//g;
311: my $dfilename=
1.305 www 312: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
313: $dumpcount++;
1.1 albertel 314: {
1.448 albertel 315: my $dfh;
316: if (open($dfh,">$dfilename")) {
317: print $dfh "$cmd\n";
318: close($dfh);
319: }
1.1 albertel 320: }
321: sleep 2;
322: my $wcmd='';
323: {
1.448 albertel 324: my $dfh;
325: if (open($dfh,"<$dfilename")) {
326: $wcmd=<$dfh>;
327: close($dfh);
328: }
1.1 albertel 329: }
330: chomp($wcmd);
1.7 www 331: if ($wcmd eq $cmd) {
1.672 albertel 332: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 333: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 334: &logperm("D:$server:$cmd");
335: return 'con_delayed';
336: } else {
1.672 albertel 337: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 338: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 339: &logperm("F:$server:$cmd");
340: return 'con_failed';
341: }
342: }
343: }
344: return $answer;
1.405 albertel 345: }
346:
1.755 albertel 347: # ------------------------------------------- check if return value is an error
348:
349: sub error {
350: my ($result) = @_;
1.756 albertel 351: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 352: if ($2 == 2) { return undef; }
353: return $1;
354: }
355: return undef;
356: }
357:
1.783 albertel 358: sub convert_and_load_session_env {
359: my ($lonidsdir,$handle)=@_;
360: my @profile;
361: {
1.917 albertel 362: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
363: if (!$opened) {
1.915 albertel 364: return 0;
365: }
1.783 albertel 366: flock($idf,LOCK_SH);
367: @profile=<$idf>;
368: close($idf);
369: }
370: my %temp_env;
371: foreach my $line (@profile) {
1.786 albertel 372: if ($line !~ m/=/) {
373: return 0;
374: }
1.783 albertel 375: chomp($line);
376: my ($envname,$envvalue)=split(/=/,$line,2);
377: $temp_env{&unescape($envname)} = &unescape($envvalue);
378: }
379: unlink("$lonidsdir/$handle.id");
380: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
381: 0640)) {
382: %disk_env = %temp_env;
383: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
384: untie(%disk_env);
385: }
1.786 albertel 386: return 1;
1.783 albertel 387: }
388:
1.374 www 389: # ------------------------------------------- Transfer profile into environment
1.780 albertel 390: my $env_loaded;
391: sub transfer_profile_to_env {
1.788 albertel 392: my ($lonidsdir,$handle,$force_transfer) = @_;
393: if (!$force_transfer && $env_loaded) { return; }
1.374 www 394:
1.720 albertel 395: if (!defined($lonidsdir)) {
396: $lonidsdir = $perlvar{'lonIDsDir'};
397: }
398: if (!defined($handle)) {
399: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
400: }
401:
1.786 albertel 402: my $convert;
403: {
1.917 albertel 404: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
405: if (!$opened) {
1.915 albertel 406: return;
407: }
1.786 albertel 408: flock($idf,LOCK_SH);
409: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
410: &GDBM_READER(),0640)) {
411: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
412: untie(%disk_env);
413: } else {
414: $convert = 1;
415: }
416: }
417: if ($convert) {
418: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
419: &logthis("Failed to load session, or convert session.");
420: }
1.374 www 421: }
1.783 albertel 422:
1.786 albertel 423: my %remove;
1.783 albertel 424: while ( my $envname = each(%env) ) {
1.433 matthew 425: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
426: if ($time < time-300) {
1.783 albertel 427: $remove{$key}++;
1.433 matthew 428: }
429: }
430: }
1.783 albertel 431:
1.619 albertel 432: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 433: $env_loaded=1;
1.783 albertel 434: foreach my $expired_key (keys(%remove)) {
1.433 matthew 435: &delenv($expired_key);
1.374 www 436: }
1.1 albertel 437: }
438:
1.916 albertel 439: # ---------------------------------------------------- Check for valid session
440: sub check_for_valid_session {
441: my ($r) = @_;
442: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
443: my $lonid=$cookies{'lonID'};
444: return undef if (!$lonid);
445:
446: my $handle=&LONCAPA::clean_handle($lonid->value);
447: my $lonidsdir=$r->dir_config('lonIDsDir');
448: return undef if (!-e "$lonidsdir/$handle.id");
449:
1.917 albertel 450: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
451: return undef if (!$opened);
1.916 albertel 452:
453: flock($idf,LOCK_SH);
454: my %disk_env;
455: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
456: &GDBM_READER(),0640)) {
457: return undef;
458: }
459:
460: if (!defined($disk_env{'user.name'})
461: || !defined($disk_env{'user.domain'})) {
462: return undef;
463: }
464: return $handle;
465: }
466:
1.830 albertel 467: sub timed_flock {
468: my ($file,$lock_type) = @_;
469: my $failed=0;
470: eval {
471: local $SIG{__DIE__}='DEFAULT';
472: local $SIG{ALRM}=sub {
473: $failed=1;
474: die("failed lock");
475: };
476: alarm(13);
477: flock($file,$lock_type);
478: alarm(0);
479: };
480: if ($failed) {
481: return undef;
482: } else {
483: return 1;
484: }
485: }
486:
1.5 www 487: # ---------------------------------------------------------- Append Environment
488:
489: sub appenv {
1.949 raeburn 490: my ($newenv,$roles) = @_;
491: if (ref($newenv) eq 'HASH') {
492: foreach my $key (keys(%{$newenv})) {
493: my $refused = 0;
494: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
495: $refused = 1;
496: if (ref($roles) eq 'ARRAY') {
497: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
498: if (grep(/^\Q$role\E$/,@{$roles})) {
499: $refused = 0;
500: }
501: }
502: }
503: if ($refused) {
504: &logthis("<font color=\"blue\">WARNING: ".
505: "Attempt to modify environment ".$key." to ".$newenv->{$key}
506: .'</font>');
507: delete($newenv->{$key});
508: } else {
509: $env{$key}=$newenv->{$key};
510: }
511: }
512: my $opened = open(my $env_file,'+<',$env{'user.environment'});
513: if ($opened
514: && &timed_flock($env_file,LOCK_EX)
515: &&
516: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
517: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
518: while (my ($key,$value) = each(%{$newenv})) {
519: $disk_env{$key} = $value;
520: }
521: untie(%disk_env);
1.35 www 522: }
1.191 harris41 523: }
1.56 www 524: return 'ok';
525: }
526: # ----------------------------------------------------- Delete from Environment
527:
528: sub delenv {
529: my $delthis=shift;
530: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 531: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 532: "Attempt to delete from environment ".$delthis);
533: return 'error';
534: }
1.917 albertel 535: my $opened = open(my $env_file,'+<',$env{'user.environment'});
536: if ($opened
1.915 albertel 537: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 538: &&
539: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
540: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 541: foreach my $key (keys(%disk_env)) {
1.981 raeburn 542: if ($key=~/^\Q$delthis\E/) {
1.915 albertel 543: delete($env{$key});
544: delete($disk_env{$key});
545: }
1.448 albertel 546: }
1.783 albertel 547: untie(%disk_env);
1.5 www 548: }
549: return 'ok';
1.369 albertel 550: }
551:
1.790 albertel 552: sub get_env_multiple {
553: my ($name) = @_;
554: my @values;
555: if (defined($env{$name})) {
556: # exists is it an array
557: if (ref($env{$name})) {
558: @values=@{ $env{$name} };
559: } else {
560: $values[0]=$env{$name};
561: }
562: }
563: return(@values);
564: }
565:
1.958 www 566: # ------------------------------------------------------------------- Locking
567:
568: sub set_lock {
569: my ($text)=@_;
570: $locknum++;
571: my $id=$$.'-'.$locknum;
572: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
573: 'session.lock.'.$id => $text});
574: return $id;
575: }
576:
577: sub get_locks {
578: my $num=0;
579: my %texts=();
580: foreach my $lock (split(/\,/,$env{'session.locks'})) {
581: if ($lock=~/\w/) {
582: $num++;
583: $texts{$lock}=$env{'session.lock.'.$lock};
584: }
585: }
586: return ($num,%texts);
587: }
588:
589: sub remove_lock {
590: my ($id)=@_;
591: my $newlocks='';
592: foreach my $lock (split(/\,/,$env{'session.locks'})) {
593: if (($lock=~/\w/) && ($lock ne $id)) {
594: $newlocks.=','.$lock;
595: }
596: }
597: &appenv({'session.locks' => $newlocks});
598: &delenv('session.lock.'.$id);
599: }
600:
601: sub remove_all_locks {
602: my $activelocks=$env{'session.locks'};
603: foreach my $lock (split(/\,/,$env{'session.locks'})) {
604: if ($lock=~/\w/) {
605: &remove_lock($lock);
606: }
607: }
608: }
609:
610:
1.369 albertel 611: # ------------------------------------------ Find out current server userload
612: sub userload {
613: my $numusers=0;
614: {
615: opendir(LONIDS,$perlvar{'lonIDsDir'});
616: my $filename;
617: my $curtime=time;
618: while ($filename=readdir(LONIDS)) {
1.925 albertel 619: next if ($filename eq '.' || $filename eq '..');
620: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 621: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 622: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 623: }
624: closedir(LONIDS);
625: }
626: my $userloadpercent=0;
627: my $maxuserload=$perlvar{'lonUserLoadLim'};
628: if ($maxuserload) {
1.371 albertel 629: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 630: }
1.372 albertel 631: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 632: return $userloadpercent;
1.283 www 633: }
634:
635: # ------------------------------------------ Fight off request when overloaded
636:
637: sub overloaderror {
638: my ($r,$checkserver)=@_;
639: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
640: my $loadavg;
641: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 642: open(my $loadfile,'/proc/loadavg');
1.283 www 643: $loadavg=<$loadfile>;
644: $loadavg =~ s/\s.*//g;
1.285 matthew 645: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 646: close($loadfile);
1.283 www 647: } else {
648: $loadavg=&reply('load',$checkserver);
649: }
1.285 matthew 650: my $overload=$loadavg-100;
1.283 www 651: if ($overload>0) {
1.285 matthew 652: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 653: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 654: return 413;
1.283 www 655: }
656: return '';
1.5 www 657: }
1.1 albertel 658:
659: # ------------------------------ Find server with least workload from spare.tab
1.11 www 660:
1.1 albertel 661: sub spareserver {
1.670 albertel 662: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 663: my $spare_server;
1.370 albertel 664: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 665: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
666: : $userloadpercent;
667:
668: foreach my $try_server (@{ $spareid{'primary'} }) {
669: ($spare_server, $lowest_load) =
670: &compare_server_load($try_server, $spare_server, $lowest_load);
671: }
672:
673: my $found_server = ($spare_server ne '' && $lowest_load < 100);
674:
675: if (!$found_server) {
676: foreach my $try_server (@{ $spareid{'default'} }) {
677: ($spare_server, $lowest_load) =
678: &compare_server_load($try_server, $spare_server, $lowest_load);
679: }
680: }
681:
682: if (!$want_server_name) {
1.968 raeburn 683: my $protocol = 'http';
684: if ($protocol{$spare_server} eq 'https') {
685: $protocol = $protocol{$spare_server};
686: }
687: $spare_server = $protocol.'://'.&hostname($spare_server);
1.784 albertel 688: }
689: return $spare_server;
690: }
691:
692: sub compare_server_load {
693: my ($try_server, $spare_server, $lowest_load) = @_;
694:
695: my $loadans = &reply('load', $try_server);
696: my $userloadans = &reply('userload',$try_server);
697:
698: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
699: next; #didn't get a number from the server
700: }
701:
702: my $load;
703: if ($loadans =~ /\d/) {
704: if ($userloadans =~ /\d/) {
705: #both are numbers, pick the bigger one
706: $load = ($loadans > $userloadans) ? $loadans
707: : $userloadans;
1.411 albertel 708: } else {
1.784 albertel 709: $load = $loadans;
1.411 albertel 710: }
1.784 albertel 711: } else {
712: $load = $userloadans;
713: }
714:
715: if (($load =~ /\d/) && ($load < $lowest_load)) {
716: $spare_server = $try_server;
717: $lowest_load = $load;
1.370 albertel 718: }
1.784 albertel 719: return ($spare_server,$lowest_load);
1.202 matthew 720: }
1.914 albertel 721:
722: # --------------------------- ask offload servers if user already has a session
723: sub find_existing_session {
724: my ($udom,$uname) = @_;
725: foreach my $try_server (@{ $spareid{'primary'} },
726: @{ $spareid{'default'} }) {
727: return $try_server if (&has_user_session($try_server, $udom, $uname));
728: }
729: return;
730: }
731:
732: # -------------------------------- ask if server already has a session for user
733: sub has_user_session {
734: my ($lonid,$udom,$uname) = @_;
735: my $result = &reply(join(':','userhassession',
736: map {&escape($_)} ($udom,$uname)),$lonid);
737: return 1 if ($result eq 'ok');
738:
739: return 0;
740: }
741:
1.202 matthew 742: # --------------------------------------------- Try to change a user's password
743:
744: sub changepass {
1.799 raeburn 745: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 746: $currentpass = &escape($currentpass);
747: $newpass = &escape($newpass);
1.799 raeburn 748: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 749: $server);
750: if (! $answer) {
751: &logthis("No reply on password change request to $server ".
752: "by $uname in domain $udom.");
753: } elsif ($answer =~ "^ok") {
754: &logthis("$uname in $udom successfully changed their password ".
755: "on $server.");
756: } elsif ($answer =~ "^pwchange_failure") {
757: &logthis("$uname in $udom was unable to change their password ".
758: "on $server. The action was blocked by either lcpasswd ".
759: "or pwchange");
760: } elsif ($answer =~ "^non_authorized") {
761: &logthis("$uname in $udom did not get their password correct when ".
762: "attempting to change it on $server.");
763: } elsif ($answer =~ "^auth_mode_error") {
764: &logthis("$uname in $udom attempted to change their password despite ".
765: "not being locally or internally authenticated on $server.");
766: } elsif ($answer =~ "^unknown_user") {
767: &logthis("$uname in $udom attempted to change their password ".
768: "on $server but were unable to because $server is not ".
769: "their home server.");
770: } elsif ($answer =~ "^refused") {
771: &logthis("$server refused to change $uname in $udom password because ".
772: "it was sent an unencrypted request to change the password.");
773: }
774: return $answer;
1.1 albertel 775: }
776:
1.169 harris41 777: # ----------------------- Try to determine user's current authentication scheme
778:
779: sub queryauthenticate {
780: my ($uname,$udom)=@_;
1.456 albertel 781: my $uhome=&homeserver($uname,$udom);
782: if (!$uhome) {
783: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
784: return 'no_host';
785: }
786: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
787: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
788: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 789: }
1.456 albertel 790: return $answer;
1.169 harris41 791: }
792:
1.1 albertel 793: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 794:
1.1 albertel 795: sub authenticate {
1.952 raeburn 796: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 797: $upass=&escape($upass);
798: $uname= &LONCAPA::clean_username($uname);
1.836 www 799: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 800: my $newhome;
1.836 www 801: if ((!$uhome) || ($uhome eq 'no_host')) {
802: # Maybe the machine was offline and only re-appeared again recently?
803: &reconlonc();
804: # One more
1.952 raeburn 805: $uhome=&homeserver($uname,$udom,1);
806: if (($uhome eq 'no_host') && $checkdefauth) {
807: if (defined(&domain($udom,'primary'))) {
808: $newhome=&domain($udom,'primary');
809: }
810: if ($newhome ne '') {
811: $uhome = $newhome;
812: }
813: }
1.836 www 814: if ((!$uhome) || ($uhome eq 'no_host')) {
815: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 816: return 'no_host';
817: }
1.1 albertel 818: }
1.952 raeburn 819: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 820: if ($answer eq 'authorized') {
1.952 raeburn 821: if ($newhome) {
822: &logthis("User $uname at $udom authorized by $uhome, but needs account");
823: return 'no_account_on_host';
824: } else {
825: &logthis("User $uname at $udom authorized by $uhome");
826: return $uhome;
827: }
1.471 albertel 828: }
829: if ($answer eq 'non_authorized') {
830: &logthis("User $uname at $udom rejected by $uhome");
831: return 'no_host';
1.9 www 832: }
1.471 albertel 833: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 834: return 'no_host';
835: }
836:
837: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 838:
1.599 albertel 839: my %homecache;
1.1 albertel 840: sub homeserver {
1.230 stredwic 841: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 842: my $index="$uname:$udom";
1.426 albertel 843:
1.599 albertel 844: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 845:
846: my %servers = &get_servers($udom,'library');
847: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 848: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 849: exists($badServerCache{$tryserver}));
1.841 albertel 850:
851: my $answer=reply("home:$udom:$uname",$tryserver);
852: if ($answer eq 'found') {
853: delete($badServerCache{$tryserver});
854: return $homecache{$index}=$tryserver;
855: } elsif ($answer eq 'no_host') {
856: $badServerCache{$tryserver}=1;
857: }
1.1 albertel 858: }
859: return 'no_host';
1.70 www 860: }
861:
862: # ------------------------------------- Find the usernames behind a list of IDs
863:
864: sub idget {
865: my ($udom,@ids)=@_;
866: my %returnhash=();
867:
1.841 albertel 868: my %servers = &get_servers($udom,'library');
869: foreach my $tryserver (keys(%servers)) {
870: my $idlist=join('&',@ids);
871: $idlist=~tr/A-Z/a-z/;
872: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
873: my @answer=();
874: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
875: @answer=split(/\&/,$reply);
876: } ;
877: my $i;
878: for ($i=0;$i<=$#ids;$i++) {
879: if ($answer[$i]) {
880: $returnhash{$ids[$i]}=$answer[$i];
881: }
882: }
883: }
1.70 www 884: return %returnhash;
885: }
886:
887: # ------------------------------------- Find the IDs behind a list of usernames
888:
889: sub idrget {
890: my ($udom,@unames)=@_;
891: my %returnhash=();
1.800 albertel 892: foreach my $uname (@unames) {
893: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 894: }
1.70 www 895: return %returnhash;
896: }
897:
898: # ------------------------------- Store away a list of names and associated IDs
899:
900: sub idput {
901: my ($udom,%ids)=@_;
902: my %servers=();
1.800 albertel 903: foreach my $uname (keys(%ids)) {
904: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
905: my $uhom=&homeserver($uname,$udom);
1.70 www 906: if ($uhom ne 'no_host') {
1.800 albertel 907: my $id=&escape($ids{$uname});
1.70 www 908: $id=~tr/A-Z/a-z/;
1.800 albertel 909: my $esc_unam=&escape($uname);
1.70 www 910: if ($servers{$uhom}) {
1.800 albertel 911: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 912: } else {
1.800 albertel 913: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 914: }
915: }
1.191 harris41 916: }
1.800 albertel 917: foreach my $server (keys(%servers)) {
918: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 919: }
1.344 www 920: }
921:
1.806 raeburn 922: # ------------------------------------------- get items from domain db files
923:
924: sub get_dom {
1.860 raeburn 925: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 926: my $items='';
927: foreach my $item (@$storearr) {
928: $items.=&escape($item).'&';
929: }
930: $items=~s/\&$//;
1.860 raeburn 931: if (!$udom) {
932: $udom=$env{'user.domain'};
933: if (defined(&domain($udom,'primary'))) {
934: $uhome=&domain($udom,'primary');
935: } else {
1.874 albertel 936: undef($uhome);
1.860 raeburn 937: }
938: } else {
939: if (!$uhome) {
940: if (defined(&domain($udom,'primary'))) {
941: $uhome=&domain($udom,'primary');
942: }
943: }
944: }
945: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 946: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 947: my %returnhash;
1.875 albertel 948: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 949: return %returnhash;
950: }
1.806 raeburn 951: my @pairs=split(/\&/,$rep);
952: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
953: return @pairs;
954: }
955: my $i=0;
956: foreach my $item (@$storearr) {
957: $returnhash{$item}=&thaw_unescape($pairs[$i]);
958: $i++;
959: }
960: return %returnhash;
961: } else {
1.880 banghart 962: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 963: }
964: }
965:
966: # -------------------------------------------- put items in domain db files
967:
968: sub put_dom {
1.860 raeburn 969: my ($namespace,$storehash,$udom,$uhome)=@_;
970: if (!$udom) {
971: $udom=$env{'user.domain'};
972: if (defined(&domain($udom,'primary'))) {
973: $uhome=&domain($udom,'primary');
974: } else {
1.874 albertel 975: undef($uhome);
1.860 raeburn 976: }
977: } else {
978: if (!$uhome) {
979: if (defined(&domain($udom,'primary'))) {
980: $uhome=&domain($udom,'primary');
981: }
982: }
983: }
984: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 985: my $items='';
986: foreach my $item (keys(%$storehash)) {
987: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
988: }
989: $items=~s/\&$//;
990: return &reply("putdom:$udom:$namespace:$items",$uhome);
991: } else {
1.860 raeburn 992: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 993: }
994: }
995:
1.837 raeburn 996: sub retrieve_inst_usertypes {
997: my ($udom) = @_;
998: my (%returnhash,@order);
1.846 albertel 999: if (defined(&domain($udom,'primary'))) {
1000: my $uhome=&domain($udom,'primary');
1.837 raeburn 1001: my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960 raeburn 1002: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1003: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1004: return (\%returnhash,\@order);
1005: }
1.837 raeburn 1006: my ($hashitems,$orderitems) = split(/:/,$rep);
1007: my @pairs=split(/\&/,$hashitems);
1008: foreach my $item (@pairs) {
1009: my ($key,$value)=split(/=/,$item,2);
1010: $key = &unescape($key);
1011: next if ($key =~ /^error: 2 /);
1012: $returnhash{$key}=&thaw_unescape($value);
1013: }
1014: my @esc_order = split(/\&/,$orderitems);
1015: foreach my $item (@esc_order) {
1016: push(@order,&unescape($item));
1017: }
1018: } else {
1019: &logthis("get_dom failed - no primary domain server for $udom");
1020: }
1021: return (\%returnhash,\@order);
1022: }
1023:
1.868 raeburn 1024: sub is_domainimage {
1025: my ($url) = @_;
1026: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1027: if (&domain($1) ne '') {
1028: return '1';
1029: }
1030: }
1031: return;
1032: }
1033:
1.899 raeburn 1034: sub inst_directory_query {
1035: my ($srch) = @_;
1036: my $udom = $srch->{'srchdomain'};
1037: my %results;
1038: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1039: my $outcome;
1.899 raeburn 1040: if ($homeserver ne '') {
1.904 albertel 1041: my $queryid=&reply("querysend:instdirsearch:".
1042: &escape($srch->{'srchby'}).':'.
1043: &escape($srch->{'srchterm'}).':'.
1044: &escape($srch->{'srchtype'}),$homeserver);
1045: my $host=&hostname($homeserver);
1046: if ($queryid !~/^\Q$host\E\_/) {
1047: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1048: return;
1049: }
1050: my $response = &get_query_reply($queryid);
1051: my $maxtries = 5;
1052: my $tries = 1;
1053: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1054: $response = &get_query_reply($queryid);
1055: $tries ++;
1056: }
1057:
1058: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1059: if ($response eq 'unavailable') {
1060: $outcome = $response;
1061: } else {
1062: $outcome = 'ok';
1063: my @matches = split(/\n/,$response);
1064: foreach my $match (@matches) {
1065: my ($key,$value) = split(/=/,$match);
1066: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1067: }
1.899 raeburn 1068: }
1069: }
1070: }
1.909 raeburn 1071: return ($outcome,%results);
1.899 raeburn 1072: }
1073:
1074: sub usersearch {
1075: my ($srch) = @_;
1076: my $dom = $srch->{'srchdomain'};
1077: my %results;
1078: my %libserv = &all_library();
1079: my $query = 'usersearch';
1080: foreach my $tryserver (keys(%libserv)) {
1081: if (&host_domain($tryserver) eq $dom) {
1082: my $host=&hostname($tryserver);
1083: my $queryid=
1.911 raeburn 1084: &reply("querysend:".&escape($query).':'.
1085: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1086: &escape($srch->{'srchtype'}).':'.
1087: &escape($srch->{'srchterm'}),$tryserver);
1088: if ($queryid !~/^\Q$host\E\_/) {
1089: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1090: next;
1.899 raeburn 1091: }
1092: my $reply = &get_query_reply($queryid);
1093: my $maxtries = 1;
1094: my $tries = 1;
1095: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1096: $reply = &get_query_reply($queryid);
1097: $tries ++;
1098: }
1099: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1100: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1101: } else {
1.911 raeburn 1102: my @matches;
1103: if ($reply =~ /\n/) {
1104: @matches = split(/\n/,$reply);
1105: } else {
1106: @matches = split(/\&/,$reply);
1107: }
1.899 raeburn 1108: foreach my $match (@matches) {
1109: my ($uname,$udom,%userhash);
1.911 raeburn 1110: foreach my $entry (split(/:/,$match)) {
1111: my ($key,$value) =
1112: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1113: $userhash{$key} = $value;
1114: if ($key eq 'username') {
1115: $uname = $value;
1116: } elsif ($key eq 'domain') {
1117: $udom = $value;
1.911 raeburn 1118: }
1.899 raeburn 1119: }
1120: $results{$uname.':'.$udom} = \%userhash;
1121: }
1122: }
1123: }
1124: }
1125: return %results;
1126: }
1127:
1.912 raeburn 1128: sub get_instuser {
1129: my ($udom,$uname,$id) = @_;
1130: my $homeserver = &domain($udom,'primary');
1131: my ($outcome,%results);
1132: if ($homeserver ne '') {
1133: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1134: &escape($id).':'.&escape($udom),$homeserver);
1135: my $host=&hostname($homeserver);
1136: if ($queryid !~/^\Q$host\E\_/) {
1137: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1138: return;
1139: }
1140: my $response = &get_query_reply($queryid);
1141: my $maxtries = 5;
1142: my $tries = 1;
1143: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1144: $response = &get_query_reply($queryid);
1145: $tries ++;
1146: }
1147: if (!&error($response) && $response ne 'refused') {
1148: if ($response eq 'unavailable') {
1149: $outcome = $response;
1150: } else {
1151: $outcome = 'ok';
1152: my @matches = split(/\n/,$response);
1153: foreach my $match (@matches) {
1154: my ($key,$value) = split(/=/,$match);
1155: $results{&unescape($key)} = &thaw_unescape($value);
1156: }
1157: }
1158: }
1159: }
1160: my %userinfo;
1161: if (ref($results{$uname}) eq 'HASH') {
1162: %userinfo = %{$results{$uname}};
1163: }
1164: return ($outcome,%userinfo);
1165: }
1166:
1167: sub inst_rulecheck {
1.923 raeburn 1168: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1169: my %returnhash;
1170: if ($udom ne '') {
1171: if (ref($rules) eq 'ARRAY') {
1172: @{$rules} = map {&escape($_);} (@{$rules});
1173: my $rulestr = join(':',@{$rules});
1174: my $homeserver=&domain($udom,'primary');
1175: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1176: my $response;
1177: if ($item eq 'username') {
1178: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1179: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1180: $homeserver));
1.923 raeburn 1181: } elsif ($item eq 'id') {
1182: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1183: ':'.&escape($id).':'.$rulestr,
1184: $homeserver));
1.945 raeburn 1185: } elsif ($item eq 'selfcreate') {
1186: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1187: &escape($udom).':'.&escape($uname).
1188: ':'.$rulestr,$homeserver));
1.923 raeburn 1189: }
1.912 raeburn 1190: if ($response ne 'refused') {
1191: my @pairs=split(/\&/,$response);
1192: foreach my $item (@pairs) {
1193: my ($key,$value)=split(/=/,$item,2);
1194: $key = &unescape($key);
1195: next if ($key =~ /^error: 2 /);
1196: $returnhash{$key}=&thaw_unescape($value);
1197: }
1198: }
1199: }
1200: }
1201: }
1202: return %returnhash;
1203: }
1204:
1205: sub inst_userrules {
1.923 raeburn 1206: my ($udom,$check) = @_;
1.912 raeburn 1207: my (%ruleshash,@ruleorder);
1208: if ($udom ne '') {
1209: my $homeserver=&domain($udom,'primary');
1210: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1211: my $response;
1212: if ($check eq 'id') {
1213: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1214: $homeserver);
1.943 raeburn 1215: } elsif ($check eq 'email') {
1216: $response=&reply('instemailrules:'.&escape($udom),
1217: $homeserver);
1.923 raeburn 1218: } else {
1219: $response=&reply('instuserrules:'.&escape($udom),
1220: $homeserver);
1221: }
1.912 raeburn 1222: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1223: ($response ne 'unknown_cmd') &&
1.912 raeburn 1224: ($response ne 'no_such_host')) {
1225: my ($hashitems,$orderitems) = split(/:/,$response);
1226: my @pairs=split(/\&/,$hashitems);
1227: foreach my $item (@pairs) {
1228: my ($key,$value)=split(/=/,$item,2);
1229: $key = &unescape($key);
1230: next if ($key =~ /^error: 2 /);
1231: $ruleshash{$key}=&thaw_unescape($value);
1232: }
1233: my @esc_order = split(/\&/,$orderitems);
1234: foreach my $item (@esc_order) {
1235: push(@ruleorder,&unescape($item));
1236: }
1237: }
1238: }
1239: }
1240: return (\%ruleshash,\@ruleorder);
1241: }
1242:
1.976 raeburn 1243: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1244:
1245: sub get_domain_defaults {
1246: my ($domain) = @_;
1247: my $cachetime = 60*60*24;
1248: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1249: if (defined($cached)) {
1250: if (ref($result) eq 'HASH') {
1251: return %{$result};
1252: }
1253: }
1254: my %domdefaults;
1255: my %domconfig =
1.976 raeburn 1256: &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943 raeburn 1257: if (ref($domconfig{'defaults'}) eq 'HASH') {
1258: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1259: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1260: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1261: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 ! raeburn 1262: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1263: } else {
1264: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1265: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1266: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1267: }
1.976 raeburn 1268: if (ref($domconfig{'quotas'}) eq 'HASH') {
1269: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1270: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1271: } else {
1272: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1273: }
1274: my @usertools = ('aboutme','blog','portfolio');
1275: foreach my $item (@usertools) {
1276: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1277: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1278: }
1279: }
1280: }
1.985 ! raeburn 1281: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
! 1282: foreach my $item ('official','unofficial') {
! 1283: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
! 1284: }
! 1285: }
1.943 raeburn 1286: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1287: $cachetime);
1288: return %domdefaults;
1289: }
1290:
1.344 www 1291: # --------------------------------------------------- Assign a key to a student
1292:
1293: sub assign_access_key {
1.364 www 1294: #
1295: # a valid key looks like uname:udom#comments
1296: # comments are being appended
1297: #
1.498 www 1298: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1299: $kdom=
1.620 albertel 1300: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1301: $knum=
1.620 albertel 1302: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1303: $cdom=
1.620 albertel 1304: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1305: $cnum=
1.620 albertel 1306: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1307: $udom=$env{'user.name'} unless (defined($udom));
1308: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1309: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1310: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1311: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1312: # assigned to this person
1313: # - this should not happen,
1.345 www 1314: # unless something went wrong
1315: # the first time around
1316: # ready to assign
1.364 www 1317: $logentry=$1.'; '.$logentry;
1.496 www 1318: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1319: $kdom,$knum) eq 'ok') {
1.345 www 1320: # key now belongs to user
1.346 www 1321: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1322: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1323: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1324: return 'ok';
1325: } else {
1326: return
1327: 'error: Count not permanently assign key, will need to be re-entered later.';
1328: }
1329: } else {
1330: return 'error: Could not assign key, try again later.';
1331: }
1.364 www 1332: } elsif (!$existing{$ckey}) {
1.345 www 1333: # the key does not exist
1334: return 'error: The key does not exist';
1335: } else {
1336: # the key is somebody else's
1337: return 'error: The key is already in use';
1338: }
1.344 www 1339: }
1340:
1.364 www 1341: # ------------------------------------------ put an additional comment on a key
1342:
1343: sub comment_access_key {
1344: #
1345: # a valid key looks like uname:udom#comments
1346: # comments are being appended
1347: #
1348: my ($ckey,$cdom,$cnum,$logentry)=@_;
1349: $cdom=
1.620 albertel 1350: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1351: $cnum=
1.620 albertel 1352: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1353: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1354: if ($existing{$ckey}) {
1355: $existing{$ckey}.='; '.$logentry;
1356: # ready to assign
1.367 www 1357: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1358: $cdom,$cnum) eq 'ok') {
1359: return 'ok';
1360: } else {
1361: return 'error: Count not store comment.';
1362: }
1363: } else {
1364: # the key does not exist
1365: return 'error: The key does not exist';
1366: }
1367: }
1368:
1.344 www 1369: # ------------------------------------------------------ Generate a set of keys
1370:
1371: sub generate_access_keys {
1.364 www 1372: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1373: $cdom=
1.620 albertel 1374: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1375: $cnum=
1.620 albertel 1376: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1377: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1378: unless (($cdom) && ($cnum)) { return 0; }
1379: if ($number>10000) { return 0; }
1380: sleep(2); # make sure don't get same seed twice
1381: srand(time()^($$+($$<<15))); # from "Programming Perl"
1382: my $total=0;
1383: for (my $i=1;$i<=$number;$i++) {
1384: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1385: sprintf("%lx",int(100000*rand)).'-'.
1386: sprintf("%lx",int(100000*rand));
1387: $newkey=~s/1/g/g; # folks mix up 1 and l
1388: $newkey=~s/0/h/g; # and also 0 and O
1389: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1390: if ($existing{$newkey}) {
1391: $i--;
1392: } else {
1.364 www 1393: if (&put('accesskeys',
1394: { $newkey => '# generated '.localtime().
1.620 albertel 1395: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1396: '; '.$logentry },
1397: $cdom,$cnum) eq 'ok') {
1.344 www 1398: $total++;
1399: }
1400: }
1401: }
1.620 albertel 1402: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1403: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1404: return $total;
1405: }
1406:
1407: # ------------------------------------------------------- Validate an accesskey
1408:
1409: sub validate_access_key {
1410: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1411: $cdom=
1.620 albertel 1412: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1413: $cnum=
1.620 albertel 1414: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1415: $udom=$env{'user.domain'} unless (defined($udom));
1416: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1417: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1418: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1419: }
1420:
1421: # ------------------------------------- Find the section of student in a course
1.652 albertel 1422: sub devalidate_getsection_cache {
1423: my ($udom,$unam,$courseid)=@_;
1424: my $hashid="$udom:$unam:$courseid";
1425: &devalidate_cache_new('getsection',$hashid);
1426: }
1.298 matthew 1427:
1.815 albertel 1428: sub courseid_to_courseurl {
1429: my ($courseid) = @_;
1430: #already url style courseid
1431: return $courseid if ($courseid =~ m{^/});
1432:
1433: if (exists($env{'course.'.$courseid.'.num'})) {
1434: my $cnum = $env{'course.'.$courseid.'.num'};
1435: my $cdom = $env{'course.'.$courseid.'.domain'};
1436: return "/$cdom/$cnum";
1437: }
1438:
1439: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1440: if (exists($courseinfo{'num'})) {
1441: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1442: }
1443:
1444: return undef;
1445: }
1446:
1.298 matthew 1447: sub getsection {
1448: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1449: my $cachetime=1800;
1.551 albertel 1450:
1451: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1452: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1453: if (defined($cached)) { return $result; }
1454:
1.298 matthew 1455: my %Pending;
1456: my %Expired;
1457: #
1458: # Each role can either have not started yet (pending), be active,
1459: # or have expired.
1460: #
1461: # If there is an active role, we are done.
1462: #
1463: # If there is more than one role which has not started yet,
1464: # choose the one which will start sooner
1465: # If there is one role which has not started yet, return it.
1466: #
1467: # If there is more than one expired role, choose the one which ended last.
1468: # If there is a role which has expired, return it.
1469: #
1.815 albertel 1470: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1471: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1472: foreach my $key (keys(%roleshash)) {
1.479 albertel 1473: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1474: my $section=$1;
1475: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1476: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1477: my $now=time;
1.548 albertel 1478: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1479: $Expired{$end}=$section;
1480: next;
1481: }
1.548 albertel 1482: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1483: $Pending{$start}=$section;
1484: next;
1485: }
1.599 albertel 1486: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1487: }
1488: #
1489: # Presumedly there will be few matching roles from the above
1490: # loop and the sorting time will be negligible.
1491: if (scalar(keys(%Pending))) {
1492: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1493: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1494: }
1495: if (scalar(keys(%Expired))) {
1496: my @sorted = sort {$a <=> $b} keys(%Expired);
1497: my $time = pop(@sorted);
1.599 albertel 1498: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1499: }
1.599 albertel 1500: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1501: }
1.70 www 1502:
1.599 albertel 1503: sub save_cache {
1504: &purge_remembered();
1.722 albertel 1505: #&Apache::loncommon::validate_page();
1.620 albertel 1506: undef(%env);
1.780 albertel 1507: undef($env_loaded);
1.599 albertel 1508: }
1.452 albertel 1509:
1.599 albertel 1510: my $to_remember=-1;
1511: my %remembered;
1512: my %accessed;
1513: my $kicks=0;
1514: my $hits=0;
1.849 albertel 1515: sub make_key {
1516: my ($name,$id) = @_;
1.872 albertel 1517: if (length($id) > 65
1518: && length(&escape($id)) > 200) {
1519: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1520: }
1.849 albertel 1521: return &escape($name.':'.$id);
1522: }
1523:
1.599 albertel 1524: sub devalidate_cache_new {
1525: my ($name,$id,$debug) = @_;
1526: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1527: $id=&make_key($name,$id);
1.599 albertel 1528: $memcache->delete($id);
1529: delete($remembered{$id});
1530: delete($accessed{$id});
1531: }
1532:
1533: sub is_cached_new {
1534: my ($name,$id,$debug) = @_;
1.849 albertel 1535: $id=&make_key($name,$id);
1.599 albertel 1536: if (exists($remembered{$id})) {
1537: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1538: $accessed{$id}=[&gettimeofday()];
1539: $hits++;
1540: return ($remembered{$id},1);
1541: }
1542: my $value = $memcache->get($id);
1543: if (!(defined($value))) {
1544: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1545: return (undef,undef);
1.416 albertel 1546: }
1.599 albertel 1547: if ($value eq '__undef__') {
1548: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1549: $value=undef;
1550: }
1551: &make_room($id,$value,$debug);
1552: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1553: return ($value,1);
1554: }
1555:
1556: sub do_cache_new {
1557: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1558: $id=&make_key($name,$id);
1.599 albertel 1559: my $setvalue=$value;
1560: if (!defined($setvalue)) {
1561: $setvalue='__undef__';
1562: }
1.623 albertel 1563: if (!defined($time) ) {
1564: $time=600;
1565: }
1.599 albertel 1566: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1567: my $result = $memcache->set($id,$setvalue,$time);
1568: if (! $result) {
1.872 albertel 1569: &logthis("caching of id -> $id failed");
1.910 albertel 1570: $memcache->disconnect_all();
1.872 albertel 1571: }
1.600 albertel 1572: # need to make a copy of $value
1.919 albertel 1573: &make_room($id,$value,$debug);
1.599 albertel 1574: return $value;
1575: }
1576:
1577: sub make_room {
1578: my ($id,$value,$debug)=@_;
1.919 albertel 1579:
1580: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1581: : $value;
1.599 albertel 1582: if ($to_remember<0) { return; }
1583: $accessed{$id}=[&gettimeofday()];
1584: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1585: my $to_kick;
1586: my $max_time=0;
1587: foreach my $other (keys(%accessed)) {
1588: if (&tv_interval($accessed{$other}) > $max_time) {
1589: $to_kick=$other;
1590: $max_time=&tv_interval($accessed{$other});
1591: }
1592: }
1593: delete($remembered{$to_kick});
1594: delete($accessed{$to_kick});
1595: $kicks++;
1596: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1597: return;
1598: }
1599:
1.599 albertel 1600: sub purge_remembered {
1.604 albertel 1601: #&logthis("Tossing ".scalar(keys(%remembered)));
1602: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1603: undef(%remembered);
1604: undef(%accessed);
1.428 albertel 1605: }
1.70 www 1606: # ------------------------------------- Read an entry from a user's environment
1607:
1608: sub userenvironment {
1609: my ($udom,$unam,@what)=@_;
1.976 raeburn 1610: my $items;
1611: foreach my $item (@what) {
1612: $items.=&escape($item).'&';
1613: }
1614: $items=~s/\&$//;
1.70 www 1615: my %returnhash=();
1616: my @answer=split(/\&/,
1.976 raeburn 1617: &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70 www 1618: &homeserver($unam,$udom)));
1619: my $i;
1620: for ($i=0;$i<=$#what;$i++) {
1621: $returnhash{$what[$i]}=&unescape($answer[$i]);
1622: }
1623: return %returnhash;
1.1 albertel 1624: }
1625:
1.617 albertel 1626: # ---------------------------------------------------------- Get a studentphoto
1627: sub studentphoto {
1628: my ($udom,$unam,$ext) = @_;
1629: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1630: if (defined($env{'request.course.id'})) {
1.708 raeburn 1631: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1632: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1633: return(&retrievestudentphoto($udom,$unam,$ext));
1634: } else {
1635: my ($result,$perm_reqd)=
1.707 albertel 1636: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1637: if ($result eq 'ok') {
1638: if (!($perm_reqd eq 'yes')) {
1639: return(&retrievestudentphoto($udom,$unam,$ext));
1640: }
1641: }
1642: }
1643: }
1644: } else {
1645: my ($result,$perm_reqd) =
1.707 albertel 1646: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1647: if ($result eq 'ok') {
1648: if (!($perm_reqd eq 'yes')) {
1649: return(&retrievestudentphoto($udom,$unam,$ext));
1650: }
1651: }
1652: }
1653: return '/adm/lonKaputt/lonlogo_broken.gif';
1654: }
1655:
1656: sub retrievestudentphoto {
1657: my ($udom,$unam,$ext,$type) = @_;
1658: my $home=&Apache::lonnet::homeserver($unam,$udom);
1659: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1660: if ($ret eq 'ok') {
1661: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1662: if ($type eq 'thumbnail') {
1663: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1664: }
1665: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1666: return $tokenurl;
1667: } else {
1668: if ($type eq 'thumbnail') {
1669: return '/adm/lonKaputt/genericstudent_tn.gif';
1670: } else {
1671: return '/adm/lonKaputt/lonlogo_broken.gif';
1672: }
1.617 albertel 1673: }
1674: }
1675:
1.263 www 1676: # -------------------------------------------------------------------- New chat
1677:
1678: sub chatsend {
1.724 raeburn 1679: my ($newentry,$anon,$group)=@_;
1.620 albertel 1680: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1681: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1682: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1683: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1684: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1685: &escape($newentry)).':'.$group,$chome);
1.292 www 1686: }
1687:
1688: # ------------------------------------------ Find current version of a resource
1689:
1690: sub getversion {
1691: my $fname=&clutter(shift);
1692: unless ($fname=~/^\/res\//) { return -1; }
1693: return ¤tversion(&filelocation('',$fname));
1694: }
1695:
1696: sub currentversion {
1697: my $fname=shift;
1.599 albertel 1698: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1699: if (defined($cached)) { return $result; }
1.292 www 1700: my $author=$fname;
1701: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1702: my ($udom,$uname)=split(/\//,$author);
1703: my $home=homeserver($uname,$udom);
1704: if ($home eq 'no_host') {
1705: return -1;
1706: }
1707: my $answer=reply("currentversion:$fname",$home);
1708: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1709: return -1;
1710: }
1.599 albertel 1711: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1712: }
1713:
1.1 albertel 1714: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1715:
1.1 albertel 1716: sub subscribe {
1717: my $fname=shift;
1.761 raeburn 1718: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1719: $fname=~s/[\n\r]//g;
1.1 albertel 1720: my $author=$fname;
1721: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1722: my ($udom,$uname)=split(/\//,$author);
1723: my $home=homeserver($uname,$udom);
1.335 albertel 1724: if ($home eq 'no_host') {
1725: return 'not_found';
1.1 albertel 1726: }
1727: my $answer=reply("sub:$fname",$home);
1.64 www 1728: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1729: $answer.=' by '.$home;
1730: }
1.1 albertel 1731: return $answer;
1732: }
1733:
1.8 www 1734: # -------------------------------------------------------------- Replicate file
1735:
1736: sub repcopy {
1737: my $filename=shift;
1.23 www 1738: $filename=~s/\/+/\//g;
1.607 raeburn 1739: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1740: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1741: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1742: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1743: return &repcopy_userfile($filename);
1744: }
1.532 albertel 1745: $filename=~s/[\n\r]//g;
1.8 www 1746: my $transname="$filename.in.transfer";
1.828 www 1747: # FIXME: this should flock
1.607 raeburn 1748: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1749: my $remoteurl=subscribe($filename);
1.64 www 1750: if ($remoteurl =~ /^con_lost by/) {
1751: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1752: return 'unavailable';
1.8 www 1753: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1754: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1755: return 'not_found';
1.64 www 1756: } elsif ($remoteurl =~ /^rejected by/) {
1757: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1758: return 'forbidden';
1.20 www 1759: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1760: return 'ok';
1.8 www 1761: } else {
1.290 www 1762: my $author=$filename;
1763: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1764: my ($udom,$uname)=split(/\//,$author);
1765: my $home=homeserver($uname,$udom);
1766: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1767: my @parts=split(/\//,$filename);
1768: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1769: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1770: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1771: return 'bad_request';
1.8 www 1772: }
1773: my $count;
1774: for ($count=5;$count<$#parts;$count++) {
1775: $path.="/$parts[$count]";
1776: if ((-e $path)!=1) {
1777: mkdir($path,0777);
1778: }
1779: }
1780: my $ua=new LWP::UserAgent;
1781: my $request=new HTTP::Request('GET',"$remoteurl");
1782: my $response=$ua->request($request,$transname);
1783: if ($response->is_error()) {
1784: unlink($transname);
1785: my $message=$response->status_line;
1.672 albertel 1786: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1787: ." LWP get: $message: $filename</font>");
1.607 raeburn 1788: return 'unavailable';
1.8 www 1789: } else {
1.16 www 1790: if ($remoteurl!~/\.meta$/) {
1791: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1792: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1793: if ($mresponse->is_error()) {
1794: unlink($filename.'.meta');
1795: &logthis(
1.672 albertel 1796: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1797: }
1798: }
1.8 www 1799: rename($transname,$filename);
1.607 raeburn 1800: return 'ok';
1.8 www 1801: }
1.290 www 1802: }
1.8 www 1803: }
1.330 www 1804: }
1805:
1806: # ------------------------------------------------ Get server side include body
1807: sub ssi_body {
1.381 albertel 1808: my ($filelink,%form)=@_;
1.606 matthew 1809: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1810: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1811: }
1.953 www 1812: my $output='';
1813: my $response;
1.980 raeburn 1814: if ($filelink=~/^https?\:/) {
1.954 raeburn 1815: ($output,$response)=&externalssi($filelink);
1.953 www 1816: } else {
1817: ($output,$response)=&ssi($filelink,%form);
1818: }
1.778 albertel 1819: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1820: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1821: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1822: if (wantarray) {
1823: return ($output, $response);
1824: } else {
1825: return $output;
1826: }
1.8 www 1827: }
1828:
1.15 www 1829: # --------------------------------------------------------- Server Side Include
1830:
1.782 albertel 1831: sub absolute_url {
1832: my ($host_name) = @_;
1833: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1834: if ($host_name eq '') {
1835: $host_name = $ENV{'SERVER_NAME'};
1836: }
1837: return $protocol.$host_name;
1838: }
1839:
1.942 foxr 1840: #
1841: # Server side include.
1842: # Parameters:
1843: # fn Possibly encrypted resource name/id.
1844: # form Hash that describes how the rendering should be done
1845: # and other things.
1.944 foxr 1846: # Returns:
1.950 raeburn 1847: # Scalar context: The content of the response.
1848: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1849: #
1.15 www 1850: sub ssi {
1851:
1.944 foxr 1852: my ($fn,%form)=@_;
1.15 www 1853: my $ua=new LWP::UserAgent;
1.23 www 1854: my $request;
1.711 albertel 1855:
1856: $form{'no_update_last_known'}=1;
1.895 albertel 1857: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1858: if (%form) {
1.782 albertel 1859: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1860: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1861: } else {
1.782 albertel 1862: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1863: }
1864:
1.15 www 1865: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1866: my $response=$ua->request($request);
1867:
1.944 foxr 1868: if (wantarray) {
1869: return ($response->content, $response);
1870: } else {
1871: return $response->content;
1.942 foxr 1872: }
1.324 www 1873: }
1874:
1875: sub externalssi {
1876: my ($url)=@_;
1877: my $ua=new LWP::UserAgent;
1878: my $request=new HTTP::Request('GET',$url);
1879: my $response=$ua->request($request);
1.954 raeburn 1880: if (wantarray) {
1881: return ($response->content, $response);
1882: } else {
1883: return $response->content;
1884: }
1.15 www 1885: }
1.254 www 1886:
1.492 albertel 1887: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1888:
1889: sub allowuploaded {
1890: my ($srcurl,$url)=@_;
1891: $url=&clutter(&declutter($url));
1892: my $dir=$url;
1893: $dir=~s/\/[^\/]+$//;
1894: my %httpref=();
1895: my $httpurl=&hreflocation('',$url);
1896: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1897: &Apache::lonnet::appenv(\%httpref);
1.254 www 1898: }
1.477 raeburn 1899:
1.478 albertel 1900: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1901: # input: action, courseID, current domain, intended
1.637 raeburn 1902: # path to file, source of file, instruction to parse file for objects,
1903: # ref to hash for embedded objects,
1904: # ref to hash for codebase of java objects.
1905: #
1.485 raeburn 1906: # output: url to file (if action was uploaddoc),
1907: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1908: #
1.478 albertel 1909: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1910: # course.
1.477 raeburn 1911: #
1.478 albertel 1912: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1913: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1914: # course's home server.
1.477 raeburn 1915: #
1.478 albertel 1916: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1917: # be copied from $source (current location) to
1918: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1919: # and will then be copied to
1920: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1921: # course's home server.
1.485 raeburn 1922: #
1.481 raeburn 1923: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1924: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1925: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1926: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1927: # in course's home server.
1.637 raeburn 1928: #
1.477 raeburn 1929:
1930: sub process_coursefile {
1.638 albertel 1931: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1932: my $fetchresult;
1.638 albertel 1933: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1934: if ($action eq 'propagate') {
1.638 albertel 1935: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1936: $home);
1.481 raeburn 1937: } else {
1.477 raeburn 1938: my $fpath = '';
1939: my $fname = $file;
1.478 albertel 1940: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1941: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1942: my $filepath = &build_filepath($fpath);
1.481 raeburn 1943: if ($action eq 'copy') {
1944: if ($source eq '') {
1945: $fetchresult = 'no source file';
1946: return $fetchresult;
1947: } else {
1948: my $destination = $filepath.'/'.$fname;
1949: rename($source,$destination);
1950: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1951: $home);
1.481 raeburn 1952: }
1953: } elsif ($action eq 'uploaddoc') {
1954: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1955: print $fh $env{'form.'.$source};
1.481 raeburn 1956: close($fh);
1.637 raeburn 1957: if ($parser eq 'parse') {
1.961 raeburn 1958: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 1959: unless ($parse_result eq 'ok') {
1960: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1961: }
1962: }
1.477 raeburn 1963: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1964: $home);
1.481 raeburn 1965: if ($fetchresult eq 'ok') {
1966: return '/uploaded/'.$fpath.'/'.$fname;
1967: } else {
1968: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1969: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1970: return '/adm/notfound.html';
1971: }
1.477 raeburn 1972: }
1973: }
1.485 raeburn 1974: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1975: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1976: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1977: }
1978: return $fetchresult;
1979: }
1980:
1.637 raeburn 1981: sub build_filepath {
1982: my ($fpath) = @_;
1983: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1984: unless ($fpath eq '') {
1985: my @parts=split('/',$fpath);
1986: foreach my $part (@parts) {
1987: $filepath.= '/'.$part;
1988: if ((-e $filepath)!=1) {
1989: mkdir($filepath,0777);
1990: }
1991: }
1992: }
1993: return $filepath;
1994: }
1995:
1996: sub store_edited_file {
1.638 albertel 1997: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1998: my $file = $primary_url;
1999: $file =~ s#^/uploaded/$docudom/$docuname/##;
2000: my $fpath = '';
2001: my $fname = $file;
2002: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2003: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2004: my $filepath = &build_filepath($fpath);
2005: open(my $fh,'>'.$filepath.'/'.$fname);
2006: print $fh $content;
2007: close($fh);
1.638 albertel 2008: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2009: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2010: $home);
1.637 raeburn 2011: if ($$fetchresult eq 'ok') {
2012: return '/uploaded/'.$fpath.'/'.$fname;
2013: } else {
1.638 albertel 2014: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2015: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2016: return '/adm/notfound.html';
2017: }
2018: }
2019:
1.531 albertel 2020: sub clean_filename {
1.831 albertel 2021: my ($fname,$args)=@_;
1.315 www 2022: # Replace Windows backslashes by forward slashes
1.257 www 2023: $fname=~s/\\/\//g;
1.831 albertel 2024: if (!$args->{'keep_path'}) {
2025: # Get rid of everything but the actual filename
2026: $fname=~s/^.*\/([^\/]+)$/$1/;
2027: }
1.315 www 2028: # Replace spaces by underscores
2029: $fname=~s/\s+/\_/g;
2030: # Replace all other weird characters by nothing
1.831 albertel 2031: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2032: # Replace all .\d. sequences with _\d. so they no longer look like version
2033: # numbers
2034: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2035: return $fname;
2036: }
1.984 neumanie 2037: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2038: sub resizeImage {
2039: my($img_url) = @_;
2040: my $ima = Image::Magick->new;
2041: $ima->Read($img_url);
2042: if($ima->Get('width') > 400)
2043: {
2044: my $factor = $ima->Get('width')/400;
2045: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2046: }
2047: if($ima->Get('height') > 500)
2048: {
2049: my $factor = $ima->Get('height')/500;
2050: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2051: }
2052:
2053: $ima->Write($img_url);
2054: }
1.531 albertel 2055:
1.977 amueller 2056: #Wrapper function for userphotoupload
2057: sub userphotoupload
2058: {
2059: my($formname,$subdir) = @_;
2060: $upload_photo_form = 1;
2061: return &userfileupload($formname,undef,$subdir);
2062: }
2063:
1.608 albertel 2064: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2065: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2066: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2067: # $coursedoc - if true up to the current course
2068: # if false
2069: # $subdir - directory in userfile to store the file into
1.858 raeburn 2070: # $parser - instruction to parse file for objects ($parser = parse)
2071: # $allfiles - reference to hash for embedded objects
2072: # $codebase - reference to hash for codebase of java objects
2073: # $desuname - username for permanent storage of uploaded file
2074: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2075: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2076: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2077: #
1.686 albertel 2078: # output: url of file in userspace, or error: <message>
2079: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2080:
2081:
1.531 albertel 2082: sub userfileupload {
1.860 raeburn 2083: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2084: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2085: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2086: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2087: $fname=&clean_filename($fname);
1.315 www 2088: # See if there is anything left
1.257 www 2089: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2090: chop($env{'form.'.$formname});
1.523 raeburn 2091: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2092: my $now = time;
2093: my $filepath = 'tmp/helprequests/'.$now;
2094: my @parts=split(/\//,$filepath);
2095: my $fullpath = $perlvar{'lonDaemons'};
2096: for (my $i=0;$i<@parts;$i++) {
2097: $fullpath .= '/'.$parts[$i];
2098: if ((-e $fullpath)!=1) {
2099: mkdir($fullpath,0777);
2100: }
2101: }
2102: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2103: print $fh $env{'form.'.$formname};
1.523 raeburn 2104: close($fh);
1.741 raeburn 2105: return $fullpath.'/'.$fname;
2106: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2107: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2108: '_'.$env{'user.domain'}.'/pending';
2109: my @parts=split(/\//,$filepath);
2110: my $fullpath = $perlvar{'lonDaemons'};
2111: for (my $i=0;$i<@parts;$i++) {
2112: $fullpath .= '/'.$parts[$i];
2113: if ((-e $fullpath)!=1) {
2114: mkdir($fullpath,0777);
2115: }
2116: }
2117: open(my $fh,'>'.$fullpath.'/'.$fname);
2118: print $fh $env{'form.'.$formname};
2119: close($fh);
2120: return $fullpath.'/'.$fname;
1.523 raeburn 2121: }
1.719 banghart 2122:
1.258 www 2123: # Create the directory if not present
1.493 albertel 2124: $fname="$subdir/$fname";
1.259 www 2125: if ($coursedoc) {
1.638 albertel 2126: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2127: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2128: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2129: return &finishuserfileupload($docuname,$docudom,
2130: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2131: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2132: } else {
1.620 albertel 2133: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2134: return &process_coursefile('uploaddoc',$docuname,$docudom,
2135: $fname,$formname,$parser,
2136: $allfiles,$codebase);
1.481 raeburn 2137: }
1.719 banghart 2138: } elsif (defined($destuname)) {
2139: my $docuname=$destuname;
2140: my $docudom=$destudom;
1.860 raeburn 2141: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2142: $parser,$allfiles,$codebase,
2143: $thumbwidth,$thumbheight);
1.719 banghart 2144:
1.259 www 2145: } else {
1.638 albertel 2146: my $docuname=$env{'user.name'};
2147: my $docudom=$env{'user.domain'};
1.714 raeburn 2148: if (exists($env{'form.group'})) {
2149: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2150: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2151: }
1.860 raeburn 2152: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2153: $parser,$allfiles,$codebase,
2154: $thumbwidth,$thumbheight);
1.259 www 2155: }
1.271 www 2156: }
2157:
2158: sub finishuserfileupload {
1.860 raeburn 2159: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2160: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2161: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2162: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2163:
1.860 raeburn 2164: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2165: $file=$fname;
2166: if ($fname=~m|/|) {
2167: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2168: $path.=$fnamepath.'/';
2169: }
1.259 www 2170: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2171: my $count;
2172: for ($count=4;$count<=$#parts;$count++) {
2173: $filepath.="/$parts[$count]";
2174: if ((-e $filepath)!=1) {
2175: mkdir($filepath,0777);
2176: }
2177: }
1.984 neumanie 2178:
1.258 www 2179: # Save the file
2180: {
1.701 albertel 2181: if (!open(FH,'>'.$filepath.'/'.$file)) {
2182: &logthis('Failed to create '.$filepath.'/'.$file);
2183: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2184: return '/adm/notfound.html';
2185: }
2186: if (!print FH ($env{'form.'.$formname})) {
2187: &logthis('Failed to write to '.$filepath.'/'.$file);
2188: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2189: return '/adm/notfound.html';
2190: }
1.570 albertel 2191: close(FH);
1.977 amueller 2192: if($upload_photo_form==1)
2193: {
1.984 neumanie 2194: resizeImage($filepath.'/'.$file);
1.977 amueller 2195: $upload_photo_form = 0;
2196: }
1.258 www 2197: }
1.637 raeburn 2198: if ($parser eq 'parse') {
1.961 raeburn 2199: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2200: $codebase);
1.637 raeburn 2201: unless ($parse_result eq 'ok') {
1.638 albertel 2202: &logthis('Failed to parse '.$filepath.$file.
2203: ' for embedded media: '.$parse_result);
1.637 raeburn 2204: }
2205: }
1.860 raeburn 2206: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2207: my $input = $filepath.'/'.$file;
2208: my $output = $filepath.'/'.'tn-'.$file;
2209: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2210: system("convert -sample $thumbsize $input $output");
2211: if (-e $filepath.'/'.'tn-'.$file) {
2212: $fetchthumb = 1;
2213: }
2214: }
1.858 raeburn 2215:
1.259 www 2216: # Notify homeserver to grep it
2217: #
1.984 neumanie 2218: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2219: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2220: if ($fetchresult eq 'ok') {
1.860 raeburn 2221: if ($fetchthumb) {
2222: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2223: if ($thumbresult ne 'ok') {
2224: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2225: $docuhome.': '.$thumbresult);
2226: }
2227: }
1.259 www 2228: #
1.258 www 2229: # Return the URL to it
1.494 albertel 2230: return '/uploaded/'.$path.$file;
1.263 www 2231: } else {
1.494 albertel 2232: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2233: ': '.$fetchresult);
1.263 www 2234: return '/adm/notfound.html';
1.858 raeburn 2235: }
1.493 albertel 2236: }
2237:
1.637 raeburn 2238: sub extract_embedded_items {
1.961 raeburn 2239: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2240: my @state = ();
2241: my %javafiles = (
2242: codebase => '',
2243: code => '',
2244: archive => ''
2245: );
2246: my %mediafiles = (
2247: src => '',
2248: movie => '',
2249: );
1.648 raeburn 2250: my $p;
2251: if ($content) {
2252: $p = HTML::LCParser->new($content);
2253: } else {
1.961 raeburn 2254: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2255: }
1.641 albertel 2256: while (my $t=$p->get_token()) {
1.640 albertel 2257: if ($t->[0] eq 'S') {
2258: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2259: push(@state, $tagname);
1.648 raeburn 2260: if (lc($tagname) eq 'allow') {
2261: &add_filetype($allfiles,$attr->{'src'},'src');
2262: }
1.640 albertel 2263: if (lc($tagname) eq 'img') {
2264: &add_filetype($allfiles,$attr->{'src'},'src');
2265: }
1.886 albertel 2266: if (lc($tagname) eq 'a') {
2267: &add_filetype($allfiles,$attr->{'href'},'href');
2268: }
1.645 raeburn 2269: if (lc($tagname) eq 'script') {
2270: if ($attr->{'archive'} =~ /\.jar$/i) {
2271: &add_filetype($allfiles,$attr->{'archive'},'archive');
2272: } else {
2273: &add_filetype($allfiles,$attr->{'src'},'src');
2274: }
2275: }
2276: if (lc($tagname) eq 'link') {
2277: if (lc($attr->{'rel'}) eq 'stylesheet') {
2278: &add_filetype($allfiles,$attr->{'href'},'href');
2279: }
2280: }
1.640 albertel 2281: if (lc($tagname) eq 'object' ||
2282: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2283: foreach my $item (keys(%javafiles)) {
2284: $javafiles{$item} = '';
2285: }
2286: }
2287: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2288: my $name = lc($attr->{'name'});
2289: foreach my $item (keys(%javafiles)) {
2290: if ($name eq $item) {
2291: $javafiles{$item} = $attr->{'value'};
2292: last;
2293: }
2294: }
2295: foreach my $item (keys(%mediafiles)) {
2296: if ($name eq $item) {
2297: &add_filetype($allfiles, $attr->{'value'}, 'value');
2298: last;
2299: }
2300: }
2301: }
2302: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2303: foreach my $item (keys(%javafiles)) {
2304: if ($attr->{$item}) {
2305: $javafiles{$item} = $attr->{$item};
2306: last;
2307: }
2308: }
2309: foreach my $item (keys(%mediafiles)) {
2310: if ($attr->{$item}) {
2311: &add_filetype($allfiles,$attr->{$item},$item);
2312: last;
2313: }
2314: }
2315: }
2316: } elsif ($t->[0] eq 'E') {
2317: my ($tagname) = ($t->[1]);
2318: if ($javafiles{'codebase'} ne '') {
2319: $javafiles{'codebase'} .= '/';
2320: }
2321: if (lc($tagname) eq 'applet' ||
2322: lc($tagname) eq 'object' ||
2323: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2324: ) {
2325: foreach my $item (keys(%javafiles)) {
2326: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2327: my $file=$javafiles{'codebase'}.$javafiles{$item};
2328: &add_filetype($allfiles,$file,$item);
2329: }
2330: }
2331: }
2332: pop @state;
2333: }
2334: }
1.637 raeburn 2335: return 'ok';
2336: }
2337:
1.639 albertel 2338: sub add_filetype {
2339: my ($allfiles,$file,$type)=@_;
2340: if (exists($allfiles->{$file})) {
2341: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2342: push(@{$allfiles->{$file}}, &escape($type));
2343: }
2344: } else {
2345: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2346: }
2347: }
2348:
1.493 albertel 2349: sub removeuploadedurl {
1.984 neumanie 2350: my ($url)=@_;
2351: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2352: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2353: }
2354:
2355: sub removeuserfile {
2356: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2357: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2358: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2359: if ($result eq 'ok') {
1.798 raeburn 2360: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2361: my $metafile = $fname.'.meta';
2362: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2363: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2364: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2365: my $sqlresult =
1.823 albertel 2366: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2367: 'portfolio_metadata',$group,
2368: 'delete');
1.798 raeburn 2369: }
2370: }
2371: return $result;
1.257 www 2372: }
1.15 www 2373:
1.530 albertel 2374: sub mkdiruserfile {
2375: my ($docuname,$docudom,$dir)=@_;
2376: my $home=&homeserver($docuname,$docudom);
2377: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2378: }
2379:
1.531 albertel 2380: sub renameuserfile {
2381: my ($docuname,$docudom,$old,$new)=@_;
2382: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2383: my $result = &reply("renameuserfile:$docudom:$docuname:".
2384: &escape("$old").':'.&escape("$new"),$home);
2385: if ($result eq 'ok') {
2386: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2387: my $oldmeta = $old.'.meta';
2388: my $newmeta = $new.'.meta';
2389: my $metaresult =
2390: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2391: my $url = "/uploaded/$docudom/$docuname/$old";
2392: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2393: my $sqlresult =
1.823 albertel 2394: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2395: 'portfolio_metadata',$group,
2396: 'delete');
1.798 raeburn 2397: }
2398: }
2399: return $result;
1.531 albertel 2400: }
2401:
1.14 www 2402: # ------------------------------------------------------------------------- Log
2403:
2404: sub log {
2405: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2406: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2407: }
2408:
2409: # ------------------------------------------------------------------ Course Log
1.352 www 2410: #
2411: # This routine flushes several buffers of non-mission-critical nature
2412: #
1.157 www 2413:
2414: sub flushcourselogs {
1.352 www 2415: &logthis('Flushing log buffers');
2416: #
2417: # course logs
2418: # This is a log of all transactions in a course, which can be used
2419: # for data mining purposes
2420: #
2421: # It also collects the courseid database, which lists last transaction
2422: # times and course titles for all courseids
2423: #
2424: my %courseidbuffer=();
1.921 raeburn 2425: foreach my $crsid (keys(%courselogs)) {
1.352 www 2426: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2427: &escape($courselogs{$crsid}),
2428: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2429: delete $courselogs{$crsid};
2430: } else {
2431: &logthis('Failed to flush log buffer for '.$crsid);
2432: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2433: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2434: " exceeded maximum size, deleting.</font>");
2435: delete $courselogs{$crsid};
2436: }
1.352 www 2437: }
1.920 raeburn 2438: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2439: 'description' => $coursedescrbuf{$crsid},
2440: 'inst_code' => $courseinstcodebuf{$crsid},
2441: 'type' => $coursetypebuf{$crsid},
2442: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2443: };
1.191 harris41 2444: }
1.352 www 2445: #
2446: # Write course id database (reverse lookup) to homeserver of courses
2447: # Is used in pickcourse
2448: #
1.840 albertel 2449: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2450: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2451: $courseidbuffer{$crs_home},
2452: $crs_home,'timeonly');
1.352 www 2453: }
2454: #
2455: # File accesses
2456: # Writes to the dynamic metadata of resources to get hit counts, etc.
2457: #
1.449 matthew 2458: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2459: if ($entry =~ /___count$/) {
2460: my ($dom,$name);
1.807 albertel 2461: ($dom,$name,undef)=
1.811 albertel 2462: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2463: if (! defined($dom) || $dom eq '' ||
2464: ! defined($name) || $name eq '') {
1.620 albertel 2465: my $cid = $env{'request.course.id'};
2466: $dom = $env{'request.'.$cid.'.domain'};
2467: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2468: }
1.450 matthew 2469: my $value = $accesshash{$entry};
2470: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2471: my %temphash=($url => $value);
1.449 matthew 2472: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2473: if ($result eq 'ok') {
2474: delete $accesshash{$entry};
2475: } elsif ($result eq 'unknown_cmd') {
2476: # Target server has old code running on it.
1.450 matthew 2477: my %temphash=($entry => $value);
1.449 matthew 2478: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2479: delete $accesshash{$entry};
2480: }
2481: }
2482: } else {
1.811 albertel 2483: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2484: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2485: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2486: delete $accesshash{$entry};
2487: }
1.185 www 2488: }
1.191 harris41 2489: }
1.352 www 2490: #
2491: # Roles
2492: # Reverse lookup of user roles for course faculty/staff and co-authorship
2493: #
1.800 albertel 2494: foreach my $entry (keys(%userrolehash)) {
1.351 www 2495: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2496: split(/\:/,$entry);
2497: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2498: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2499: $rudom,$runame) eq 'ok') {
2500: delete $userrolehash{$entry};
2501: }
2502: }
1.662 raeburn 2503: #
2504: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2505: #
2506: my %domrolebuffer = ();
2507: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2508: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2509: if ($domrolebuffer{$rudom}) {
2510: $domrolebuffer{$rudom}.='&'.&escape($entry).
2511: '='.&escape($domainrolehash{$entry});
2512: } else {
2513: $domrolebuffer{$rudom}.=&escape($entry).
2514: '='.&escape($domainrolehash{$entry});
2515: }
2516: delete $domainrolehash{$entry};
2517: }
2518: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2519: my %servers = &get_servers($dom,'library');
2520: foreach my $tryserver (keys(%servers)) {
2521: unless (&reply('domroleput:'.$dom.':'.
2522: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2523: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2524: }
1.662 raeburn 2525: }
2526: }
1.186 www 2527: $dumpcount++;
1.157 www 2528: }
2529:
2530: sub courselog {
2531: my $what=shift;
1.158 www 2532: $what=time.':'.$what;
1.620 albertel 2533: unless ($env{'request.course.id'}) { return ''; }
2534: $coursedombuf{$env{'request.course.id'}}=
2535: $env{'course.'.$env{'request.course.id'}.'.domain'};
2536: $coursenumbuf{$env{'request.course.id'}}=
2537: $env{'course.'.$env{'request.course.id'}.'.num'};
2538: $coursehombuf{$env{'request.course.id'}}=
2539: $env{'course.'.$env{'request.course.id'}.'.home'};
2540: $coursedescrbuf{$env{'request.course.id'}}=
2541: $env{'course.'.$env{'request.course.id'}.'.description'};
2542: $courseinstcodebuf{$env{'request.course.id'}}=
2543: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2544: $courseownerbuf{$env{'request.course.id'}}=
2545: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2546: $coursetypebuf{$env{'request.course.id'}}=
2547: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2548: if (defined $courselogs{$env{'request.course.id'}}) {
2549: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2550: } else {
1.620 albertel 2551: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2552: }
1.620 albertel 2553: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2554: &flushcourselogs();
2555: }
1.158 www 2556: }
2557:
2558: sub courseacclog {
2559: my $fnsymb=shift;
1.620 albertel 2560: unless ($env{'request.course.id'}) { return ''; }
2561: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2562: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2563: $what.=':POST';
1.583 matthew 2564: # FIXME: Probably ought to escape things....
1.800 albertel 2565: foreach my $key (keys(%env)) {
2566: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2567: my $formitem = $1;
2568: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2569: $what.=':'.$formitem.'='.$env{$key};
2570: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2571: $what.=':'.$formitem.'='.$env{$key};
2572: }
1.158 www 2573: }
1.191 harris41 2574: }
1.583 matthew 2575: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2576: # FIXME: We should not be depending on a form parameter that someone
2577: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2578: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2579: $what.= ':POST';
2580: # FIXME: Probably ought to escape things....
2581: foreach my $element ('courseexp','crsfulltext','crsrelated',
2582: 'crsdiscuss') {
1.620 albertel 2583: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2584: }
2585: }
1.158 www 2586: }
2587: &courselog($what);
1.149 www 2588: }
2589:
1.185 www 2590: sub countacc {
2591: my $url=&declutter(shift);
1.458 matthew 2592: return if (! defined($url) || $url eq '');
1.620 albertel 2593: unless ($env{'request.course.id'}) { return ''; }
2594: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2595: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2596: $accesshash{$key}++;
1.185 www 2597: }
1.349 www 2598:
1.361 www 2599: sub linklog {
2600: my ($from,$to)=@_;
2601: $from=&declutter($from);
2602: $to=&declutter($to);
2603: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2604: $accesshash{$to.'___'.$from.'___goto'}=1;
2605: }
2606:
1.349 www 2607: sub userrolelog {
2608: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2609: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2610: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2611: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2612: ($trole=~/^ta/)) {
1.350 www 2613: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2614: $userrolehash
2615: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2616: =$tend.':'.$tstart;
1.662 raeburn 2617: }
1.898 albertel 2618: if (($env{'request.role'} =~ /dc\./) &&
2619: (($trole=~/^au/) || ($trole=~/^in/) ||
2620: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2621: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2622: $userrolehash
2623: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2624: =$tend.':'.$tstart;
2625: }
1.662 raeburn 2626: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2627: ($trole=~/^li/) || ($trole=~/^li/) ||
2628: ($trole=~/^au/) || ($trole=~/^dg/) ||
2629: ($trole=~/^sc/)) {
2630: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2631: $domainrolehash
2632: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2633: = $tend.':'.$tstart;
2634: }
1.351 www 2635: }
2636:
1.957 raeburn 2637: sub courserolelog {
2638: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2639: if (($trole eq 'cc') || ($trole eq 'in') ||
2640: ($trole eq 'ep') || ($trole eq 'ad') ||
2641: ($trole eq 'ta') || ($trole eq 'st') ||
2642: ($trole=~/^cr/) || ($trole eq 'gr')) {
2643: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2644: my $cdom = $1;
2645: my $cnum = $2;
2646: my $sec = $3;
2647: my $namespace = 'rolelog';
2648: my %storehash = (
2649: role => $trole,
2650: start => $tstart,
2651: end => $tend,
2652: selfenroll => $selfenroll,
2653: context => $context,
2654: );
2655: if ($trole eq 'gr') {
2656: $namespace = 'groupslog';
2657: $storehash{'group'} = $sec;
2658: } else {
2659: $storehash{'section'} = $sec;
2660: }
2661: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2662: }
2663: }
2664: return;
2665: }
2666:
1.351 www 2667: sub get_course_adv_roles {
1.948 raeburn 2668: my ($cid,$codes) = @_;
1.620 albertel 2669: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2670: my %coursehash=&coursedescription($cid);
1.470 www 2671: my %nothide=();
1.800 albertel 2672: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2673: if ($user !~ /:/) {
2674: $nothide{join(':',split(/[\@]/,$user))}=1;
2675: } else {
2676: $nothide{$user}=1;
2677: }
1.470 www 2678: }
1.351 www 2679: my %returnhash=();
2680: my %dumphash=
2681: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2682: my $now=time;
1.800 albertel 2683: foreach my $entry (keys %dumphash) {
2684: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2685: if (($tstart) && ($tstart<0)) { next; }
2686: if (($tend) && ($tend<$now)) { next; }
2687: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2688: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2689: if ($username eq '' || $domain eq '') { next; }
1.470 www 2690: if ((&privileged($username,$domain)) &&
2691: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2692: if ($role eq 'cr') { next; }
1.948 raeburn 2693: if ($codes) {
2694: if ($section) { $role .= ':'.$section; }
2695: if ($returnhash{$role}) {
2696: $returnhash{$role}.=','.$username.':'.$domain;
2697: } else {
2698: $returnhash{$role}=$username.':'.$domain;
2699: }
1.351 www 2700: } else {
1.948 raeburn 2701: my $key=&plaintext($role);
1.973 bisitz 2702: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2703: if ($returnhash{$key}) {
2704: $returnhash{$key}.=','.$username.':'.$domain;
2705: } else {
2706: $returnhash{$key}=$username.':'.$domain;
2707: }
1.351 www 2708: }
1.948 raeburn 2709: }
1.400 www 2710: return %returnhash;
2711: }
2712:
2713: sub get_my_roles {
1.937 raeburn 2714: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2715: unless (defined($uname)) { $uname=$env{'user.name'}; }
2716: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2717: my (%dumphash,%nothide);
1.858 raeburn 2718: if ($context eq 'userroles') {
2719: %dumphash = &dump('roles',$udom,$uname);
2720: } else {
2721: %dumphash=
1.400 www 2722: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2723: if ($hidepriv) {
2724: my %coursehash=&coursedescription($udom.'_'.$uname);
2725: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2726: if ($user !~ /:/) {
2727: $nothide{join(':',split(/[\@]/,$user))} = 1;
2728: } else {
2729: $nothide{$user} = 1;
2730: }
2731: }
2732: }
1.858 raeburn 2733: }
1.400 www 2734: my %returnhash=();
2735: my $now=time;
1.800 albertel 2736: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2737: my ($role,$tend,$tstart);
2738: if ($context eq 'userroles') {
2739: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2740: } else {
2741: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2742: }
1.400 www 2743: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2744: my $status = 'active';
1.939 raeburn 2745: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2746: $status = 'previous';
2747: }
2748: if (($tstart) && ($now<$tstart)) {
2749: $status = 'future';
2750: }
2751: if (ref($types) eq 'ARRAY') {
2752: if (!grep(/^\Q$status\E$/,@{$types})) {
2753: next;
2754: }
2755: } else {
2756: if ($status ne 'active') {
2757: next;
2758: }
2759: }
1.867 raeburn 2760: my ($rolecode,$username,$domain,$section,$area);
2761: if ($context eq 'userroles') {
2762: ($area,$rolecode) = split(/_/,$entry);
2763: (undef,$domain,$username,$section) = split(/\//,$area);
2764: } else {
2765: ($role,$username,$domain,$section) = split(/\:/,$entry);
2766: }
1.832 raeburn 2767: if (ref($roledoms) eq 'ARRAY') {
2768: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2769: next;
2770: }
2771: }
2772: if (ref($roles) eq 'ARRAY') {
2773: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2774: if ($role =~ /^cr\//) {
2775: if (!grep(/^cr$/,@{$roles})) {
2776: next;
2777: }
2778: } else {
2779: next;
2780: }
1.832 raeburn 2781: }
1.867 raeburn 2782: }
1.937 raeburn 2783: if ($hidepriv) {
2784: if ((&privileged($username,$domain)) &&
2785: (!$nothide{$username.':'.$domain})) {
2786: next;
2787: }
2788: }
1.933 raeburn 2789: if ($withsec) {
2790: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2791: $tstart.':'.$tend;
2792: } else {
2793: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2794: }
1.832 raeburn 2795: }
1.373 www 2796: return %returnhash;
1.399 www 2797: }
2798:
2799: # ----------------------------------------------------- Frontpage Announcements
2800: #
2801: #
2802:
2803: sub postannounce {
2804: my ($server,$text)=@_;
1.844 albertel 2805: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2806: unless ($text=~/\w/) { $text=''; }
2807: return &reply('setannounce:'.&escape($text),$server);
2808: }
2809:
2810: sub getannounce {
1.448 albertel 2811:
2812: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2813: my $announcement='';
1.800 albertel 2814: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2815: close($fh);
1.399 www 2816: if ($announcement=~/\w/) {
2817: return
2818: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2819: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2820: } else {
2821: return '';
2822: }
2823: } else {
2824: return '';
2825: }
1.351 www 2826: }
1.353 www 2827:
2828: # ---------------------------------------------------------- Course ID routines
2829: # Deal with domain's nohist_courseid.db files
2830: #
2831:
2832: sub courseidput {
1.921 raeburn 2833: my ($domain,$storehash,$coursehome,$caller) = @_;
2834: my $outcome;
2835: if ($caller eq 'timeonly') {
2836: my $cids = '';
2837: foreach my $item (keys(%$storehash)) {
2838: $cids.=&escape($item).'&';
2839: }
2840: $cids=~s/\&$//;
2841: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2842: $coursehome);
2843: } else {
2844: my $items = '';
2845: foreach my $item (keys(%$storehash)) {
2846: $items.= &escape($item).'='.
2847: &freeze_escape($$storehash{$item}).'&';
2848: }
2849: $items=~s/\&$//;
2850: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2851: $coursehome);
1.918 raeburn 2852: }
2853: if ($outcome eq 'unknown_cmd') {
2854: my $what;
2855: foreach my $cid (keys(%$storehash)) {
2856: $what .= &escape($cid).'=';
1.921 raeburn 2857: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2858: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2859: }
2860: $what =~ s/\:$/&/;
2861: }
2862: $what =~ s/\&$//;
2863: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2864: } else {
2865: return $outcome;
2866: }
1.353 www 2867: }
2868:
2869: sub courseiddump {
1.921 raeburn 2870: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2871: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 raeburn 2872: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2873: my $as_hash = 1;
2874: my %returnhash;
2875: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2876: my %libserv = &all_library();
2877: foreach my $tryserver (keys(%libserv)) {
2878: if ( ( $hostidflag == 1
2879: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2880: || (!defined($hostidflag)) ) {
2881:
1.918 raeburn 2882: if (($domfilter eq '') ||
2883: (&host_domain($tryserver) eq $domfilter)) {
2884: my $rep =
2885: &reply('courseiddump:'.&host_domain($tryserver).':'.
2886: $sincefilter.':'.&escape($descfilter).':'.
2887: &escape($instcodefilter).':'.&escape($ownerfilter).
2888: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2889: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2890: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2891: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2892: my @pairs=split(/\&/,$rep);
2893: foreach my $item (@pairs) {
2894: my ($key,$value)=split(/\=/,$item,2);
2895: $key = &unescape($key);
2896: next if ($key =~ /^error: 2 /);
2897: my $result = &thaw_unescape($value);
2898: if (ref($result) eq 'HASH') {
2899: $returnhash{$key}=$result;
2900: } else {
1.921 raeburn 2901: my @responses = split(/:/,$value);
2902: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2903: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2904: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2905: }
2906: }
1.353 www 2907: }
2908: }
2909: }
2910: }
2911: return %returnhash;
2912: }
2913:
1.658 raeburn 2914: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2915:
2916: sub dcmailput {
1.685 raeburn 2917: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2918: my $status = &Apache::lonnet::critical(
1.740 www 2919: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2920: &escape($message),$server);
1.662 raeburn 2921: return $status;
2922: }
2923:
1.658 raeburn 2924: sub dcmaildump {
2925: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2926: my %returnhash=();
1.846 albertel 2927:
2928: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2929: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2930: &escape($enddate).':';
2931: my @esc_senders=map { &escape($_)} @$senders;
2932: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2933: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2934: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2935: if (($key) && ($value)) {
2936: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2937: }
2938: }
2939: }
2940: return %returnhash;
2941: }
1.662 raeburn 2942: # ---------------------------------------------------------- Domain roles
2943:
2944: sub get_domain_roles {
2945: my ($dom,$roles,$startdate,$enddate)=@_;
2946: if (undef($startdate) || $startdate eq '') {
2947: $startdate = '.';
2948: }
2949: if (undef($enddate) || $enddate eq '') {
2950: $enddate = '.';
2951: }
1.922 raeburn 2952: my $rolelist;
2953: if (ref($roles) eq 'ARRAY') {
2954: $rolelist = join(':',@{$roles});
2955: }
1.662 raeburn 2956: my %personnel = ();
1.841 albertel 2957:
2958: my %servers = &get_servers($dom,'library');
2959: foreach my $tryserver (keys(%servers)) {
2960: %{$personnel{$tryserver}}=();
2961: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2962: &escape($startdate).':'.
2963: &escape($enddate).':'.
2964: &escape($rolelist), $tryserver))) {
2965: my ($key,$value) = split(/\=/,$line,2);
2966: if (($key) && ($value)) {
2967: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2968: }
2969: }
1.662 raeburn 2970: }
2971: return %personnel;
2972: }
1.658 raeburn 2973:
1.149 www 2974: # ----------------------------------------------------------- Check out an item
2975:
1.504 albertel 2976: sub get_first_access {
2977: my ($type,$argsymb)=@_;
1.790 albertel 2978: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2979: if ($argsymb) { $symb=$argsymb; }
2980: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2981: if ($type eq 'course') {
2982: $res='course';
2983: } elsif ($type eq 'map') {
1.588 albertel 2984: $res=&symbread($map);
2985: } else {
2986: $res=$symb;
2987: }
2988: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2989: return $times{"$courseid\0$res"};
1.504 albertel 2990: }
2991:
2992: sub set_first_access {
2993: my ($type)=@_;
1.790 albertel 2994: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2995: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 2996: if ($type eq 'course') {
2997: $res='course';
2998: } elsif ($type eq 'map') {
1.588 albertel 2999: $res=&symbread($map);
3000: } else {
3001: $res=$symb;
3002: }
3003: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3004: if (!$firstaccess) {
1.588 albertel 3005: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3006: }
3007: return 'already_set';
1.504 albertel 3008: }
3009:
1.149 www 3010: sub checkout {
3011: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3012: my $now=time;
3013: my $lonhost=$perlvar{'lonHostID'};
3014: my $infostr=&escape(
1.234 www 3015: 'CHECKOUTTOKEN&'.
1.149 www 3016: $tuname.'&'.
3017: $tudom.'&'.
3018: $tcrsid.'&'.
3019: $symb.'&'.
3020: $now.'&'.$ENV{'REMOTE_ADDR'});
3021: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3022: if ($token=~/^error\:/) {
1.672 albertel 3023: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3024: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3025: "</font>");
3026: return '';
3027: }
3028:
1.149 www 3029: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3030: $token=~tr/a-z/A-Z/;
3031:
1.153 www 3032: my %infohash=('resource.0.outtoken' => $token,
3033: 'resource.0.checkouttime' => $now,
3034: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3035:
3036: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3037: return '';
1.151 www 3038: } else {
1.672 albertel 3039: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3040: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3041: "</font>");
1.149 www 3042: }
3043:
3044: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3045: &escape('Checkout '.$infostr.' - '.
3046: $token)) ne 'ok') {
3047: return '';
1.151 www 3048: } else {
1.672 albertel 3049: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3050: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3051: "</font>");
1.149 www 3052: }
1.151 www 3053: return $token;
1.149 www 3054: }
3055:
3056: # ------------------------------------------------------------ Check in an item
3057:
3058: sub checkin {
3059: my $token=shift;
1.150 www 3060: my $now=time;
3061: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3062: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3063: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3064: $dtoken=~s/\W/\_/g;
1.234 www 3065: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3066: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3067:
1.154 www 3068: unless (($tuname) && ($tudom)) {
3069: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3070: return '';
3071: }
3072:
3073: unless (&allowed('mgr',$tcrsid)) {
3074: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3075: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3076: return '';
3077: }
3078:
1.153 www 3079: my %infohash=('resource.0.intoken' => $token,
3080: 'resource.0.checkintime' => $now,
3081: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3082:
3083: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3084: return '';
3085: }
3086:
3087: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3088: &escape('Checkin - '.$token)) ne 'ok') {
3089: return '';
3090: }
3091:
3092: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3093: }
3094:
3095: # --------------------------------------------- Set Expire Date for Spreadsheet
3096:
3097: sub expirespread {
3098: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3099: my $cid=$env{'request.course.id'};
1.110 www 3100: if ($cid) {
3101: my $now=time;
3102: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3103: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3104: $env{'course.'.$cid.'.num'}.
1.110 www 3105: ':nohist_expirationdates:'.
3106: &escape($key).'='.$now,
1.620 albertel 3107: $env{'course.'.$cid.'.home'})
1.110 www 3108: }
3109: return 'ok';
1.14 www 3110: }
3111:
1.109 www 3112: # ----------------------------------------------------- Devalidate Spreadsheets
3113:
3114: sub devalidate {
1.325 www 3115: my ($symb,$uname,$udom)=@_;
1.620 albertel 3116: my $cid=$env{'request.course.id'};
1.109 www 3117: if ($cid) {
1.391 matthew 3118: # delete the stored spreadsheets for
3119: # - the student level sheet of this user in course's homespace
3120: # - the assessment level sheet for this resource
3121: # for this user in user's homespace
1.553 albertel 3122: # - current conditional state info
1.325 www 3123: my $key=$uname.':'.$udom.':';
1.109 www 3124: my $status=
1.299 matthew 3125: &del('nohist_calculatedsheets',
1.391 matthew 3126: [$key.'studentcalc:'],
1.620 albertel 3127: $env{'course.'.$cid.'.domain'},
3128: $env{'course.'.$cid.'.num'})
1.133 albertel 3129: .' '.
3130: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3131: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3132: unless ($status eq 'ok ok') {
3133: &logthis('Could not devalidate spreadsheet '.
1.325 www 3134: $uname.' at '.$udom.' for '.
1.109 www 3135: $symb.': '.$status);
1.133 albertel 3136: }
1.553 albertel 3137: &delenv('user.state.'.$cid);
1.109 www 3138: }
3139: }
3140:
1.265 albertel 3141: sub get_scalar {
3142: my ($string,$end) = @_;
3143: my $value;
3144: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3145: $value = $1;
3146: } elsif ($$string =~ s/^([^&]*?)&//) {
3147: $value = $1;
3148: }
3149: return &unescape($value);
3150: }
3151:
3152: sub array2str {
3153: my (@array) = @_;
3154: my $result=&arrayref2str(\@array);
3155: $result=~s/^__ARRAY_REF__//;
3156: $result=~s/__END_ARRAY_REF__$//;
3157: return $result;
3158: }
3159:
1.204 albertel 3160: sub arrayref2str {
3161: my ($arrayref) = @_;
1.265 albertel 3162: my $result='__ARRAY_REF__';
1.204 albertel 3163: foreach my $elem (@$arrayref) {
1.265 albertel 3164: if(ref($elem) eq 'ARRAY') {
3165: $result.=&arrayref2str($elem).'&';
3166: } elsif(ref($elem) eq 'HASH') {
3167: $result.=&hashref2str($elem).'&';
3168: } elsif(ref($elem)) {
3169: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3170: } else {
3171: $result.=&escape($elem).'&';
3172: }
3173: }
3174: $result=~s/\&$//;
1.265 albertel 3175: $result .= '__END_ARRAY_REF__';
1.204 albertel 3176: return $result;
3177: }
3178:
1.168 albertel 3179: sub hash2str {
1.204 albertel 3180: my (%hash) = @_;
3181: my $result=&hashref2str(\%hash);
1.265 albertel 3182: $result=~s/^__HASH_REF__//;
3183: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3184: return $result;
3185: }
3186:
3187: sub hashref2str {
3188: my ($hashref)=@_;
1.265 albertel 3189: my $result='__HASH_REF__';
1.800 albertel 3190: foreach my $key (sort(keys(%$hashref))) {
3191: if (ref($key) eq 'ARRAY') {
3192: $result.=&arrayref2str($key).'=';
3193: } elsif (ref($key) eq 'HASH') {
3194: $result.=&hashref2str($key).'=';
3195: } elsif (ref($key)) {
1.265 albertel 3196: $result.='=';
1.800 albertel 3197: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3198: } else {
1.800 albertel 3199: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3200: }
3201:
1.800 albertel 3202: if(ref($hashref->{$key}) eq 'ARRAY') {
3203: $result.=&arrayref2str($hashref->{$key}).'&';
3204: } elsif(ref($hashref->{$key}) eq 'HASH') {
3205: $result.=&hashref2str($hashref->{$key}).'&';
3206: } elsif(ref($hashref->{$key})) {
1.265 albertel 3207: $result.='&';
1.800 albertel 3208: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3209: } else {
1.800 albertel 3210: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3211: }
3212: }
1.168 albertel 3213: $result=~s/\&$//;
1.265 albertel 3214: $result .= '__END_HASH_REF__';
1.168 albertel 3215: return $result;
3216: }
3217:
3218: sub str2hash {
1.265 albertel 3219: my ($string)=@_;
3220: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3221: return %$hash;
3222: }
3223:
3224: sub str2hashref {
1.168 albertel 3225: my ($string) = @_;
1.265 albertel 3226:
3227: my %hash;
3228:
3229: if($string !~ /^__HASH_REF__/) {
3230: if (! ($string eq '' || !defined($string))) {
3231: $hash{'error'}='Not hash reference';
3232: }
3233: return (\%hash, $string);
3234: }
3235:
3236: $string =~ s/^__HASH_REF__//;
3237:
3238: while($string !~ /^__END_HASH_REF__/) {
3239: #key
3240: my $key='';
3241: if($string =~ /^__HASH_REF__/) {
3242: ($key, $string)=&str2hashref($string);
3243: if(defined($key->{'error'})) {
3244: $hash{'error'}='Bad data';
3245: return (\%hash, $string);
3246: }
3247: } elsif($string =~ /^__ARRAY_REF__/) {
3248: ($key, $string)=&str2arrayref($string);
3249: if($key->[0] eq 'Array reference error') {
3250: $hash{'error'}='Bad data';
3251: return (\%hash, $string);
3252: }
3253: } else {
3254: $string =~ s/^(.*?)=//;
1.267 albertel 3255: $key=&unescape($1);
1.265 albertel 3256: }
3257: $string =~ s/^=//;
3258:
3259: #value
3260: my $value='';
3261: if($string =~ /^__HASH_REF__/) {
3262: ($value, $string)=&str2hashref($string);
3263: if(defined($value->{'error'})) {
3264: $hash{'error'}='Bad data';
3265: return (\%hash, $string);
3266: }
3267: } elsif($string =~ /^__ARRAY_REF__/) {
3268: ($value, $string)=&str2arrayref($string);
3269: if($value->[0] eq 'Array reference error') {
3270: $hash{'error'}='Bad data';
3271: return (\%hash, $string);
3272: }
3273: } else {
3274: $value=&get_scalar(\$string,'__END_HASH_REF__');
3275: }
3276: $string =~ s/^&//;
3277:
3278: $hash{$key}=$value;
1.204 albertel 3279: }
1.265 albertel 3280:
3281: $string =~ s/^__END_HASH_REF__//;
3282:
3283: return (\%hash, $string);
1.204 albertel 3284: }
3285:
3286: sub str2array {
1.265 albertel 3287: my ($string)=@_;
3288: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3289: return @$array;
3290: }
3291:
3292: sub str2arrayref {
1.204 albertel 3293: my ($string) = @_;
1.265 albertel 3294: my @array;
3295:
3296: if($string !~ /^__ARRAY_REF__/) {
3297: if (! ($string eq '' || !defined($string))) {
3298: $array[0]='Array reference error';
3299: }
3300: return (\@array, $string);
3301: }
3302:
3303: $string =~ s/^__ARRAY_REF__//;
3304:
3305: while($string !~ /^__END_ARRAY_REF__/) {
3306: my $value='';
3307: if($string =~ /^__HASH_REF__/) {
3308: ($value, $string)=&str2hashref($string);
3309: if(defined($value->{'error'})) {
3310: $array[0] ='Array reference error';
3311: return (\@array, $string);
3312: }
3313: } elsif($string =~ /^__ARRAY_REF__/) {
3314: ($value, $string)=&str2arrayref($string);
3315: if($value->[0] eq 'Array reference error') {
3316: $array[0] ='Array reference error';
3317: return (\@array, $string);
3318: }
3319: } else {
3320: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3321: }
3322: $string =~ s/^&//;
3323:
3324: push(@array, $value);
1.191 harris41 3325: }
1.265 albertel 3326:
3327: $string =~ s/^__END_ARRAY_REF__//;
3328:
3329: return (\@array, $string);
1.168 albertel 3330: }
3331:
1.167 albertel 3332: # -------------------------------------------------------------------Temp Store
3333:
1.168 albertel 3334: sub tmpreset {
3335: my ($symb,$namespace,$domain,$stuname) = @_;
3336: if (!$symb) {
3337: $symb=&symbread();
1.620 albertel 3338: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3339: }
3340: $symb=escape($symb);
3341:
1.620 albertel 3342: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3343: $namespace=~s/\//\_/g;
3344: $namespace=~s/\W//g;
3345:
1.620 albertel 3346: if (!$domain) { $domain=$env{'user.domain'}; }
3347: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3348: if ($domain eq 'public' && $stuname eq 'public') {
3349: $stuname=$ENV{'REMOTE_ADDR'};
3350: }
1.168 albertel 3351: my $path=$perlvar{'lonDaemons'}.'/tmp';
3352: my %hash;
3353: if (tie(%hash,'GDBM_File',
3354: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3355: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3356: foreach my $key (keys %hash) {
1.180 albertel 3357: if ($key=~ /:$symb/) {
1.168 albertel 3358: delete($hash{$key});
3359: }
3360: }
3361: }
3362: }
3363:
1.167 albertel 3364: sub tmpstore {
1.168 albertel 3365: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3366:
3367: if (!$symb) {
3368: $symb=&symbread();
1.620 albertel 3369: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3370: }
3371: $symb=escape($symb);
3372:
3373: if (!$namespace) {
3374: # I don't think we would ever want to store this for a course.
3375: # it seems this will only be used if we don't have a course.
1.620 albertel 3376: #$namespace=$env{'request.course.id'};
1.168 albertel 3377: #if (!$namespace) {
1.620 albertel 3378: $namespace=$env{'request.state'};
1.168 albertel 3379: #}
3380: }
3381: $namespace=~s/\//\_/g;
3382: $namespace=~s/\W//g;
1.620 albertel 3383: if (!$domain) { $domain=$env{'user.domain'}; }
3384: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3385: if ($domain eq 'public' && $stuname eq 'public') {
3386: $stuname=$ENV{'REMOTE_ADDR'};
3387: }
1.168 albertel 3388: my $now=time;
3389: my %hash;
3390: my $path=$perlvar{'lonDaemons'}.'/tmp';
3391: if (tie(%hash,'GDBM_File',
3392: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3393: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3394: $hash{"version:$symb"}++;
3395: my $version=$hash{"version:$symb"};
3396: my $allkeys='';
3397: foreach my $key (keys(%$storehash)) {
3398: $allkeys.=$key.':';
1.591 albertel 3399: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3400: }
3401: $hash{"$version:$symb:timestamp"}=$now;
3402: $allkeys.='timestamp';
3403: $hash{"$version:keys:$symb"}=$allkeys;
3404: if (untie(%hash)) {
3405: return 'ok';
3406: } else {
3407: return "error:$!";
3408: }
3409: } else {
3410: return "error:$!";
3411: }
3412: }
1.167 albertel 3413:
1.168 albertel 3414: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3415:
1.168 albertel 3416: sub tmprestore {
3417: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3418:
1.168 albertel 3419: if (!$symb) {
3420: $symb=&symbread();
1.620 albertel 3421: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3422: }
3423: $symb=escape($symb);
3424:
1.620 albertel 3425: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3426:
1.620 albertel 3427: if (!$domain) { $domain=$env{'user.domain'}; }
3428: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3429: if ($domain eq 'public' && $stuname eq 'public') {
3430: $stuname=$ENV{'REMOTE_ADDR'};
3431: }
1.168 albertel 3432: my %returnhash;
3433: $namespace=~s/\//\_/g;
3434: $namespace=~s/\W//g;
3435: my %hash;
3436: my $path=$perlvar{'lonDaemons'}.'/tmp';
3437: if (tie(%hash,'GDBM_File',
3438: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3439: &GDBM_READER(),0640)) {
1.168 albertel 3440: my $version=$hash{"version:$symb"};
3441: $returnhash{'version'}=$version;
3442: my $scope;
3443: for ($scope=1;$scope<=$version;$scope++) {
3444: my $vkeys=$hash{"$scope:keys:$symb"};
3445: my @keys=split(/:/,$vkeys);
3446: my $key;
3447: $returnhash{"$scope:keys"}=$vkeys;
3448: foreach $key (@keys) {
1.591 albertel 3449: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3450: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3451: }
3452: }
1.168 albertel 3453: if (!(untie(%hash))) {
3454: return "error:$!";
3455: }
3456: } else {
3457: return "error:$!";
3458: }
3459: return %returnhash;
1.167 albertel 3460: }
3461:
1.9 www 3462: # ----------------------------------------------------------------------- Store
3463:
3464: sub store {
1.124 www 3465: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3466: my $home='';
3467:
1.168 albertel 3468: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3469:
1.213 www 3470: $symb=&symbclean($symb);
1.122 albertel 3471: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3472:
1.620 albertel 3473: if (!$domain) { $domain=$env{'user.domain'}; }
3474: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3475:
3476: &devalidate($symb,$stuname,$domain);
1.109 www 3477:
3478: $symb=escape($symb);
1.187 www 3479: if (!$namespace) {
1.620 albertel 3480: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3481: return '';
3482: }
3483: }
1.620 albertel 3484: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3485:
3486: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3487: $$storehash{'host'}=$perlvar{'lonHostID'};
3488:
1.12 www 3489: my $namevalue='';
1.800 albertel 3490: foreach my $key (keys(%$storehash)) {
3491: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3492: }
1.12 www 3493: $namevalue=~s/\&$//;
1.187 www 3494: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3495: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3496: }
3497:
1.47 www 3498: # -------------------------------------------------------------- Critical Store
3499:
3500: sub cstore {
1.124 www 3501: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3502: my $home='';
3503:
1.168 albertel 3504: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3505:
1.213 www 3506: $symb=&symbclean($symb);
1.122 albertel 3507: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3508:
1.620 albertel 3509: if (!$domain) { $domain=$env{'user.domain'}; }
3510: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3511:
3512: &devalidate($symb,$stuname,$domain);
1.109 www 3513:
3514: $symb=escape($symb);
1.187 www 3515: if (!$namespace) {
1.620 albertel 3516: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3517: return '';
3518: }
3519: }
1.620 albertel 3520: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3521:
3522: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3523: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3524:
1.47 www 3525: my $namevalue='';
1.800 albertel 3526: foreach my $key (keys(%$storehash)) {
3527: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3528: }
1.47 www 3529: $namevalue=~s/\&$//;
1.187 www 3530: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3531: return critical
3532: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3533: }
3534:
1.9 www 3535: # --------------------------------------------------------------------- Restore
3536:
3537: sub restore {
1.124 www 3538: my ($symb,$namespace,$domain,$stuname) = @_;
3539: my $home='';
3540:
1.168 albertel 3541: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3542:
1.122 albertel 3543: if (!$symb) {
3544: unless ($symb=escape(&symbread())) { return ''; }
3545: } else {
1.213 www 3546: $symb=&escape(&symbclean($symb));
1.122 albertel 3547: }
1.188 www 3548: if (!$namespace) {
1.620 albertel 3549: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3550: return '';
3551: }
3552: }
1.620 albertel 3553: if (!$domain) { $domain=$env{'user.domain'}; }
3554: if (!$stuname) { $stuname=$env{'user.name'}; }
3555: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3556: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3557:
1.12 www 3558: my %returnhash=();
1.800 albertel 3559: foreach my $line (split(/\&/,$answer)) {
3560: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3561: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3562: }
1.75 www 3563: my $version;
3564: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3565: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3566: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3567: }
1.75 www 3568: }
1.13 www 3569: return %returnhash;
1.34 www 3570: }
3571:
3572: # ---------------------------------------------------------- Course Description
3573:
3574: sub coursedescription {
1.731 albertel 3575: my ($courseid,$args)=@_;
1.34 www 3576: $courseid=~s/^\///;
1.49 www 3577: $courseid=~s/\_/\//g;
1.34 www 3578: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3579: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3580: my $normalid=$cdomain.'_'.$cnum;
3581: # need to always cache even if we get errors otherwise we keep
3582: # trying and trying and trying to get the course description.
3583: my %envhash=();
3584: my %returnhash=();
1.731 albertel 3585:
3586: my $expiretime=600;
3587: if ($env{'request.course.id'} eq $normalid) {
3588: $expiretime=120;
3589: }
3590:
3591: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3592: if (!$args->{'freshen_cache'}
3593: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3594: foreach my $key (keys(%env)) {
3595: next if ($key !~ /^\Q$prefix\E(.*)/);
3596: my ($setting) = $1;
3597: $returnhash{$setting} = $env{$key};
3598: }
3599: return %returnhash;
3600: }
3601:
3602: # get the data agin
3603: if (!$args->{'one_time'}) {
3604: $envhash{'course.'.$normalid.'.last_cache'}=time;
3605: }
1.811 albertel 3606:
1.34 www 3607: if ($chome ne 'no_host') {
1.302 albertel 3608: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3609: if (!exists($returnhash{'con_lost'})) {
3610: $returnhash{'home'}= $chome;
3611: $returnhash{'domain'} = $cdomain;
3612: $returnhash{'num'} = $cnum;
1.741 raeburn 3613: if (!defined($returnhash{'type'})) {
3614: $returnhash{'type'} = 'Course';
3615: }
1.130 albertel 3616: while (my ($name,$value) = each %returnhash) {
1.53 www 3617: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3618: }
1.270 www 3619: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3620: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3621: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3622: $envhash{'course.'.$normalid.'.home'}=$chome;
3623: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3624: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3625: }
3626: }
1.731 albertel 3627: if (!$args->{'one_time'}) {
1.949 raeburn 3628: &appenv(\%envhash);
1.731 albertel 3629: }
1.302 albertel 3630: return %returnhash;
1.461 www 3631: }
3632:
3633: # -------------------------------------------------See if a user is privileged
3634:
3635: sub privileged {
3636: my ($username,$domain)=@_;
3637: my $rolesdump=&reply("dump:$domain:$username:roles",
3638: &homeserver($username,$domain));
3639: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3640: my $now=time;
3641: if ($rolesdump ne '') {
1.800 albertel 3642: foreach my $entry (split(/&/,$rolesdump)) {
3643: if ($entry!~/^rolesdef_/) {
3644: my ($area,$role)=split(/=/,$entry);
1.461 www 3645: $area=~s/\_\w\w$//;
3646: my ($trole,$tend,$tstart)=split(/_/,$role);
3647: if (($trole eq 'dc') || ($trole eq 'su')) {
3648: my $active=1;
3649: if ($tend) {
3650: if ($tend<$now) { $active=0; }
3651: }
3652: if ($tstart) {
3653: if ($tstart>$now) { $active=0; }
3654: }
3655: if ($active) { return 1; }
3656: }
3657: }
3658: }
3659: }
3660: return 0;
1.9 www 3661: }
1.1 albertel 3662:
1.103 harris41 3663: # -------------------------------------------------------- Get user privileges
1.11 www 3664:
3665: sub rolesinit {
3666: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3667: my %userroles;
1.11 www 3668: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3669: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3670: my %allroles=();
1.678 raeburn 3671: my %allgroups=();
1.11 www 3672: my $now=time;
1.966 raeburn 3673: %userroles = ('user.login.time' => $now);
1.678 raeburn 3674: my $group_privs;
1.11 www 3675:
3676: if ($rolesdump ne '') {
1.800 albertel 3677: foreach my $entry (split(/&/,$rolesdump)) {
3678: if ($entry!~/^rolesdef_/) {
3679: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3680: $area=~s/\_\w\w$//;
1.678 raeburn 3681: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3682: if ($role=~/^cr/) {
1.807 albertel 3683: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3684: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3685: ($tend,$tstart)=split('_',$trest);
3686: } else {
3687: $trole=$role;
3688: }
1.678 raeburn 3689: } elsif ($role =~ m|^gr/|) {
3690: ($trole,$tend,$tstart) = split(/_/,$role);
3691: ($trole,$group_privs) = split(/\//,$trole);
3692: $group_privs = &unescape($group_privs);
1.587 albertel 3693: } else {
3694: ($trole,$tend,$tstart)=split(/_/,$role);
3695: }
1.743 albertel 3696: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3697: $username);
3698: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3699: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3700: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3701: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3702: my $spec=$trole.'.'.$area;
3703: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3704: if ($trole =~ /^cr\//) {
1.567 raeburn 3705: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3706: } elsif ($trole eq 'gr') {
3707: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3708: } else {
1.567 raeburn 3709: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3710: }
1.12 www 3711: }
1.662 raeburn 3712: }
1.191 harris41 3713: }
1.743 albertel 3714: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3715: $userroles{'user.adv'} = $adv;
3716: $userroles{'user.author'} = $author;
1.620 albertel 3717: $env{'user.adv'}=$adv;
1.11 www 3718: }
1.743 albertel 3719: return \%userroles;
1.11 www 3720: }
3721:
1.567 raeburn 3722: sub set_arearole {
3723: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3724: # log the associated role with the area
3725: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3726: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3727: }
3728:
3729: sub custom_roleprivs {
3730: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3731: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3732: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3733: if (&hostname($homsvr) ne '') {
1.567 raeburn 3734: my ($rdummy,$roledef)=
3735: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3736: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3737: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3738: if (defined($syspriv)) {
3739: $$allroles{'cm./'}.=':'.$syspriv;
3740: $$allroles{$spec.'./'}.=':'.$syspriv;
3741: }
3742: if ($tdomain ne '') {
3743: if (defined($dompriv)) {
3744: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3745: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3746: }
3747: if (($trest ne '') && (defined($coursepriv))) {
3748: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3749: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3750: }
3751: }
3752: }
3753: }
3754: }
3755:
1.678 raeburn 3756: sub group_roleprivs {
3757: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3758: my $access = 1;
3759: my $now = time;
3760: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3761: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3762: if ($access) {
1.811 albertel 3763: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3764: $$allgroups{$course}{$group} .=':'.$group_privs;
3765: }
3766: }
1.567 raeburn 3767:
3768: sub standard_roleprivs {
3769: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3770: if (defined($pr{$trole.':s'})) {
3771: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3772: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3773: }
3774: if ($tdomain ne '') {
3775: if (defined($pr{$trole.':d'})) {
3776: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3777: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3778: }
3779: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3780: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3781: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3782: }
3783: }
3784: }
3785:
3786: sub set_userprivs {
1.678 raeburn 3787: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3788: my $author=0;
3789: my $adv=0;
1.678 raeburn 3790: my %grouproles = ();
3791: if (keys(%{$allgroups}) > 0) {
3792: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3793: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3794: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3795: $trole = $1;
3796: $area = $2;
1.681 raeburn 3797: $sec = $3;
3798: $extendedarea = $area.$sec;
3799: if (exists($$allgroups{$area})) {
3800: foreach my $group (keys(%{$$allgroups{$area}})) {
3801: my $spec = $trole.'.'.$extendedarea;
3802: $grouproles{$spec.'.'.$area.'/'.$group} =
3803: $$allgroups{$area}{$group};
1.678 raeburn 3804: }
3805: }
3806: }
3807: }
3808: }
1.800 albertel 3809: foreach my $group (keys(%grouproles)) {
3810: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3811: }
1.800 albertel 3812: foreach my $role (keys(%{$allroles})) {
3813: my %thesepriv;
1.941 raeburn 3814: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3815: foreach my $item (split(/:/,$$allroles{$role})) {
3816: if ($item ne '') {
3817: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3818: if ($restrictions eq '') {
3819: $thesepriv{$privilege}='F';
3820: } elsif ($thesepriv{$privilege} ne 'F') {
3821: $thesepriv{$privilege}.=$restrictions;
3822: }
3823: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3824: }
3825: }
3826: my $thesestr='';
1.800 albertel 3827: foreach my $priv (keys(%thesepriv)) {
3828: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3829: }
3830: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3831: }
3832: return ($author,$adv);
3833: }
3834:
1.12 www 3835: # --------------------------------------------------------------- get interface
3836:
3837: sub get {
1.131 albertel 3838: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3839: my $items='';
1.800 albertel 3840: foreach my $item (@$storearr) {
3841: $items.=&escape($item).'&';
1.191 harris41 3842: }
1.12 www 3843: $items=~s/\&$//;
1.620 albertel 3844: if (!$udomain) { $udomain=$env{'user.domain'}; }
3845: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3846: my $uhome=&homeserver($uname,$udomain);
3847:
1.133 albertel 3848: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3849: my @pairs=split(/\&/,$rep);
1.273 albertel 3850: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3851: return @pairs;
3852: }
1.15 www 3853: my %returnhash=();
1.42 www 3854: my $i=0;
1.800 albertel 3855: foreach my $item (@$storearr) {
3856: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3857: $i++;
1.191 harris41 3858: }
1.15 www 3859: return %returnhash;
1.27 www 3860: }
3861:
3862: # --------------------------------------------------------------- del interface
3863:
3864: sub del {
1.133 albertel 3865: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3866: my $items='';
1.800 albertel 3867: foreach my $item (@$storearr) {
3868: $items.=&escape($item).'&';
1.191 harris41 3869: }
1.984 neumanie 3870:
1.27 www 3871: $items=~s/\&$//;
1.620 albertel 3872: if (!$udomain) { $udomain=$env{'user.domain'}; }
3873: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3874: my $uhome=&homeserver($uname,$udomain);
3875: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3876: }
3877:
3878: # -------------------------------------------------------------- dump interface
3879:
3880: sub dump {
1.755 albertel 3881: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3882: if (!$udomain) { $udomain=$env{'user.domain'}; }
3883: if (!$uname) { $uname=$env{'user.name'}; }
3884: my $uhome=&homeserver($uname,$udomain);
3885: if ($regexp) {
3886: $regexp=&escape($regexp);
3887: } else {
3888: $regexp='.';
3889: }
3890: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3891: my @pairs=split(/\&/,$rep);
3892: my %returnhash=();
3893: foreach my $item (@pairs) {
3894: my ($key,$value)=split(/=/,$item,2);
3895: $key = &unescape($key);
3896: next if ($key =~ /^error: 2 /);
3897: $returnhash{$key}=&thaw_unescape($value);
3898: }
3899: return %returnhash;
1.407 www 3900: }
3901:
1.717 albertel 3902: # --------------------------------------------------------- dumpstore interface
3903:
3904: sub dumpstore {
3905: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3906: if (!$udomain) { $udomain=$env{'user.domain'}; }
3907: if (!$uname) { $uname=$env{'user.name'}; }
3908: my $uhome=&homeserver($uname,$udomain);
3909: if ($regexp) {
3910: $regexp=&escape($regexp);
3911: } else {
3912: $regexp='.';
3913: }
3914: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3915: my @pairs=split(/\&/,$rep);
3916: my %returnhash=();
3917: foreach my $item (@pairs) {
3918: my ($key,$value)=split(/=/,$item,2);
3919: next if ($key =~ /^error: 2 /);
3920: $returnhash{$key}=&thaw_unescape($value);
3921: }
3922: return %returnhash;
1.717 albertel 3923: }
3924:
1.407 www 3925: # -------------------------------------------------------------- keys interface
3926:
3927: sub getkeys {
3928: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3929: if (!$udomain) { $udomain=$env{'user.domain'}; }
3930: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3931: my $uhome=&homeserver($uname,$udomain);
3932: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3933: my @keyarray=();
1.800 albertel 3934: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3935: next if ($key =~ /^error: 2 /);
1.800 albertel 3936: push(@keyarray,&unescape($key));
1.407 www 3937: }
3938: return @keyarray;
1.318 matthew 3939: }
3940:
1.319 matthew 3941: # --------------------------------------------------------------- currentdump
3942: sub currentdump {
1.328 matthew 3943: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3944: $courseid = $env{'request.course.id'} if (! defined($courseid));
3945: $sdom = $env{'user.domain'} if (! defined($sdom));
3946: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3947: my $uhome = &homeserver($sname,$sdom);
3948: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3949: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3950: #
1.318 matthew 3951: my %returnhash=();
1.319 matthew 3952: #
3953: if ($rep eq "unknown_cmd") {
3954: # an old lond will not know currentdump
3955: # Do a dump and make it look like a currentdump
1.822 albertel 3956: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3957: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3958: my %hash = @tmp;
3959: @tmp=();
1.424 matthew 3960: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3961: } else {
3962: my @pairs=split(/\&/,$rep);
1.800 albertel 3963: foreach my $pair (@pairs) {
3964: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3965: my ($symb,$param) = split(/:/,$key);
3966: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3967: &thaw_unescape($value);
1.319 matthew 3968: }
1.191 harris41 3969: }
1.12 www 3970: return %returnhash;
1.424 matthew 3971: }
3972:
3973: sub convert_dump_to_currentdump{
3974: my %hash = %{shift()};
3975: my %returnhash;
3976: # Code ripped from lond, essentially. The only difference
3977: # here is the unescaping done by lonnet::dump(). Conceivably
3978: # we might run in to problems with parameter names =~ /^v\./
3979: while (my ($key,$value) = each(%hash)) {
3980: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3981: $symb = &unescape($symb);
3982: $param = &unescape($param);
1.424 matthew 3983: next if ($v eq 'version' || $symb eq 'keys');
3984: next if (exists($returnhash{$symb}) &&
3985: exists($returnhash{$symb}->{$param}) &&
3986: $returnhash{$symb}->{'v.'.$param} > $v);
3987: $returnhash{$symb}->{$param}=$value;
3988: $returnhash{$symb}->{'v.'.$param}=$v;
3989: }
3990: #
3991: # Remove all of the keys in the hashes which keep track of
3992: # the version of the parameter.
3993: while (my ($symb,$param_hash) = each(%returnhash)) {
3994: # use a foreach because we are going to delete from the hash.
3995: foreach my $key (keys(%$param_hash)) {
3996: delete($param_hash->{$key}) if ($key =~ /^v\./);
3997: }
3998: }
3999: return \%returnhash;
1.12 www 4000: }
4001:
1.627 albertel 4002: # ------------------------------------------------------ critical inc interface
4003:
4004: sub cinc {
4005: return &inc(@_,'critical');
4006: }
4007:
1.449 matthew 4008: # --------------------------------------------------------------- inc interface
4009:
4010: sub inc {
1.627 albertel 4011: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4012: if (!$udomain) { $udomain=$env{'user.domain'}; }
4013: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4014: my $uhome=&homeserver($uname,$udomain);
4015: my $items='';
4016: if (! ref($store)) {
4017: # got a single value, so use that instead
4018: $items = &escape($store).'=&';
4019: } elsif (ref($store) eq 'SCALAR') {
4020: $items = &escape($$store).'=&';
4021: } elsif (ref($store) eq 'ARRAY') {
4022: $items = join('=&',map {&escape($_);} @{$store});
4023: } elsif (ref($store) eq 'HASH') {
4024: while (my($key,$value) = each(%{$store})) {
4025: $items.= &escape($key).'='.&escape($value).'&';
4026: }
4027: }
4028: $items=~s/\&$//;
1.627 albertel 4029: if ($critical) {
4030: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4031: } else {
4032: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4033: }
1.449 matthew 4034: }
4035:
1.12 www 4036: # --------------------------------------------------------------- put interface
4037:
4038: sub put {
1.134 albertel 4039: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4040: if (!$udomain) { $udomain=$env{'user.domain'}; }
4041: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4042: my $uhome=&homeserver($uname,$udomain);
1.12 www 4043: my $items='';
1.800 albertel 4044: foreach my $item (keys(%$storehash)) {
4045: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4046: }
1.12 www 4047: $items=~s/\&$//;
1.134 albertel 4048: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4049: }
4050:
1.631 albertel 4051: # ------------------------------------------------------------ newput interface
4052:
4053: sub newput {
4054: my ($namespace,$storehash,$udomain,$uname)=@_;
4055: if (!$udomain) { $udomain=$env{'user.domain'}; }
4056: if (!$uname) { $uname=$env{'user.name'}; }
4057: my $uhome=&homeserver($uname,$udomain);
4058: my $items='';
4059: foreach my $key (keys(%$storehash)) {
4060: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4061: }
4062: $items=~s/\&$//;
4063: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4064: }
4065:
4066: # --------------------------------------------------------- putstore interface
4067:
1.524 raeburn 4068: sub putstore {
1.715 albertel 4069: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4070: if (!$udomain) { $udomain=$env{'user.domain'}; }
4071: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4072: my $uhome=&homeserver($uname,$udomain);
4073: my $items='';
1.715 albertel 4074: foreach my $key (keys(%$storehash)) {
4075: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4076: }
1.715 albertel 4077: $items=~s/\&$//;
1.716 albertel 4078: my $esc_symb=&escape($symb);
4079: my $esc_v=&escape($version);
1.715 albertel 4080: my $reply =
1.716 albertel 4081: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4082: $uhome);
4083: if ($reply eq 'unknown_cmd') {
1.716 albertel 4084: # gfall back to way things use to be done
1.715 albertel 4085: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4086: $uname);
1.524 raeburn 4087: }
1.715 albertel 4088: return $reply;
4089: }
4090:
4091: sub old_putstore {
1.716 albertel 4092: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4093: if (!$udomain) { $udomain=$env{'user.domain'}; }
4094: if (!$uname) { $uname=$env{'user.name'}; }
4095: my $uhome=&homeserver($uname,$udomain);
4096: my %newstorehash;
1.800 albertel 4097: foreach my $item (keys(%$storehash)) {
4098: my $key = $version.':'.&escape($symb).':'.$item;
4099: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4100: }
4101: my $items='';
4102: my %allitems = ();
1.800 albertel 4103: foreach my $item (keys(%newstorehash)) {
4104: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4105: my $key = $1.':keys:'.$2;
4106: $allitems{$key} .= $3.':';
4107: }
1.800 albertel 4108: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4109: }
1.800 albertel 4110: foreach my $item (keys(%allitems)) {
4111: $allitems{$item} =~ s/\:$//;
4112: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4113: }
4114: $items=~s/\&$//;
4115: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4116: }
4117:
1.47 www 4118: # ------------------------------------------------------ critical put interface
4119:
4120: sub cput {
1.134 albertel 4121: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4122: if (!$udomain) { $udomain=$env{'user.domain'}; }
4123: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4124: my $uhome=&homeserver($uname,$udomain);
1.47 www 4125: my $items='';
1.800 albertel 4126: foreach my $item (keys(%$storehash)) {
4127: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4128: }
1.47 www 4129: $items=~s/\&$//;
1.134 albertel 4130: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4131: }
4132:
4133: # -------------------------------------------------------------- eget interface
4134:
4135: sub eget {
1.133 albertel 4136: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4137: my $items='';
1.800 albertel 4138: foreach my $item (@$storearr) {
4139: $items.=&escape($item).'&';
1.191 harris41 4140: }
1.12 www 4141: $items=~s/\&$//;
1.620 albertel 4142: if (!$udomain) { $udomain=$env{'user.domain'}; }
4143: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4144: my $uhome=&homeserver($uname,$udomain);
4145: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4146: my @pairs=split(/\&/,$rep);
4147: my %returnhash=();
1.42 www 4148: my $i=0;
1.800 albertel 4149: foreach my $item (@$storearr) {
4150: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4151: $i++;
1.191 harris41 4152: }
1.12 www 4153: return %returnhash;
4154: }
4155:
1.667 albertel 4156: # ------------------------------------------------------------ tmpput interface
4157: sub tmpput {
1.802 raeburn 4158: my ($storehash,$server,$context)=@_;
1.667 albertel 4159: my $items='';
1.800 albertel 4160: foreach my $item (keys(%$storehash)) {
4161: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4162: }
4163: $items=~s/\&$//;
1.802 raeburn 4164: if (defined($context)) {
4165: $items .= ':'.&escape($context);
4166: }
1.667 albertel 4167: return &reply("tmpput:$items",$server);
4168: }
4169:
4170: # ------------------------------------------------------------ tmpget interface
4171: sub tmpget {
1.688 albertel 4172: my ($token,$server)=@_;
4173: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4174: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4175: my %returnhash;
4176: foreach my $item (split(/\&/,$rep)) {
4177: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4178: next if ($key =~ /^error: 2 /);
1.667 albertel 4179: $returnhash{&unescape($key)}=&thaw_unescape($value);
4180: }
4181: return %returnhash;
4182: }
4183:
1.688 albertel 4184: # ------------------------------------------------------------ tmpget interface
4185: sub tmpdel {
4186: my ($token,$server)=@_;
4187: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4188: return &reply("tmpdel:$token",$server);
4189: }
4190:
1.765 albertel 4191: # -------------------------------------------------- portfolio access checking
4192:
4193: sub portfolio_access {
1.766 albertel 4194: my ($requrl) = @_;
1.765 albertel 4195: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4196: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4197: if ($result) {
4198: my %setters;
4199: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4200: my ($startblock,$endblock) =
4201: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4202: if ($startblock && $endblock) {
4203: return 'B';
4204: }
4205: } else {
4206: my ($startblock,$endblock) =
4207: &Apache::loncommon::blockcheck(\%setters,'port');
4208: if ($startblock && $endblock) {
4209: return 'B';
4210: }
4211: }
4212: }
1.765 albertel 4213: if ($result eq 'ok') {
1.766 albertel 4214: return 'F';
1.765 albertel 4215: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4216: return 'A';
1.765 albertel 4217: }
1.766 albertel 4218: return '';
1.765 albertel 4219: }
4220:
4221: sub get_portfolio_access {
1.767 albertel 4222: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4223:
4224: if (!ref($access_hash)) {
4225: my $current_perms = &get_portfile_permissions($udom,$unum);
4226: my %access_controls = &get_access_controls($current_perms,$group,
4227: $file_name);
4228: $access_hash = $access_controls{$file_name};
4229: }
4230:
1.765 albertel 4231: my ($public,$guest,@domains,@users,@courses,@groups);
4232: my $now = time;
4233: if (ref($access_hash) eq 'HASH') {
4234: foreach my $key (keys(%{$access_hash})) {
4235: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4236: if ($start > $now) {
4237: next;
4238: }
4239: if ($end && $end<$now) {
4240: next;
4241: }
4242: if ($scope eq 'public') {
4243: $public = $key;
4244: last;
4245: } elsif ($scope eq 'guest') {
4246: $guest = $key;
4247: } elsif ($scope eq 'domains') {
4248: push(@domains,$key);
4249: } elsif ($scope eq 'users') {
4250: push(@users,$key);
4251: } elsif ($scope eq 'course') {
4252: push(@courses,$key);
4253: } elsif ($scope eq 'group') {
4254: push(@groups,$key);
4255: }
4256: }
4257: if ($public) {
4258: return 'ok';
4259: }
4260: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4261: if ($guest) {
4262: return $guest;
4263: }
4264: } else {
4265: if (@domains > 0) {
4266: foreach my $domkey (@domains) {
4267: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4268: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4269: return 'ok';
4270: }
4271: }
4272: }
4273: }
4274: if (@users > 0) {
4275: foreach my $userkey (@users) {
1.865 raeburn 4276: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4277: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4278: if (ref($item) eq 'HASH') {
4279: if (($item->{'uname'} eq $env{'user.name'}) &&
4280: ($item->{'udom'} eq $env{'user.domain'})) {
4281: return 'ok';
4282: }
4283: }
4284: }
4285: }
1.765 albertel 4286: }
4287: }
4288: my %roleshash;
4289: my @courses_and_groups = @courses;
4290: push(@courses_and_groups,@groups);
4291: if (@courses_and_groups > 0) {
4292: my (%allgroups,%allroles);
4293: my ($start,$end,$role,$sec,$group);
4294: foreach my $envkey (%env) {
1.811 albertel 4295: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4296: my $cid = $2.'_'.$3;
4297: if ($1 eq 'gr') {
4298: $group = $4;
4299: $allgroups{$cid}{$group} = $env{$envkey};
4300: } else {
4301: if ($4 eq '') {
4302: $sec = 'none';
4303: } else {
4304: $sec = $4;
4305: }
4306: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4307: }
1.811 albertel 4308: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4309: my $cid = $2.'_'.$3;
4310: if ($4 eq '') {
4311: $sec = 'none';
4312: } else {
4313: $sec = $4;
4314: }
4315: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4316: }
4317: }
4318: if (keys(%allroles) == 0) {
4319: return;
4320: }
4321: foreach my $key (@courses_and_groups) {
4322: my %content = %{$$access_hash{$key}};
4323: my $cnum = $content{'number'};
4324: my $cdom = $content{'domain'};
4325: my $cid = $cdom.'_'.$cnum;
4326: if (!exists($allroles{$cid})) {
4327: next;
4328: }
4329: foreach my $role_id (keys(%{$content{'roles'}})) {
4330: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4331: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4332: my @status = @{$content{'roles'}{$role_id}{'access'}};
4333: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4334: foreach my $role (keys(%{$allroles{$cid}})) {
4335: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4336: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4337: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4338: if (grep/^all$/,@sections) {
4339: return 'ok';
4340: } else {
4341: if (grep/^$sec$/,@sections) {
4342: return 'ok';
4343: }
4344: }
4345: }
4346: }
4347: if (keys(%{$allgroups{$cid}}) == 0) {
4348: if (grep/^none$/,@groups) {
4349: return 'ok';
4350: }
4351: } else {
4352: if (grep/^all$/,@groups) {
4353: return 'ok';
4354: }
4355: foreach my $group (keys(%{$allgroups{$cid}})) {
4356: if (grep/^$group$/,@groups) {
4357: return 'ok';
4358: }
4359: }
4360: }
4361: }
4362: }
4363: }
4364: }
4365: }
4366: if ($guest) {
4367: return $guest;
4368: }
4369: }
4370: }
4371: return;
4372: }
4373:
4374: sub course_group_datechecker {
4375: my ($dates,$now,$status) = @_;
4376: my ($start,$end) = split(/\./,$dates);
4377: if (!$start && !$end) {
4378: return 'ok';
4379: }
4380: if (grep/^active$/,@{$status}) {
4381: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4382: return 'ok';
4383: }
4384: }
4385: if (grep/^previous$/,@{$status}) {
4386: if ($end > $now ) {
4387: return 'ok';
4388: }
4389: }
4390: if (grep/^future$/,@{$status}) {
4391: if ($start > $now) {
4392: return 'ok';
4393: }
4394: }
4395: return;
4396: }
4397:
4398: sub parse_portfolio_url {
4399: my ($url) = @_;
4400:
4401: my ($type,$udom,$unum,$group,$file_name);
4402:
1.823 albertel 4403: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4404: $type = 1;
4405: $udom = $1;
4406: $unum = $2;
4407: $file_name = $3;
1.823 albertel 4408: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4409: $type = 2;
4410: $udom = $1;
4411: $unum = $2;
4412: $group = $3;
4413: $file_name = $3.'/'.$4;
4414: }
4415: if (wantarray) {
4416: return ($type,$udom,$unum,$file_name,$group);
4417: }
4418: return $type;
4419: }
4420:
4421: sub is_portfolio_url {
4422: my ($url) = @_;
4423: return scalar(&parse_portfolio_url($url));
4424: }
4425:
1.798 raeburn 4426: sub is_portfolio_file {
4427: my ($file) = @_;
1.820 raeburn 4428: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4429: return 1;
4430: }
4431: return;
4432: }
4433:
1.976 raeburn 4434: sub usertools_access {
1.985 ! raeburn 4435: my ($uname,$udom,$tool,$action,$context) = @_;
! 4436: my ($access,%tools);
! 4437: if ($context eq '') {
! 4438: $context = 'tools';
! 4439: }
! 4440: if ($context eq 'requestcourses') {
! 4441: %tools = (
! 4442: official => 1,
! 4443: unofficial => 1,
! 4444: );
! 4445: } else {
! 4446: %tools = (
! 4447: aboutme => 1,
! 4448: blog => 1,
! 4449: portfolio => 1,
! 4450: );
! 4451: }
1.976 raeburn 4452: return if (!defined($tools{$tool}));
4453:
4454: if ((!defined($udom)) || (!defined($uname))) {
4455: $udom = $env{'user.domain'};
4456: $uname = $env{'user.name'};
4457: }
4458:
1.978 raeburn 4459: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4460: if ($action ne 'reload') {
1.985 ! raeburn 4461: if ($context eq 'requestcourses') {
! 4462: return $env{'environment.canrequest.'.$tool};
! 4463: } else {
! 4464: return $env{'environment.availabletools.'.$tool};
! 4465: }
! 4466: }
1.976 raeburn 4467: }
4468:
4469: my ($toolstatus,$inststatus);
4470:
1.985 ! raeburn 4471: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
! 4472: ($action ne 'reload')) {
! 4473: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4474: $inststatus = $env{'environment.inststatus'};
4475: } else {
1.985 ! raeburn 4476: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
! 4477: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4478: $inststatus = $userenv{'inststatus'};
4479: }
4480:
4481: if ($toolstatus ne '') {
4482: if ($toolstatus) {
4483: $access = 1;
4484: } else {
4485: $access = 0;
4486: }
4487: return $access;
4488: }
4489:
4490: my $is_adv = &is_advanced_user($udom,$uname);
4491: my %domdef = &get_domain_defaults($udom);
4492: if (ref($domdef{$tool}) eq 'HASH') {
4493: if ($is_adv) {
4494: if ($domdef{$tool}{'_LC_adv'} ne '') {
4495: if ($domdef{$tool}{'_LC_adv'}) {
4496: $access = 1;
4497: } else {
4498: $access = 0;
4499: }
4500: return $access;
4501: }
4502: }
4503: if ($inststatus ne '') {
4504: my ($hasaccess,$hasnoaccess);
4505: foreach my $affiliation (split(/:/,$inststatus)) {
4506: if ($domdef{$tool}{$affiliation} ne '') {
4507: if ($domdef{$tool}{$affiliation}) {
4508: $hasaccess = 1;
4509: } else {
4510: $hasnoaccess = 1;
4511: }
4512: }
4513: }
4514: if ($hasaccess || $hasnoaccess) {
4515: if ($hasaccess) {
4516: $access = 1;
4517: } elsif ($hasnoaccess) {
4518: $access = 0;
4519: }
4520: return $access;
4521: }
4522: } else {
4523: if ($domdef{$tool}{'default'} ne '') {
4524: if ($domdef{$tool}{'default'}) {
4525: $access = 1;
4526: } elsif ($domdef{$tool}{'default'} == 0) {
4527: $access = 0;
4528: }
4529: return $access;
4530: }
4531: }
4532: } else {
1.985 ! raeburn 4533: if ($context eq 'tools') {
! 4534: $access = 1;
! 4535: } else {
! 4536: $access = 0;
! 4537: }
1.976 raeburn 4538: return $access;
4539: }
4540: }
4541:
4542: sub is_advanced_user {
4543: my ($udom,$uname) = @_;
4544: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4545: my %allroles;
4546: my $is_adv;
4547: foreach my $role (keys(%roleshash)) {
4548: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4549: my $area = '/'.$tdomain.'/'.$trest;
4550: if ($sec ne '') {
4551: $area .= '/'.$sec;
4552: }
4553: if (($area ne '') && ($trole ne '')) {
4554: my $spec=$trole.'.'.$area;
4555: if ($trole =~ /^cr\//) {
4556: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4557: } elsif ($trole ne 'gr') {
4558: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4559: }
4560: }
4561: }
4562: foreach my $role (keys(%allroles)) {
4563: last if ($is_adv);
4564: foreach my $item (split(/:/,$allroles{$role})) {
4565: if ($item ne '') {
4566: my ($privilege,$restrictions)=split(/&/,$item);
4567: if ($privilege eq 'adv') {
4568: $is_adv = 1;
4569: last;
4570: }
4571: }
4572: }
4573: }
4574: return $is_adv;
4575: }
1.798 raeburn 4576:
1.341 www 4577: # ---------------------------------------------- Custom access rule evaluation
4578:
4579: sub customaccess {
4580: my ($priv,$uri)=@_;
1.807 albertel 4581: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4582: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4583: $udom = &LONCAPA::clean_domain($udom);
4584: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4585: my $access=0;
1.800 albertel 4586: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4587: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4588: if ($type eq 'user') {
4589: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4590: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4591: if ($tdom) {
4592: if ($tdom ne $env{'user.domain'}) { next; }
4593: }
1.896 albertel 4594: if ($tuname) {
4595: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4596: }
4597: $access=($effect eq 'allow');
4598: last;
4599: }
4600: } else {
4601: if ($role) {
4602: if ($role ne $urole) { next; }
4603: }
4604: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4605: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4606: if ($tdom) {
4607: if ($tdom ne $udom) { next; }
4608: }
4609: if ($tcrs) {
4610: if ($tcrs ne $ucrs) { next; }
4611: }
4612: if ($tsec) {
4613: if ($tsec ne $usec) { next; }
4614: }
4615: $access=($effect eq 'allow');
4616: last;
4617: }
4618: if ($realm eq '' && $role eq '') {
4619: $access=($effect eq 'allow');
4620: }
1.402 bowersj2 4621: }
1.341 www 4622: }
4623: return $access;
4624: }
4625:
1.103 harris41 4626: # ------------------------------------------------- Check for a user privilege
1.12 www 4627:
4628: sub allowed {
1.810 raeburn 4629: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4630: my $ver_orguri=$uri;
1.439 www 4631: $uri=&deversion($uri);
1.152 www 4632: my $orguri=$uri;
1.52 www 4633: $uri=&declutter($uri);
1.809 raeburn 4634:
1.810 raeburn 4635: if ($priv eq 'evb') {
4636: # Evade communication block restrictions for specified role in a course
4637: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4638: return $1;
4639: } else {
4640: return;
4641: }
4642: }
4643:
1.620 albertel 4644: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4645: # Free bre access to adm and meta resources
1.775 albertel 4646: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4647: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4648: && ($priv eq 'bre')) {
1.14 www 4649: return 'F';
1.159 www 4650: }
4651:
1.545 banghart 4652: # Free bre access to user's own portfolio contents
1.714 raeburn 4653: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4654: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4655: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4656: my %setters;
4657: my ($startblock,$endblock) =
4658: &Apache::loncommon::blockcheck(\%setters,'port');
4659: if ($startblock && $endblock) {
4660: return 'B';
4661: } else {
4662: return 'F';
4663: }
1.545 banghart 4664: }
4665:
1.762 raeburn 4666: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4667: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4668: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4669: if (exists($env{'request.course.id'})) {
4670: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4671: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4672: if (($domain eq $cdom) && ($name eq $cnum)) {
4673: my $courseprivid=$env{'request.course.id'};
4674: $courseprivid=~s/\_/\//;
4675: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4676: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4677: return $1;
1.762 raeburn 4678: } else {
4679: if ($env{'request.course.sec'}) {
4680: $courseprivid.='/'.$env{'request.course.sec'};
4681: }
4682: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4683: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4684: return $2;
4685: }
1.714 raeburn 4686: }
4687: }
4688: }
4689: }
4690:
1.159 www 4691: # Free bre to public access
4692:
4693: if ($priv eq 'bre') {
1.238 www 4694: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4695: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4696: return 'F';
4697: }
1.238 www 4698: if ($copyright eq 'priv') {
4699: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4700: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4701: return '';
4702: }
4703: }
4704: if ($copyright eq 'domain') {
4705: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4706: unless (($env{'user.domain'} eq $1) ||
4707: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4708: return '';
4709: }
1.262 matthew 4710: }
1.620 albertel 4711: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4712: # Library role, so allow browsing of resources in this domain.
4713: return 'F';
1.238 www 4714: }
1.341 www 4715: if ($copyright eq 'custom') {
4716: unless (&customaccess($priv,$uri)) { return ''; }
4717: }
1.14 www 4718: }
1.264 matthew 4719: # Domain coordinator is trying to create a course
1.620 albertel 4720: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4721: # uri is the requested domain in this case.
4722: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4723: # a role of dc for the domain in question.
1.620 albertel 4724: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4725: }
1.29 www 4726:
1.52 www 4727: my $thisallowed='';
4728: my $statecond=0;
4729: my $courseprivid='';
4730:
4731: # Course
4732:
1.620 albertel 4733: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4734: $thisallowed.=$1;
4735: }
1.29 www 4736:
1.52 www 4737: # Domain
4738:
1.620 albertel 4739: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4740: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4741: $thisallowed.=$1;
4742: }
1.52 www 4743:
4744: # Course: uri itself is a course
1.66 www 4745: my $courseuri=$uri;
4746: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4747: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4748:
1.620 albertel 4749: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4750: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4751: $thisallowed.=$1;
4752: }
1.29 www 4753:
1.665 albertel 4754: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4755: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4756: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4757: $thisallowed='';
1.671 raeburn 4758: my ($match)=&is_on_map($uri);
4759: if ($match) {
4760: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4761: =~/\Q$priv\E\&([^\:]*)/) {
4762: $thisallowed.=$1;
4763: }
4764: } else {
1.705 albertel 4765: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4766: if ($refuri) {
4767: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4768: $thisallowed='F';
1.671 raeburn 4769: } else {
4770: $refuri=&declutter($refuri);
4771: my ($match) = &is_on_map($refuri);
4772: if ($match) {
4773: $thisallowed='F';
4774: }
1.669 raeburn 4775: }
1.671 raeburn 4776: }
4777: }
1.314 www 4778: }
1.492 albertel 4779:
1.766 albertel 4780: if ($priv eq 'bre'
4781: && $thisallowed ne 'F'
4782: && $thisallowed ne '2'
4783: && &is_portfolio_url($uri)) {
4784: $thisallowed = &portfolio_access($uri);
4785: }
4786:
1.52 www 4787: # Full access at system, domain or course-wide level? Exit.
1.29 www 4788: if ($thisallowed=~/F/) {
4789: return 'F';
4790: }
4791:
1.52 www 4792: # If this is generating or modifying users, exit with special codes
1.29 www 4793:
1.643 www 4794: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4795: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4796: my ($audom,$auname)=split('/',$uri);
1.643 www 4797: # no author name given, so this just checks on the general right to make a co-author in this domain
4798: unless ($auname) { return $thisallowed; }
4799: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4800: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4801: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4802: ($audom ne $env{'request.role.domain'}))) { return ''; }
4803: }
1.52 www 4804: return $thisallowed;
4805: }
4806: #
1.103 harris41 4807: # Gathered so far: system, domain and course wide privileges
1.52 www 4808: #
4809: # Course: See if uri or referer is an individual resource that is part of
4810: # the course
4811:
1.620 albertel 4812: if ($env{'request.course.id'}) {
1.232 www 4813:
1.620 albertel 4814: $courseprivid=$env{'request.course.id'};
4815: if ($env{'request.course.sec'}) {
4816: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4817: }
4818: $courseprivid=~s/\_/\//;
4819: my $checkreferer=1;
1.232 www 4820: my ($match,$cond)=&is_on_map($uri);
4821: if ($match) {
4822: $statecond=$cond;
1.620 albertel 4823: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4824: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4825: $thisallowed.=$1;
4826: $checkreferer=0;
4827: }
1.29 www 4828: }
1.83 www 4829:
1.148 www 4830: if ($checkreferer) {
1.620 albertel 4831: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4832: unless ($refuri) {
1.800 albertel 4833: foreach my $key (keys(%env)) {
4834: if ($key=~/^httpref\..*\*/) {
4835: my $pattern=$key;
1.156 www 4836: $pattern=~s/^httpref\.\/res\///;
1.148 www 4837: $pattern=~s/\*/\[\^\/\]\+/g;
4838: $pattern=~s/\//\\\//g;
1.152 www 4839: if ($orguri=~/$pattern/) {
1.800 albertel 4840: $refuri=$env{$key};
1.148 www 4841: }
4842: }
1.191 harris41 4843: }
1.148 www 4844: }
1.232 www 4845:
1.148 www 4846: if ($refuri) {
1.152 www 4847: $refuri=&declutter($refuri);
1.232 www 4848: my ($match,$cond)=&is_on_map($refuri);
4849: if ($match) {
4850: my $refstatecond=$cond;
1.620 albertel 4851: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4852: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4853: $thisallowed.=$1;
1.53 www 4854: $uri=$refuri;
4855: $statecond=$refstatecond;
1.52 www 4856: }
4857: }
1.148 www 4858: }
1.29 www 4859: }
1.52 www 4860: }
1.29 www 4861:
1.52 www 4862: #
1.103 harris41 4863: # Gathered now: all privileges that could apply, and condition number
1.52 www 4864: #
4865: #
4866: # Full or no access?
4867: #
1.29 www 4868:
1.52 www 4869: if ($thisallowed=~/F/) {
4870: return 'F';
4871: }
1.29 www 4872:
1.52 www 4873: unless ($thisallowed) {
4874: return '';
4875: }
1.29 www 4876:
1.52 www 4877: # Restrictions exist, deal with them
4878: #
4879: # C:according to course preferences
4880: # R:according to resource settings
4881: # L:unless locked
4882: # X:according to user session state
4883: #
4884:
4885: # Possibly locked functionality, check all courses
1.54 www 4886: # Locks might take effect only after 10 minutes cache expiration for other
4887: # courses, and 2 minutes for current course
1.52 www 4888:
4889: my $envkey;
4890: if ($thisallowed=~/L/) {
1.620 albertel 4891: foreach $envkey (keys %env) {
1.54 www 4892: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4893: my $courseid=$2;
4894: my $roleid=$1.'.'.$2;
1.92 www 4895: $courseid=~s/^\///;
1.54 www 4896: my $expiretime=600;
1.620 albertel 4897: if ($env{'request.role'} eq $roleid) {
1.54 www 4898: $expiretime=120;
4899: }
4900: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4901: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4902: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4903: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4904: }
1.620 albertel 4905: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4906: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4907: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4908: &log($env{'user.domain'},$env{'user.name'},
4909: $env{'user.home'},
1.57 www 4910: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4911: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4912: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4913: return '';
4914: }
4915: }
1.620 albertel 4916: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4917: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4918: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4919: &log($env{'user.domain'},$env{'user.name'},
4920: $env{'user.home'},
1.57 www 4921: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4922: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4923: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4924: return '';
4925: }
4926: }
4927: }
1.29 www 4928: }
1.52 www 4929: }
4930:
4931: #
4932: # Rest of the restrictions depend on selected course
4933: #
4934:
1.620 albertel 4935: unless ($env{'request.course.id'}) {
1.766 albertel 4936: if ($thisallowed eq 'A') {
4937: return 'A';
1.814 raeburn 4938: } elsif ($thisallowed eq 'B') {
4939: return 'B';
1.766 albertel 4940: } else {
4941: return '1';
4942: }
1.52 www 4943: }
1.29 www 4944:
1.52 www 4945: #
4946: # Now user is definitely in a course
4947: #
1.53 www 4948:
4949:
4950: # Course preferences
4951:
4952: if ($thisallowed=~/C/) {
1.620 albertel 4953: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4954: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4955: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4956: =~/\Q$rolecode\E/) {
1.689 albertel 4957: if ($priv ne 'pch') {
4958: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4959: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4960: $env{'request.course.id'});
4961: }
1.237 www 4962: return '';
4963: }
4964:
1.620 albertel 4965: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4966: =~/\Q$unamedom\E/) {
1.689 albertel 4967: if ($priv ne 'pch') {
4968: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4969: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4970: $env{'request.course.id'});
4971: }
1.54 www 4972: return '';
4973: }
1.53 www 4974: }
4975:
4976: # Resource preferences
4977:
4978: if ($thisallowed=~/R/) {
1.620 albertel 4979: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4980: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4981: if ($priv ne 'pch') {
4982: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4983: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4984: }
4985: return '';
1.54 www 4986: }
1.53 www 4987: }
1.30 www 4988:
1.246 www 4989: # Restricted by state or randomout?
1.30 www 4990:
1.52 www 4991: if ($thisallowed=~/X/) {
1.620 albertel 4992: if ($env{'acc.randomout'}) {
1.579 albertel 4993: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4994: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4995: return '';
4996: }
1.247 www 4997: }
4998: if (&condval($statecond)) {
1.52 www 4999: return '2';
5000: } else {
5001: return '';
5002: }
5003: }
1.30 www 5004:
1.766 albertel 5005: if ($thisallowed eq 'A') {
5006: return 'A';
1.814 raeburn 5007: } elsif ($thisallowed eq 'B') {
5008: return 'B';
1.766 albertel 5009: }
1.52 www 5010: return 'F';
1.232 www 5011: }
5012:
1.710 albertel 5013: sub split_uri_for_cond {
5014: my $uri=&deversion(&declutter(shift));
5015: my @uriparts=split(/\//,$uri);
5016: my $filename=pop(@uriparts);
5017: my $pathname=join('/',@uriparts);
5018: return ($pathname,$filename);
5019: }
1.232 www 5020: # --------------------------------------------------- Is a resource on the map?
5021:
5022: sub is_on_map {
1.710 albertel 5023: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5024: #Trying to find the conditional for the file
1.620 albertel 5025: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5026: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5027: if ($match) {
1.289 bowersj2 5028: return (1,$1);
5029: } else {
1.434 www 5030: return (0,0);
1.289 bowersj2 5031: }
1.12 www 5032: }
5033:
1.427 www 5034: # --------------------------------------------------------- Get symb from alias
5035:
5036: sub get_symb_from_alias {
5037: my $symb=shift;
5038: my ($map,$resid,$url)=&decode_symb($symb);
5039: # Already is a symb
5040: if ($url) { return $symb; }
5041: # Must be an alias
5042: my $aliassymb='';
5043: my %bighash;
1.620 albertel 5044: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5045: &GDBM_READER(),0640)) {
5046: my $rid=$bighash{'mapalias_'.$symb};
5047: if ($rid) {
5048: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5049: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5050: $resid,$bighash{'src_'.$rid});
1.427 www 5051: }
5052: untie %bighash;
5053: }
5054: return $aliassymb;
5055: }
5056:
1.12 www 5057: # ----------------------------------------------------------------- Define Role
5058:
5059: sub definerole {
5060: if (allowed('mcr','/')) {
5061: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5062: foreach my $role (split(':',$sysrole)) {
5063: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5064: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5065: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5066: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5067: return "refused:s:$crole&$cqual";
5068: }
5069: }
1.191 harris41 5070: }
1.800 albertel 5071: foreach my $role (split(':',$domrole)) {
5072: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5073: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5074: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5075: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5076: return "refused:d:$crole&$cqual";
5077: }
5078: }
1.191 harris41 5079: }
1.800 albertel 5080: foreach my $role (split(':',$courole)) {
5081: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5082: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5083: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5084: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5085: return "refused:c:$crole&$cqual";
5086: }
5087: }
1.191 harris41 5088: }
1.620 albertel 5089: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5090: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5091: "rolesdef_$rolename=".
5092: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5093: return reply($command,$env{'user.home'});
1.12 www 5094: } else {
5095: return 'refused';
5096: }
1.105 harris41 5097: }
5098:
5099: # ---------------- Make a metadata query against the network of library servers
5100:
5101: sub metadata_query {
1.244 matthew 5102: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5103: my %rhash;
1.845 albertel 5104: my %libserv = &all_library();
1.244 matthew 5105: my @server_list = (defined($server_array) ? @$server_array
5106: : keys(%libserv) );
5107: for my $server (@server_list) {
1.118 harris41 5108: unless ($custom or $customshow) {
5109: my $reply=&reply("querysend:".&escape($query),$server);
5110: $rhash{$server}=$reply;
5111: }
5112: else {
5113: my $reply=&reply("querysend:".&escape($query).':'.
5114: &escape($custom).':'.&escape($customshow),
5115: $server);
5116: $rhash{$server}=$reply;
5117: }
1.112 harris41 5118: }
1.118 harris41 5119: return \%rhash;
1.240 www 5120: }
5121:
5122: # ----------------------------------------- Send log queries and wait for reply
5123:
5124: sub log_query {
5125: my ($uname,$udom,$query,%filters)=@_;
5126: my $uhome=&homeserver($uname,$udom);
5127: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5128: my $uhost=&hostname($uhome);
1.800 albertel 5129: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5130: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5131: $uhome);
1.479 albertel 5132: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5133: return get_query_reply($queryid);
5134: }
5135:
1.818 raeburn 5136: # -------------------------- Update MySQL table for portfolio file
5137:
5138: sub update_portfolio_table {
1.821 raeburn 5139: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5140: if ($group ne '') {
5141: $file_name =~s /^\Q$group\E//;
5142: }
1.818 raeburn 5143: my $homeserver = &homeserver($uname,$udom);
5144: my $queryid=
1.821 raeburn 5145: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5146: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5147: my $reply = &get_query_reply($queryid);
5148: return $reply;
5149: }
5150:
1.899 raeburn 5151: # -------------------------- Update MySQL allusers table
5152:
5153: sub update_allusers_table {
5154: my ($uname,$udom,$names) = @_;
5155: my $homeserver = &homeserver($uname,$udom);
5156: my $queryid=
5157: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5158: 'lastname='.&escape($names->{'lastname'}).'%%'.
5159: 'firstname='.&escape($names->{'firstname'}).'%%'.
5160: 'middlename='.&escape($names->{'middlename'}).'%%'.
5161: 'generation='.&escape($names->{'generation'}).'%%'.
5162: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5163: 'id='.&escape($names->{'id'}),$homeserver);
5164: my $reply = &get_query_reply($queryid);
5165: return $reply;
5166: }
5167:
1.508 raeburn 5168: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5169:
5170: sub fetch_enrollment_query {
1.511 raeburn 5171: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5172: my $homeserver;
1.547 raeburn 5173: my $maxtries = 1;
1.508 raeburn 5174: if ($context eq 'automated') {
5175: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5176: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5177: } else {
5178: $homeserver = &homeserver($cnum,$dom);
5179: }
1.838 albertel 5180: my $host=&hostname($homeserver);
1.506 raeburn 5181: my $cmd = '';
1.800 albertel 5182: foreach my $affiliate (keys %{$affiliatesref}) {
5183: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5184: }
5185: $cmd =~ s/%%$//;
5186: $cmd = &escape($cmd);
5187: my $query = 'fetchenrollment';
1.620 albertel 5188: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5189: unless ($queryid=~/^\Q$host\E\_/) {
5190: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5191: return 'error: '.$queryid;
5192: }
1.506 raeburn 5193: my $reply = &get_query_reply($queryid);
1.547 raeburn 5194: my $tries = 1;
5195: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5196: $reply = &get_query_reply($queryid);
5197: $tries ++;
5198: }
1.526 raeburn 5199: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5200: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5201: } else {
1.901 albertel 5202: my @responses = split(/:/,$reply);
1.515 raeburn 5203: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5204: foreach my $line (@responses) {
5205: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5206: $$replyref{$key} = $value;
5207: }
5208: } else {
1.506 raeburn 5209: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5210: foreach my $line (@responses) {
5211: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5212: $$replyref{$key} = $value;
5213: if ($value > 0) {
1.800 albertel 5214: foreach my $item (@{$$affiliatesref{$key}}) {
5215: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5216: my $destname = $pathname.'/'.$filename;
5217: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5218: if ($xml_classlist =~ /^error/) {
5219: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5220: } else {
1.506 raeburn 5221: if ( open(FILE,">$destname") ) {
5222: print FILE &unescape($xml_classlist);
5223: close(FILE);
1.526 raeburn 5224: } else {
5225: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5226: }
5227: }
5228: }
5229: }
5230: }
5231: }
5232: return 'ok';
5233: }
5234: return 'error';
5235: }
5236:
1.242 www 5237: sub get_query_reply {
5238: my $queryid=shift;
1.240 www 5239: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5240: my $reply='';
5241: for (1..100) {
5242: sleep 2;
5243: if (-e $replyfile.'.end') {
1.448 albertel 5244: if (open(my $fh,$replyfile)) {
1.904 albertel 5245: $reply = join('',<$fh>);
5246: close($fh);
1.240 www 5247: } else { return 'error: reply_file_error'; }
1.242 www 5248: return &unescape($reply);
5249: }
1.240 www 5250: }
1.242 www 5251: return 'timeout:'.$queryid;
1.240 www 5252: }
5253:
5254: sub courselog_query {
1.241 www 5255: #
5256: # possible filters:
5257: # url: url or symb
5258: # username
5259: # domain
5260: # action: view, submit, grade
5261: # start: timestamp
5262: # end: timestamp
5263: #
1.240 www 5264: my (%filters)=@_;
1.620 albertel 5265: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5266: if ($filters{'url'}) {
5267: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5268: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5269: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5270: }
1.620 albertel 5271: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5272: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5273: return &log_query($cname,$cdom,'courselog',%filters);
5274: }
5275:
5276: sub userlog_query {
1.858 raeburn 5277: #
5278: # possible filters:
5279: # action: log check role
5280: # start: timestamp
5281: # end: timestamp
5282: #
1.240 www 5283: my ($uname,$udom,%filters)=@_;
5284: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5285: }
5286:
1.506 raeburn 5287: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5288:
5289: sub auto_run {
1.508 raeburn 5290: my ($cnum,$cdom) = @_;
1.876 raeburn 5291: my $response = 0;
5292: my $settings;
5293: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5294: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5295: $settings = $domconfig{'autoenroll'};
5296: if ($settings->{'run'} eq '1') {
5297: $response = 1;
5298: }
5299: } else {
1.934 raeburn 5300: my $homeserver;
5301: if (&is_course($cdom,$cnum)) {
5302: $homeserver = &homeserver($cnum,$cdom);
5303: } else {
5304: $homeserver = &domain($cdom,'primary');
5305: }
5306: if ($homeserver ne 'no_host') {
5307: $response = &reply('autorun:'.$cdom,$homeserver);
5308: }
1.876 raeburn 5309: }
1.506 raeburn 5310: return $response;
5311: }
1.776 albertel 5312:
1.506 raeburn 5313: sub auto_get_sections {
1.508 raeburn 5314: my ($cnum,$cdom,$inst_coursecode) = @_;
5315: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5316: my @secs = ();
1.511 raeburn 5317: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5318: unless ($response eq 'refused') {
1.901 albertel 5319: @secs = split(/:/,$response);
1.506 raeburn 5320: }
5321: return @secs;
5322: }
1.776 albertel 5323:
1.506 raeburn 5324: sub auto_new_course {
1.508 raeburn 5325: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5326: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5327: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5328: return $response;
5329: }
1.776 albertel 5330:
1.506 raeburn 5331: sub auto_validate_courseID {
1.508 raeburn 5332: my ($cnum,$cdom,$inst_course_id) = @_;
5333: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5334: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5335: return $response;
5336: }
1.776 albertel 5337:
1.506 raeburn 5338: sub auto_create_password {
1.873 raeburn 5339: my ($cnum,$cdom,$authparam,$udom) = @_;
5340: my ($homeserver,$response);
1.506 raeburn 5341: my $create_passwd = 0;
5342: my $authchk = '';
1.873 raeburn 5343: if ($udom =~ /^$match_domain$/) {
5344: $homeserver = &domain($udom,'primary');
5345: }
5346: if ($homeserver eq '') {
5347: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5348: $homeserver = &homeserver($cnum,$cdom);
5349: }
5350: }
5351: if ($homeserver eq '') {
5352: $authchk = 'nodomain';
1.506 raeburn 5353: } else {
1.873 raeburn 5354: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5355: if ($response eq 'refused') {
5356: $authchk = 'refused';
5357: } else {
1.901 albertel 5358: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5359: }
1.506 raeburn 5360: }
5361: return ($authparam,$create_passwd,$authchk);
5362: }
5363:
1.706 raeburn 5364: sub auto_photo_permission {
5365: my ($cnum,$cdom,$students) = @_;
5366: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5367: my ($outcome,$perm_reqd,$conditions) =
5368: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5369: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5370: return (undef,undef);
5371: }
1.706 raeburn 5372: return ($outcome,$perm_reqd,$conditions);
5373: }
5374:
5375: sub auto_checkphotos {
5376: my ($uname,$udom,$pid) = @_;
5377: my $homeserver = &homeserver($uname,$udom);
5378: my ($result,$resulttype);
5379: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5380: &escape($uname).':'.&escape($pid),
5381: $homeserver));
1.709 albertel 5382: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5383: return (undef,undef);
5384: }
1.706 raeburn 5385: if ($outcome) {
5386: ($result,$resulttype) = split(/:/,$outcome);
5387: }
5388: return ($result,$resulttype);
5389: }
5390:
5391: sub auto_photochoice {
5392: my ($cnum,$cdom) = @_;
5393: my $homeserver = &homeserver($cnum,$cdom);
5394: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5395: &escape($cdom),
5396: $homeserver)));
1.709 albertel 5397: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5398: return (undef,undef);
5399: }
1.706 raeburn 5400: return ($update,$comment);
5401: }
5402:
5403: sub auto_photoupdate {
5404: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5405: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5406: my $host=&hostname($homeserver);
1.706 raeburn 5407: my $cmd = '';
5408: my $maxtries = 1;
1.800 albertel 5409: foreach my $affiliate (keys(%{$affiliatesref})) {
5410: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5411: }
5412: $cmd =~ s/%%$//;
5413: $cmd = &escape($cmd);
5414: my $query = 'institutionalphotos';
5415: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5416: unless ($queryid=~/^\Q$host\E\_/) {
5417: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5418: return 'error: '.$queryid;
5419: }
5420: my $reply = &get_query_reply($queryid);
5421: my $tries = 1;
5422: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5423: $reply = &get_query_reply($queryid);
5424: $tries ++;
5425: }
5426: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5427: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5428: } else {
5429: my @responses = split(/:/,$reply);
5430: my $outcome = shift(@responses);
5431: foreach my $item (@responses) {
5432: my ($key,$value) = split(/=/,$item);
5433: $$photo{$key} = $value;
5434: }
5435: return $outcome;
5436: }
5437: return 'error';
5438: }
5439:
1.521 raeburn 5440: sub auto_instcode_format {
1.793 albertel 5441: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5442: $cat_order) = @_;
1.521 raeburn 5443: my $courses = '';
1.772 raeburn 5444: my @homeservers;
1.521 raeburn 5445: if ($caller eq 'global') {
1.841 albertel 5446: my %servers = &get_servers($codedom,'library');
5447: foreach my $tryserver (keys(%servers)) {
5448: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5449: push(@homeservers,$tryserver);
5450: }
1.584 raeburn 5451: }
1.521 raeburn 5452: } else {
1.772 raeburn 5453: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5454: }
1.793 albertel 5455: foreach my $code (keys(%{$instcodes})) {
5456: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5457: }
5458: chop($courses);
1.772 raeburn 5459: my $ok_response = 0;
5460: my $response;
5461: while (@homeservers > 0 && $ok_response == 0) {
5462: my $server = shift(@homeservers);
5463: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5464: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5465: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5466: split(/:/,$response);
1.772 raeburn 5467: %{$codes} = (%{$codes},&str2hash($codes_str));
5468: push(@{$codetitles},&str2array($codetitles_str));
5469: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5470: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5471: $ok_response = 1;
5472: }
5473: }
5474: if ($ok_response) {
1.521 raeburn 5475: return 'ok';
1.772 raeburn 5476: } else {
5477: return $response;
1.521 raeburn 5478: }
5479: }
5480:
1.792 raeburn 5481: sub auto_instcode_defaults {
5482: my ($domain,$returnhash,$code_order) = @_;
5483: my @homeservers;
1.841 albertel 5484:
5485: my %servers = &get_servers($domain,'library');
5486: foreach my $tryserver (keys(%servers)) {
5487: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5488: push(@homeservers,$tryserver);
5489: }
1.792 raeburn 5490: }
1.841 albertel 5491:
1.792 raeburn 5492: my $response;
1.841 albertel 5493: foreach my $server (@homeservers) {
1.792 raeburn 5494: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5495: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5496:
5497: foreach my $pair (split(/\&/,$response)) {
5498: my ($name,$value)=split(/\=/,$pair);
5499: if ($name eq 'code_order') {
5500: @{$code_order} = split(/\&/,&unescape($value));
5501: } else {
5502: $returnhash->{&unescape($name)}=&unescape($value);
5503: }
5504: }
5505: return 'ok';
1.792 raeburn 5506: }
1.841 albertel 5507:
5508: return $response;
1.792 raeburn 5509: }
5510:
1.777 albertel 5511: sub auto_validate_class_sec {
1.918 raeburn 5512: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5513: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5514: my $ownerlist;
5515: if (ref($owners) eq 'ARRAY') {
5516: $ownerlist = join(',',@{$owners});
5517: } else {
5518: $ownerlist = $owners;
5519: }
1.773 raeburn 5520: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5521: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5522: return $response;
5523: }
5524:
1.679 raeburn 5525: # ------------------------------------------------------- Course Group routines
5526:
5527: sub get_coursegroups {
1.809 raeburn 5528: my ($cdom,$cnum,$group,$namespace) = @_;
5529: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5530: }
5531:
1.679 raeburn 5532: sub modify_coursegroup {
5533: my ($cdom,$cnum,$groupsettings) = @_;
5534: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5535: }
5536:
1.809 raeburn 5537: sub toggle_coursegroup_status {
5538: my ($cdom,$cnum,$group,$action) = @_;
5539: my ($from_namespace,$to_namespace);
5540: if ($action eq 'delete') {
5541: $from_namespace = 'coursegroups';
5542: $to_namespace = 'deleted_groups';
5543: } else {
5544: $from_namespace = 'deleted_groups';
5545: $to_namespace = 'coursegroups';
5546: }
5547: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5548: if (my $tmp = &error(%curr_group)) {
5549: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5550: return ('read error',$tmp);
5551: } else {
5552: my %savedsettings = %curr_group;
1.809 raeburn 5553: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5554: my $deloutcome;
5555: if ($result eq 'ok') {
1.809 raeburn 5556: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5557: } else {
5558: return ('write error',$result);
5559: }
5560: if ($deloutcome eq 'ok') {
5561: return 'ok';
5562: } else {
5563: return ('delete error',$deloutcome);
5564: }
5565: }
5566: }
5567:
1.679 raeburn 5568: sub modify_group_roles {
1.957 raeburn 5569: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5570: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5571: my $role = 'gr/'.&escape($userprivs);
5572: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5573: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5574: if ($result eq 'ok') {
5575: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5576: }
1.679 raeburn 5577: return $result;
5578: }
5579:
5580: sub modify_coursegroup_membership {
5581: my ($cdom,$cnum,$membership) = @_;
5582: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5583: return $result;
5584: }
5585:
1.682 raeburn 5586: sub get_active_groups {
5587: my ($udom,$uname,$cdom,$cnum) = @_;
5588: my $now = time;
5589: my %groups = ();
5590: foreach my $key (keys(%env)) {
1.811 albertel 5591: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5592: my ($start,$end) = split(/\./,$env{$key});
5593: if (($end!=0) && ($end<$now)) { next; }
5594: if (($start!=0) && ($start>$now)) { next; }
5595: if ($1 eq $cdom && $2 eq $cnum) {
5596: $groups{$3} = $env{$key} ;
5597: }
5598: }
5599: }
5600: return %groups;
5601: }
5602:
1.683 raeburn 5603: sub get_group_membership {
5604: my ($cdom,$cnum,$group) = @_;
5605: return(&dump('groupmembership',$cdom,$cnum,$group));
5606: }
5607:
5608: sub get_users_groups {
5609: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5610: my @usersgroups;
1.683 raeburn 5611: my $cachetime=1800;
5612:
5613: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5614: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5615: if (defined($cached)) {
1.734 albertel 5616: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5617: } else {
5618: $grouplist = '';
1.816 raeburn 5619: my $courseurl = &courseid_to_courseurl($courseid);
5620: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5621: my $access_end = $env{'course.'.$courseid.
5622: '.default_enrollment_end_date'};
5623: my $now = time;
5624: foreach my $key (keys(%roleshash)) {
5625: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5626: my $group = $1;
5627: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5628: my $start = $2;
5629: my $end = $1;
5630: if ($start == -1) { next; } # deleted from group
5631: if (($start!=0) && ($start>$now)) { next; }
5632: if (($end!=0) && ($end<$now)) {
5633: if ($access_end && $access_end < $now) {
5634: if ($access_end - $end < 86400) {
5635: push(@usersgroups,$group);
1.733 raeburn 5636: }
5637: }
1.817 raeburn 5638: next;
1.733 raeburn 5639: }
1.817 raeburn 5640: push(@usersgroups,$group);
1.683 raeburn 5641: }
5642: }
5643: }
1.817 raeburn 5644: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5645: $grouplist = join(':',@usersgroups);
5646: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5647: }
1.733 raeburn 5648: return @usersgroups;
1.683 raeburn 5649: }
5650:
5651: sub devalidate_getgroups_cache {
5652: my ($udom,$uname,$cdom,$cnum)=@_;
5653: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5654:
1.683 raeburn 5655: my $hashid="$udom:$uname:$courseid";
5656: &devalidate_cache_new('getgroups',$hashid);
5657: }
5658:
1.12 www 5659: # ------------------------------------------------------------------ Plain Text
5660:
5661: sub plaintext {
1.742 raeburn 5662: my ($short,$type,$cid) = @_;
1.758 albertel 5663: if ($short =~ /^cr/) {
5664: return (split('/',$short))[-1];
5665: }
1.742 raeburn 5666: if (!defined($cid)) {
5667: $cid = $env{'request.course.id'};
5668: }
5669: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5670: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5671: '.plaintext'});
5672: }
5673: my %rolenames = (
5674: Course => 'std',
5675: Group => 'alt1',
5676: );
5677: if (defined($type) &&
5678: defined($rolenames{$type}) &&
5679: defined($prp{$short}{$rolenames{$type}})) {
5680: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5681: } else {
5682: return &Apache::lonlocal::mt($prp{$short}{'std'});
5683: }
1.12 www 5684: }
5685:
5686: # ----------------------------------------------------------------- Assign Role
5687:
5688: sub assignrole {
1.957 raeburn 5689: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5690: $context)=@_;
1.21 www 5691: my $mrole;
5692: if ($role =~ /^cr\//) {
1.393 www 5693: my $cwosec=$url;
1.811 albertel 5694: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5695: unless (&allowed('ccr',$cwosec)) {
1.104 www 5696: &logthis('Refused custom assignrole: '.
5697: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5698: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5699: return 'refused';
5700: }
1.21 www 5701: $mrole='cr';
1.678 raeburn 5702: } elsif ($role =~ /^gr\//) {
5703: my $cwogrp=$url;
1.811 albertel 5704: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5705: unless (&allowed('mdg',$cwogrp)) {
5706: &logthis('Refused group assignrole: '.
5707: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5708: $env{'user.name'}.' at '.$env{'user.domain'});
5709: return 'refused';
5710: }
5711: $mrole='gr';
1.21 www 5712: } else {
1.82 www 5713: my $cwosec=$url;
1.811 albertel 5714: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5715: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5716: my $refused;
5717: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5718: if (!(&allowed('c'.$role,$url))) {
5719: $refused = 1;
5720: }
5721: } else {
5722: $refused = 1;
5723: }
1.947 raeburn 5724: if ($refused) {
5725: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5726: $refused = '';
5727: } else {
5728: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5729: ' '.$role.' '.$end.' '.$start.' by '.
5730: $env{'user.name'}.' at '.$env{'user.domain'});
5731: return 'refused';
5732: }
1.932 raeburn 5733: }
1.104 www 5734: }
1.21 www 5735: $mrole=$role;
5736: }
1.620 albertel 5737: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5738: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5739: if ($end) { $command.='_'.$end; }
1.21 www 5740: if ($start) {
5741: if ($end) {
1.81 www 5742: $command.='_'.$start;
1.21 www 5743: } else {
1.81 www 5744: $command.='_0_'.$start;
1.21 www 5745: }
5746: }
1.739 raeburn 5747: my $origstart = $start;
5748: my $origend = $end;
1.957 raeburn 5749: my $delflag;
1.357 www 5750: # actually delete
5751: if ($deleteflag) {
1.373 www 5752: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5753: # modify command to delete the role
1.620 albertel 5754: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5755: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5756: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5757: # set start and finish to negative values for userrolelog
5758: $start=-1;
5759: $end=-1;
1.957 raeburn 5760: $delflag = 1;
1.357 www 5761: }
5762: }
5763: # send command
1.349 www 5764: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5765: # log new user role if status is ok
1.349 www 5766: if ($answer eq 'ok') {
1.663 raeburn 5767: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5768: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5769: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5770: unless ($role =~ /^gr/) {
5771: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5772: $origstart,$selfenroll,$context);
1.739 raeburn 5773: }
1.349 www 5774: }
5775: return $answer;
1.169 harris41 5776: }
5777:
5778: # -------------------------------------------------- Modify user authentication
1.197 www 5779: # Overrides without validation
5780:
1.169 harris41 5781: sub modifyuserauth {
5782: my ($udom,$uname,$umode,$upass)=@_;
5783: my $uhome=&homeserver($uname,$udom);
1.197 www 5784: unless (&allowed('mau',$udom)) { return 'refused'; }
5785: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5786: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5787: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5788: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5789: &escape($upass),$uhome);
1.620 albertel 5790: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5791: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5792: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5793: &log($udom,,$uname,$uhome,
1.620 albertel 5794: 'Authentication changed by '.$env{'user.domain'}.', '.
5795: $env{'user.name'}.', '.$umode.
1.197 www 5796: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5797: unless ($reply eq 'ok') {
1.197 www 5798: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5799: return 'error: '.$reply;
5800: }
1.170 harris41 5801: return 'ok';
1.80 www 5802: }
5803:
1.81 www 5804: # --------------------------------------------------------------- Modify a user
1.80 www 5805:
1.81 www 5806: sub modifyuser {
1.206 matthew 5807: my ($udom, $uname, $uid,
5808: $umode, $upass, $first,
5809: $middle, $last, $gene,
1.963 raeburn 5810: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 5811: $udom= &LONCAPA::clean_domain($udom);
5812: $uname=&LONCAPA::clean_username($uname);
1.81 www 5813: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5814: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5815: $last.', '.$gene.'(forceid: '.$forceid.')'.
5816: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5817: ' desiredhome not specified').
1.620 albertel 5818: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5819: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5820: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5821: # ----------------------------------------------------------------- Create User
1.406 albertel 5822: if (($uhome eq 'no_host') &&
5823: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5824: my $unhome='';
1.844 albertel 5825: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5826: $unhome = $desiredhome;
1.620 albertel 5827: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5828: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5829: } else { # load balancing routine for determining $unhome
1.81 www 5830: my $loadm=10000000;
1.841 albertel 5831: my %servers = &get_servers($udom,'library');
5832: foreach my $tryserver (keys(%servers)) {
5833: my $answer=reply('load',$tryserver);
5834: if (($answer=~/\d+/) && ($answer<$loadm)) {
5835: $loadm=$answer;
5836: $unhome=$tryserver;
5837: }
1.80 www 5838: }
5839: }
5840: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5841: return 'error: unable to find a home server for '.$uname.
5842: ' in domain '.$udom;
1.80 www 5843: }
5844: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5845: &escape($upass),$unhome);
5846: unless ($reply eq 'ok') {
5847: return 'error: '.$reply;
5848: }
1.230 stredwic 5849: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5850: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5851: return 'error: unable verify users home machine.';
1.80 www 5852: }
1.209 matthew 5853: } # End of creation of new user
1.80 www 5854: # ---------------------------------------------------------------------- Add ID
5855: if ($uid) {
5856: $uid=~tr/A-Z/a-z/;
5857: my %uidhash=&idrget($udom,$uname);
1.196 www 5858: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5859: && (!$forceid)) {
1.80 www 5860: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5861: return 'error: user id "'.$uid.'" does not match '.
5862: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5863: }
5864: } else {
5865: &idput($udom,($uname => $uid));
5866: }
5867: }
5868: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5869: my @tmp=&get('environment',
1.899 raeburn 5870: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 5871: 'permanentemail','inststatus'],
1.134 albertel 5872: $udom,$uname);
1.313 matthew 5873: my %names;
5874: if ($tmp[0] =~ m/^error:.*/) {
5875: %names=();
5876: } else {
5877: %names = @tmp;
5878: }
1.388 www 5879: #
5880: # Make sure to not trash student environment if instructor does not bother
5881: # to supply name and email information
5882: #
5883: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5884: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5885: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5886: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5887: if ($email) {
5888: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 5889: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 5890: }
1.899 raeburn 5891: if ($uid) { $names{'id'} = $uid; }
1.963 raeburn 5892: if (defined($inststatus)) { $names{'inststatus'} = $inststatus; }
1.134 albertel 5893: my $reply = &put('environment', \%names, $udom,$uname);
5894: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5895: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5896: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 5897: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5898: $umode.', '.$first.', '.$middle.', '.
5899: $last.', '.$gene.', '.$email.', '.$inststatus;
5900: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
5901: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
5902: } else {
5903: $logmsg .= ' during self creation';
5904: }
5905: &logthis($logmsg);
1.134 albertel 5906: return 'ok';
1.80 www 5907: }
5908:
1.81 www 5909: # -------------------------------------------------------------- Modify student
1.80 www 5910:
1.81 www 5911: sub modifystudent {
5912: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 5913: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5914: $selfenroll,$context)=@_;
1.455 albertel 5915: if (!$cid) {
1.620 albertel 5916: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5917: return 'not_in_class';
5918: }
1.80 www 5919: }
5920: # --------------------------------------------------------------- Make the user
1.81 www 5921: my $reply=&modifyuser
1.209 matthew 5922: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5923: $desiredhome,$email);
1.80 www 5924: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5925: # This will cause &modify_student_enrollment to get the uid from the
5926: # students environment
5927: $uid = undef if (!$forceid);
1.455 albertel 5928: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 5929: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 5930: return $reply;
5931: }
5932:
5933: sub modify_student_enrollment {
1.957 raeburn 5934: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 5935: my ($cdom,$cnum,$chome);
5936: if (!$cid) {
1.620 albertel 5937: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5938: return 'not_in_class';
5939: }
1.620 albertel 5940: $cdom=$env{'course.'.$cid.'.domain'};
5941: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5942: } else {
5943: ($cdom,$cnum)=split(/_/,$cid);
5944: }
1.620 albertel 5945: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5946: if (!$chome) {
1.457 raeburn 5947: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5948: }
1.455 albertel 5949: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5950: # Make sure the user exists
1.81 www 5951: my $uhome=&homeserver($uname,$udom);
5952: if (($uhome eq '') || ($uhome eq 'no_host')) {
5953: return 'error: no such user';
5954: }
1.297 matthew 5955: # Get student data if we were not given enough information
5956: if (!defined($first) || $first eq '' ||
5957: !defined($last) || $last eq '' ||
5958: !defined($uid) || $uid eq '' ||
5959: !defined($middle) || $middle eq '' ||
5960: !defined($gene) || $gene eq '') {
1.294 matthew 5961: # They did not supply us with enough data to enroll the student, so
5962: # we need to pick up more information.
1.297 matthew 5963: my %tmp = &get('environment',
1.294 matthew 5964: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5965: ,$udom,$uname);
5966:
1.800 albertel 5967: #foreach my $key (keys(%tmp)) {
5968: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5969: #}
1.294 matthew 5970: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5971: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5972: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5973: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5974: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5975: }
1.556 albertel 5976: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5977: my $reply=cput('classlist',
5978: {"$uname:$udom" =>
1.515 raeburn 5979: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5980: $cdom,$cnum);
1.81 www 5981: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5982: return 'error: '.$reply;
1.652 albertel 5983: } else {
5984: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5985: }
1.297 matthew 5986: # Add student role to user
1.83 www 5987: my $uurl='/'.$cid;
1.81 www 5988: $uurl=~s/\_/\//g;
5989: if ($usec) {
5990: $uurl.='/'.$usec;
5991: }
1.957 raeburn 5992: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 5993: }
5994:
1.556 albertel 5995: sub format_name {
5996: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5997: my $name;
5998: if ($first ne 'lastname') {
5999: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6000: } else {
6001: if ($lastname=~/\S/) {
6002: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6003: $name=~s/\s+,/,/;
6004: } else {
6005: $name.= $firstname.' '.$middlename.' '.$generation;
6006: }
6007: }
6008: $name=~s/^\s+//;
6009: $name=~s/\s+$//;
6010: $name=~s/\s+/ /g;
6011: return $name;
6012: }
6013:
1.84 www 6014: # ------------------------------------------------- Write to course preferences
6015:
6016: sub writecoursepref {
6017: my ($courseid,%prefs)=@_;
6018: $courseid=~s/^\///;
6019: $courseid=~s/\_/\//g;
6020: my ($cdomain,$cnum)=split(/\//,$courseid);
6021: my $chome=homeserver($cnum,$cdomain);
6022: if (($chome eq '') || ($chome eq 'no_host')) {
6023: return 'error: no such course';
6024: }
6025: my $cstring='';
1.800 albertel 6026: foreach my $pref (keys(%prefs)) {
6027: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6028: }
1.84 www 6029: $cstring=~s/\&$//;
6030: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6031: }
6032:
6033: # ---------------------------------------------------------- Make/modify course
6034:
6035: sub createcourse {
1.741 raeburn 6036: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6037: $course_owner,$crstype)=@_;
1.84 www 6038: $url=&declutter($url);
6039: my $cid='';
1.264 matthew 6040: unless (&allowed('ccc',$udom)) {
1.84 www 6041: return 'refused';
6042: }
6043: # ------------------------------------------------------------------- Create ID
1.674 www 6044: my $uname=int(1+rand(9)).
6045: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6046: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 6047: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6048: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 6049: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6050: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6051: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
6052: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 6053: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6054: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6055: return 'error: unable to generate unique course-ID';
6056: }
6057: }
1.264 matthew 6058: # ------------------------------------------------ Check supplied server name
1.620 albertel 6059: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6060: if (! &is_library($course_server)) {
1.264 matthew 6061: return 'error:bad server name '.$course_server;
6062: }
1.84 www 6063: # ------------------------------------------------------------- Make the course
6064: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6065: $course_server);
1.84 www 6066: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 6067: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6068: if (($uhome eq '') || ($uhome eq 'no_host')) {
6069: return 'error: no such course';
6070: }
1.271 www 6071: # ----------------------------------------------------------------- Course made
1.516 raeburn 6072: # log existence
1.918 raeburn 6073: my $newcourse = {
6074: $udom.'_'.$uname => {
1.921 raeburn 6075: description => $description,
6076: inst_code => $inst_code,
6077: owner => $course_owner,
6078: type => $crstype,
1.918 raeburn 6079: },
6080: };
1.921 raeburn 6081: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6082: # set toplevel url
1.271 www 6083: my $topurl=$url;
6084: unless ($nonstandard) {
6085: # ------------------------------------------ For standard courses, make top url
6086: my $mapurl=&clutter($url);
1.278 www 6087: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6088: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6089: <map>
6090: <resource id="1" type="start"></resource>
6091: <resource id="2" src="$mapurl"></resource>
6092: <resource id="3" type="finish"></resource>
6093: <link index="1" from="1" to="2"></link>
6094: <link index="2" from="2" to="3"></link>
6095: </map>
6096: ENDINITMAP
6097: $topurl=&declutter(
1.638 albertel 6098: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6099: );
6100: }
6101: # ----------------------------------------------------------- Write preferences
1.84 www 6102: &writecoursepref($udom.'_'.$uname,
6103: ('description' => $description,
1.271 www 6104: 'url' => $topurl));
1.84 www 6105: return '/'.$udom.'/'.$uname;
6106: }
6107:
1.813 albertel 6108: sub is_course {
6109: my ($cdom,$cnum) = @_;
6110: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6111: undef,'.');
1.813 albertel 6112: if (exists($courses{$cdom.'_'.$cnum})) {
6113: return 1;
6114: }
6115: return 0;
6116: }
6117:
1.21 www 6118: # ---------------------------------------------------------- Assign Custom Role
6119:
6120: sub assigncustomrole {
1.957 raeburn 6121: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6122: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6123: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6124: }
6125:
6126: # ----------------------------------------------------------------- Revoke Role
6127:
6128: sub revokerole {
1.957 raeburn 6129: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6130: my $now=time;
1.965 raeburn 6131: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6132: }
6133:
6134: # ---------------------------------------------------------- Revoke Custom Role
6135:
6136: sub revokecustomrole {
1.957 raeburn 6137: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6138: my $now=time;
1.357 www 6139: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6140: $deleteflag,$selfenroll,$context);
1.17 www 6141: }
6142:
1.533 banghart 6143: # ------------------------------------------------------------ Disk usage
1.535 albertel 6144: sub diskusage {
1.955 raeburn 6145: my ($udom,$uname,$directorypath,$getpropath)=@_;
6146: $directorypath =~ s/\/$//;
6147: my $listing=&reply('du2:'.&escape($directorypath).':'
6148: .&escape($getpropath).':'.&escape($uname).':'
6149: .&escape($udom),homeserver($uname,$udom));
6150: if ($listing eq 'unknown_cmd') {
6151: if ($getpropath) {
6152: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6153: }
6154: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6155: }
1.514 albertel 6156: return $listing;
1.512 banghart 6157: }
6158:
1.566 banghart 6159: sub is_locked {
6160: my ($file_name, $domain, $user) = @_;
6161: my @check;
6162: my $is_locked;
6163: push @check, $file_name;
1.613 albertel 6164: my %locked = &get('file_permissions',\@check,
1.620 albertel 6165: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6166: my ($tmp)=keys(%locked);
6167: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6168:
1.566 banghart 6169: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6170: $is_locked = 'false';
6171: foreach my $entry (@{$locked{$file_name}}) {
6172: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6173: $is_locked = 'true';
6174: last;
1.745 raeburn 6175: }
6176: }
1.566 banghart 6177: } else {
6178: $is_locked = 'false';
6179: }
6180: }
6181:
1.759 albertel 6182: sub declutter_portfile {
6183: my ($file) = @_;
1.833 albertel 6184: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6185: return $file;
6186: }
6187:
1.559 banghart 6188: # ------------------------------------------------------------- Mark as Read Only
6189:
6190: sub mark_as_readonly {
6191: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6192: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6193: my ($tmp)=keys(%current_permissions);
6194: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6195: foreach my $file (@{$files}) {
1.759 albertel 6196: $file = &declutter_portfile($file);
1.561 banghart 6197: push(@{$current_permissions{$file}},$what);
1.559 banghart 6198: }
1.613 albertel 6199: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6200: return;
6201: }
6202:
1.572 banghart 6203: # ------------------------------------------------------------Save Selected Files
6204:
6205: sub save_selected_files {
6206: my ($user, $path, @files) = @_;
6207: my $filename = $user."savedfiles";
1.573 banghart 6208: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6209: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6210: foreach my $file (@files) {
1.620 albertel 6211: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6212: }
6213: foreach my $file (@other_files) {
1.574 banghart 6214: print (OUT $file."\n");
1.572 banghart 6215: }
1.574 banghart 6216: close (OUT);
1.572 banghart 6217: return 'ok';
6218: }
6219:
1.574 banghart 6220: sub clear_selected_files {
6221: my ($user) = @_;
6222: my $filename = $user."savedfiles";
6223: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6224: print (OUT undef);
6225: close (OUT);
6226: return ("ok");
6227: }
6228:
1.572 banghart 6229: sub files_in_path {
6230: my ($user, $path) = @_;
6231: my $filename = $user."savedfiles";
6232: my %return_files;
1.574 banghart 6233: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6234: while (my $line_in = <IN>) {
1.574 banghart 6235: chomp ($line_in);
6236: my @paths_and_file = split (m!/!, $line_in);
6237: my $file_part = pop (@paths_and_file);
6238: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6239: $path_part.='/';
6240: my $path_and_file = $path_part.$file_part;
6241: if ($path_part eq $path) {
6242: $return_files{$file_part}= 'selected';
6243: }
6244: }
1.574 banghart 6245: close (IN);
6246: return (\%return_files);
1.572 banghart 6247: }
6248:
6249: # called in portfolio select mode, to show files selected NOT in current directory
6250: sub files_not_in_path {
6251: my ($user, $path) = @_;
6252: my $filename = $user."savedfiles";
6253: my @return_files;
6254: my $path_part;
1.800 albertel 6255: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6256: while (my $line = <IN>) {
1.572 banghart 6257: #ok, I know it's clunky, but I want it to work
1.800 albertel 6258: my @paths_and_file = split(m|/|, $line);
6259: my $file_part = pop(@paths_and_file);
6260: chomp($file_part);
6261: my $path_part = join('/', @paths_and_file);
1.572 banghart 6262: $path_part .= '/';
6263: my $path_and_file = $path_part.$file_part;
6264: if ($path_part ne $path) {
1.800 albertel 6265: push(@return_files, ($path_and_file));
1.572 banghart 6266: }
6267: }
1.800 albertel 6268: close(OUT);
1.574 banghart 6269: return (@return_files);
1.572 banghart 6270: }
6271:
1.745 raeburn 6272: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6273:
1.745 raeburn 6274: sub get_portfile_permissions {
6275: my ($domain,$user) = @_;
1.613 albertel 6276: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6277: my ($tmp)=keys(%current_permissions);
6278: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6279: return \%current_permissions;
6280: }
6281:
6282: #---------------------------------------------Get portfolio file access controls
6283:
1.749 raeburn 6284: sub get_access_controls {
1.745 raeburn 6285: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6286: my %access;
6287: my $real_file = $file;
6288: $file =~ s/\.meta$//;
1.745 raeburn 6289: if (defined($file)) {
1.749 raeburn 6290: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6291: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6292: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6293: }
6294: }
1.745 raeburn 6295: } else {
1.749 raeburn 6296: foreach my $key (keys(%{$current_permissions})) {
6297: if ($key =~ /\0accesscontrol$/) {
6298: if (defined($group)) {
6299: if ($key !~ m-^\Q$group\E/-) {
6300: next;
6301: }
6302: }
6303: my ($fullpath) = split(/\0/,$key);
6304: if (ref($$current_permissions{$key}) eq 'HASH') {
6305: foreach my $control (keys(%{$$current_permissions{$key}})) {
6306: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6307: }
6308: }
6309: }
6310: }
6311: }
6312: return %access;
6313: }
6314:
6315: sub modify_access_controls {
6316: my ($file_name,$changes,$domain,$user)=@_;
6317: my ($outcome,$deloutcome);
6318: my %store_permissions;
6319: my %new_values;
6320: my %new_control;
6321: my %translation;
6322: my @deletions = ();
6323: my $now = time;
6324: if (exists($$changes{'activate'})) {
6325: if (ref($$changes{'activate'}) eq 'HASH') {
6326: my @newitems = sort(keys(%{$$changes{'activate'}}));
6327: my $numnew = scalar(@newitems);
6328: for (my $i=0; $i<$numnew; $i++) {
6329: my $newkey = $newitems[$i];
6330: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6331: if ($newkey =~ /^\d+:/) {
6332: $newkey =~ s/^(\d+)/$newid/;
6333: $translation{$1} = $newid;
6334: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6335: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6336: $translation{$1} = $newid;
6337: }
1.749 raeburn 6338: $new_values{$file_name."\0".$newkey} =
6339: $$changes{'activate'}{$newitems[$i]};
6340: $new_control{$newkey} = $now;
6341: }
6342: }
6343: }
6344: my %todelete;
6345: my %changed_items;
6346: foreach my $action ('delete','update') {
6347: if (exists($$changes{$action})) {
6348: if (ref($$changes{$action}) eq 'HASH') {
6349: foreach my $key (keys(%{$$changes{$action}})) {
6350: my ($itemnum) = ($key =~ /^([^:]+):/);
6351: if ($action eq 'delete') {
6352: $todelete{$itemnum} = 1;
6353: } else {
6354: $changed_items{$itemnum} = $key;
6355: }
6356: }
1.745 raeburn 6357: }
6358: }
1.749 raeburn 6359: }
6360: # get lock on access controls for file.
6361: my $lockhash = {
6362: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6363: ':'.$env{'user.domain'},
6364: };
6365: my $tries = 0;
6366: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6367:
6368: while (($gotlock ne 'ok') && $tries <3) {
6369: $tries ++;
6370: sleep 1;
6371: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6372: }
6373: if ($gotlock eq 'ok') {
6374: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6375: my ($tmp)=keys(%curr_permissions);
6376: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6377: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6378: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6379: if (ref($curr_controls) eq 'HASH') {
6380: foreach my $control_item (keys(%{$curr_controls})) {
6381: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6382: if (defined($todelete{$itemnum})) {
6383: push(@deletions,$file_name."\0".$control_item);
6384: } else {
6385: if (defined($changed_items{$itemnum})) {
6386: $new_control{$changed_items{$itemnum}} = $now;
6387: push(@deletions,$file_name."\0".$control_item);
6388: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6389: } else {
6390: $new_control{$control_item} = $$curr_controls{$control_item};
6391: }
6392: }
1.745 raeburn 6393: }
6394: }
6395: }
1.970 raeburn 6396: my ($group);
6397: if (&is_course($domain,$user)) {
6398: ($group,my $file) = split(/\//,$file_name,2);
6399: }
1.749 raeburn 6400: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6401: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6402: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6403: # remove lock
6404: my @del_lock = ($file_name."\0".'locked_access_records');
6405: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6406: my $sqlresult =
1.970 raeburn 6407: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6408: $group);
1.749 raeburn 6409: } else {
6410: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6411: }
1.749 raeburn 6412: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6413: }
6414:
1.827 raeburn 6415: sub make_public_indefinitely {
6416: my ($requrl) = @_;
6417: my $now = time;
6418: my $action = 'activate';
6419: my $aclnum = 0;
6420: if (&is_portfolio_url($requrl)) {
6421: my (undef,$udom,$unum,$file_name,$group) =
6422: &parse_portfolio_url($requrl);
6423: my $current_perms = &get_portfile_permissions($udom,$unum);
6424: my %access_controls = &get_access_controls($current_perms,
6425: $group,$file_name);
6426: foreach my $key (keys(%{$access_controls{$file_name}})) {
6427: my ($num,$scope,$end,$start) =
6428: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6429: if ($scope eq 'public') {
6430: if ($start <= $now && $end == 0) {
6431: $action = 'none';
6432: } else {
6433: $action = 'update';
6434: $aclnum = $num;
6435: }
6436: last;
6437: }
6438: }
6439: if ($action eq 'none') {
6440: return 'ok';
6441: } else {
6442: my %changes;
6443: my $newend = 0;
6444: my $newstart = $now;
6445: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6446: $changes{$action}{$newkey} = {
6447: type => 'public',
6448: time => {
6449: start => $newstart,
6450: end => $newend,
6451: },
6452: };
6453: my ($outcome,$deloutcome,$new_values,$translation) =
6454: &modify_access_controls($file_name,\%changes,$udom,$unum);
6455: return $outcome;
6456: }
6457: } else {
6458: return 'invalid';
6459: }
6460: }
6461:
1.745 raeburn 6462: #------------------------------------------------------Get Marked as Read Only
6463:
6464: sub get_marked_as_readonly {
6465: my ($domain,$user,$what,$group) = @_;
6466: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6467: my @readonly_files;
1.629 banghart 6468: my $cmp1=$what;
6469: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6470: while (my ($file_name,$value) = each(%{$current_permissions})) {
6471: if (defined($group)) {
6472: if ($file_name !~ m-^\Q$group\E/-) {
6473: next;
6474: }
6475: }
1.561 banghart 6476: if (ref($value) eq "ARRAY"){
6477: foreach my $stored_what (@{$value}) {
1.629 banghart 6478: my $cmp2=$stored_what;
1.759 albertel 6479: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6480: $cmp2=join('',@{$stored_what});
1.745 raeburn 6481: }
1.629 banghart 6482: if ($cmp1 eq $cmp2) {
1.561 banghart 6483: push(@readonly_files, $file_name);
1.745 raeburn 6484: last;
1.563 banghart 6485: } elsif (!defined($what)) {
6486: push(@readonly_files, $file_name);
1.745 raeburn 6487: last;
1.561 banghart 6488: }
6489: }
1.745 raeburn 6490: }
1.561 banghart 6491: }
6492: return @readonly_files;
6493: }
1.577 banghart 6494: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6495:
1.577 banghart 6496: sub get_marked_as_readonly_hash {
1.745 raeburn 6497: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6498: my %readonly_files;
1.745 raeburn 6499: while (my ($file_name,$value) = each(%{$current_permissions})) {
6500: if (defined($group)) {
6501: if ($file_name !~ m-^\Q$group\E/-) {
6502: next;
6503: }
6504: }
1.577 banghart 6505: if (ref($value) eq "ARRAY"){
6506: foreach my $stored_what (@{$value}) {
1.745 raeburn 6507: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6508: foreach my $lock_descriptor(@{$stored_what}) {
6509: if ($lock_descriptor eq 'graded') {
6510: $readonly_files{$file_name} = 'graded';
6511: } elsif ($lock_descriptor eq 'handback') {
6512: $readonly_files{$file_name} = 'handback';
6513: } else {
6514: if (!exists($readonly_files{$file_name})) {
6515: $readonly_files{$file_name} = 'locked';
6516: }
6517: }
1.745 raeburn 6518: }
1.750 banghart 6519: }
1.577 banghart 6520: }
6521: }
6522: }
6523: return %readonly_files;
6524: }
1.559 banghart 6525: # ------------------------------------------------------------ Unmark as Read Only
6526:
6527: sub unmark_as_readonly {
1.629 banghart 6528: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6529: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6530: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6531: $file_name = &declutter_portfile($file_name);
1.634 albertel 6532: my $symb_crs = $what;
6533: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6534: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6535: my ($tmp)=keys(%current_permissions);
6536: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6537: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6538: foreach my $file (@readonly_files) {
1.759 albertel 6539: my $clean_file = &declutter_portfile($file);
6540: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6541: my $current_locks = $current_permissions{$file};
1.563 banghart 6542: my @new_locks;
6543: my @del_keys;
6544: if (ref($current_locks) eq "ARRAY"){
6545: foreach my $locker (@{$current_locks}) {
1.632 albertel 6546: my $compare=$locker;
1.749 raeburn 6547: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6548: $compare=join('',@{$locker});
1.746 raeburn 6549: if ($compare ne $symb_crs) {
6550: push(@new_locks, $locker);
6551: }
1.563 banghart 6552: }
6553: }
1.650 albertel 6554: if (scalar(@new_locks) > 0) {
1.563 banghart 6555: $current_permissions{$file} = \@new_locks;
6556: } else {
6557: push(@del_keys, $file);
1.613 albertel 6558: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6559: delete($current_permissions{$file});
1.563 banghart 6560: }
6561: }
1.561 banghart 6562: }
1.613 albertel 6563: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6564: return;
6565: }
1.512 banghart 6566:
1.17 www 6567: # ------------------------------------------------------------ Directory lister
6568:
6569: sub dirlist {
1.955 raeburn 6570: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6571: $uri=~s/^\///;
6572: $uri=~s/\/$//;
1.253 stredwic 6573: my ($udom, $uname);
1.955 raeburn 6574: if ($getuserdir) {
1.253 stredwic 6575: $udom = $userdomain;
6576: $uname = $username;
1.955 raeburn 6577: } else {
6578: (undef,$udom,$uname)=split(/\//,$uri);
6579: if(defined($userdomain)) {
6580: $udom = $userdomain;
6581: }
6582: if(defined($username)) {
6583: $uname = $username;
6584: }
1.253 stredwic 6585: }
1.955 raeburn 6586: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6587:
1.955 raeburn 6588: $dirRoot = $perlvar{'lonDocRoot'};
6589: if (defined($getpropath)) {
6590: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6591: $dirRoot =~ s/\/$//;
1.955 raeburn 6592: } elsif (defined($getuserdir)) {
6593: my $subdir=$uname.'__';
6594: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6595: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6596: ."/$udom/$subdir/$uname";
6597: } elsif (defined($alternateRoot)) {
6598: $dirRoot = $alternateRoot;
1.751 banghart 6599: }
1.253 stredwic 6600:
6601: if($udom) {
6602: if($uname) {
1.955 raeburn 6603: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6604: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6605: .':'.&escape($uname).':'.&escape($udom),
6606: &homeserver($uname,$udom));
6607: if ($listing eq 'unknown_cmd') {
6608: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6609: &homeserver($uname,$udom));
6610: } else {
6611: @listing_results = map { &unescape($_); } split(/:/,$listing);
6612: }
1.605 matthew 6613: if ($listing eq 'unknown_cmd') {
1.800 albertel 6614: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6615: &homeserver($uname,$udom));
1.605 matthew 6616: @listing_results = split(/:/,$listing);
6617: } else {
6618: @listing_results = map { &unescape($_); } split(/:/,$listing);
6619: }
6620: return @listing_results;
1.955 raeburn 6621: } elsif(!$alternateRoot) {
1.800 albertel 6622: my %allusers;
1.841 albertel 6623: my %servers = &get_servers($udom,'library');
1.955 raeburn 6624: foreach my $tryserver (keys(%servers)) {
6625: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6626: &escape($udom),$tryserver);
6627: if ($listing eq 'unknown_cmd') {
6628: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6629: $udom, $tryserver);
6630: } else {
6631: @listing_results = map { &unescape($_); } split(/:/,$listing);
6632: }
1.841 albertel 6633: if ($listing eq 'unknown_cmd') {
6634: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6635: $udom, $tryserver);
6636: @listing_results = split(/:/,$listing);
6637: } else {
6638: @listing_results =
6639: map { &unescape($_); } split(/:/,$listing);
6640: }
6641: if ($listing_results[0] ne 'no_such_dir' &&
6642: $listing_results[0] ne 'empty' &&
6643: $listing_results[0] ne 'con_lost') {
6644: foreach my $line (@listing_results) {
6645: my ($entry) = split(/&/,$line,2);
6646: $allusers{$entry} = 1;
6647: }
6648: }
1.253 stredwic 6649: }
6650: my $alluserstr='';
1.800 albertel 6651: foreach my $user (sort(keys(%allusers))) {
6652: $alluserstr.=$user.'&user:';
1.253 stredwic 6653: }
6654: $alluserstr=~s/:$//;
6655: return split(/:/,$alluserstr);
6656: } else {
1.800 albertel 6657: return ('missing user name');
1.253 stredwic 6658: }
1.955 raeburn 6659: } elsif(!defined($getpropath)) {
1.841 albertel 6660: my @all_domains = sort(&all_domains());
1.955 raeburn 6661: foreach my $domain (@all_domains) {
6662: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6663: }
6664: return @all_domains;
6665: } else {
1.800 albertel 6666: return ('missing domain');
1.275 stredwic 6667: }
6668: }
6669:
6670: # --------------------------------------------- GetFileTimestamp
6671: # This function utilizes dirlist and returns the date stamp for
6672: # when it was last modified. It will also return an error of -1
6673: # if an error occurs
6674:
6675: sub GetFileTimestamp {
1.955 raeburn 6676: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6677: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6678: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6679: my ($fileStat) =
6680: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6681: undef,$getuserdir);
1.275 stredwic 6682: my @stats = split('&', $fileStat);
6683: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6684: # @stats contains first the filename, then the stat output
6685: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6686: } else {
6687: return -1;
1.253 stredwic 6688: }
1.26 www 6689: }
6690:
1.712 albertel 6691: sub stat_file {
6692: my ($uri) = @_;
1.787 albertel 6693: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6694:
1.955 raeburn 6695: my ($udom,$uname,$file);
1.712 albertel 6696: if ($uri =~ m-^/(uploaded|editupload)/-) {
6697: ($udom,$uname,$file) =
1.811 albertel 6698: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6699: $file = 'userfiles/'.$file;
6700: }
6701: if ($uri =~ m-^/res/-) {
6702: ($udom,$uname) =
1.807 albertel 6703: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6704: $file = $uri;
6705: }
6706:
6707: if (!$udom || !$uname || !$file) {
6708: # unable to handle the uri
6709: return ();
6710: }
1.956 raeburn 6711: my $getpropath;
6712: if ($file =~ /^userfiles\//) {
6713: $getpropath = 1;
6714: }
1.955 raeburn 6715: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6716: my @stats = split('&', $result);
1.721 banghart 6717:
1.712 albertel 6718: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6719: shift(@stats); #filename is first
6720: return @stats;
6721: }
6722: return ();
6723: }
6724:
1.26 www 6725: # -------------------------------------------------------- Value of a Condition
6726:
1.713 albertel 6727: # gets the value of a specific preevaluated condition
6728: # stored in the string $env{user.state.<cid>}
6729: # or looks up a condition reference in the bighash and if if hasn't
6730: # already been evaluated recurses into docondval to get the value of
6731: # the condition, then memoizing it to
6732: # $env{user.state.<cid>.<condition>}
1.40 www 6733: sub directcondval {
6734: my $number=shift;
1.620 albertel 6735: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6736: &Apache::lonuserstate::evalstate();
6737: }
1.713 albertel 6738: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6739: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6740: } elsif ($number =~ /^_/) {
6741: my $sub_condition;
6742: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6743: &GDBM_READER(),0640)) {
6744: $sub_condition=$bighash{'conditions'.$number};
6745: untie(%bighash);
6746: }
6747: my $value = &docondval($sub_condition);
1.949 raeburn 6748: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6749: return $value;
6750: }
1.620 albertel 6751: if ($env{'user.state.'.$env{'request.course.id'}}) {
6752: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6753: } else {
6754: return 2;
6755: }
6756: }
6757:
1.713 albertel 6758: # get the collection of conditions for this resource
1.26 www 6759: sub condval {
6760: my $condidx=shift;
1.54 www 6761: my $allpathcond='';
1.713 albertel 6762: foreach my $cond (split(/\|/,$condidx)) {
6763: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6764: $allpathcond.=
6765: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6766: }
1.191 harris41 6767: }
1.54 www 6768: $allpathcond=~s/\|$//;
1.713 albertel 6769: return &docondval($allpathcond);
6770: }
6771:
6772: #evaluates an expression of conditions
6773: sub docondval {
6774: my ($allpathcond) = @_;
6775: my $result=0;
6776: if ($env{'request.course.id'}
6777: && defined($allpathcond)) {
6778: my $operand='|';
6779: my @stack;
6780: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6781: if ($chunk eq '(') {
6782: push @stack,($operand,$result);
6783: } elsif ($chunk eq ')') {
6784: my $before=pop @stack;
6785: if (pop @stack eq '&') {
6786: $result=$result>$before?$before:$result;
6787: } else {
6788: $result=$result>$before?$result:$before;
6789: }
6790: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6791: $operand=$chunk;
6792: } else {
6793: my $new=directcondval($chunk);
6794: if ($operand eq '&') {
6795: $result=$result>$new?$new:$result;
6796: } else {
6797: $result=$result>$new?$result:$new;
6798: }
6799: }
6800: }
1.26 www 6801: }
6802: return $result;
1.421 albertel 6803: }
6804:
6805: # ---------------------------------------------------- Devalidate courseresdata
6806:
6807: sub devalidatecourseresdata {
6808: my ($coursenum,$coursedomain)=@_;
6809: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6810: &devalidate_cache_new('courseres',$hashid);
1.28 www 6811: }
6812:
1.763 www 6813:
1.200 www 6814: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6815: #
6816: # Parameters:
6817: # $coursenum - Number of the course.
6818: # $coursedomain - Domain at which the course was created.
6819: # Returns:
6820: # A hash of the course parameters along (I think) with timestamps
6821: # and version info.
1.877 foxr 6822:
1.624 albertel 6823: sub get_courseresdata {
6824: my ($coursenum,$coursedomain)=@_;
1.200 www 6825: my $coursehom=&homeserver($coursenum,$coursedomain);
6826: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6827: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6828: my %dumpreply;
1.417 albertel 6829: unless (defined($cached)) {
1.624 albertel 6830: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6831: $result=\%dumpreply;
1.251 albertel 6832: my ($tmp) = keys(%dumpreply);
6833: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6834: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6835: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6836: return $tmp;
1.416 albertel 6837: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6838: $result=undef;
1.599 albertel 6839: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6840: }
6841: }
1.624 albertel 6842: return $result;
6843: }
6844:
1.633 albertel 6845: sub devalidateuserresdata {
6846: my ($uname,$udom)=@_;
6847: my $hashid="$udom:$uname";
6848: &devalidate_cache_new('userres',$hashid);
6849: }
6850:
1.624 albertel 6851: sub get_userresdata {
6852: my ($uname,$udom)=@_;
6853: #most student don\'t have any data set, check if there is some data
6854: if (&EXT_cache_status($udom,$uname)) { return undef; }
6855:
6856: my $hashid="$udom:$uname";
6857: my ($result,$cached)=&is_cached_new('userres',$hashid);
6858: if (!defined($cached)) {
6859: my %resourcedata=&dump('resourcedata',$udom,$uname);
6860: $result=\%resourcedata;
6861: &do_cache_new('userres',$hashid,$result,600);
6862: }
6863: my ($tmp)=keys(%$result);
6864: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6865: return $result;
6866: }
6867: #error 2 occurs when the .db doesn't exist
6868: if ($tmp!~/error: 2 /) {
1.672 albertel 6869: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6870: " Trying to get resource data for ".
6871: $uname." at ".$udom.": ".
6872: $tmp."</font>");
6873: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6874: #&EXT_cache_set($udom,$uname);
6875: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6876: undef($tmp); # not really an error so don't send it back
1.624 albertel 6877: }
6878: return $tmp;
6879: }
1.879 foxr 6880: #----------------------------------------------- resdata - return resource data
6881: # Purpose:
6882: # Return resource data for either users or for a course.
6883: # Parameters:
6884: # $name - Course/user name.
6885: # $domain - Name of the domain the user/course is registered on.
6886: # $type - Type of thing $name is (must be 'course' or 'user'
6887: # @which - Array of names of resources desired.
6888: # Returns:
6889: # The value of the first reasource in @which that is found in the
6890: # resource hash.
6891: # Exceptional Conditions:
6892: # If the $type passed in is not valid (not the string 'course' or
6893: # 'user', an undefined reference is returned.
6894: # If none of the resources are found, an undef is returned
1.624 albertel 6895: sub resdata {
6896: my ($name,$domain,$type,@which)=@_;
6897: my $result;
6898: if ($type eq 'course') {
6899: $result=&get_courseresdata($name,$domain);
6900: } elsif ($type eq 'user') {
6901: $result=&get_userresdata($name,$domain);
6902: }
6903: if (!ref($result)) { return $result; }
1.251 albertel 6904: foreach my $item (@which) {
1.927 albertel 6905: if (defined($result->{$item->[0]})) {
6906: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6907: }
1.250 albertel 6908: }
1.291 albertel 6909: return undef;
1.200 www 6910: }
6911:
1.379 matthew 6912: #
6913: # EXT resource caching routines
6914: #
6915:
6916: sub clear_EXT_cache_status {
1.383 albertel 6917: &delenv('cache.EXT.');
1.379 matthew 6918: }
6919:
6920: sub EXT_cache_status {
6921: my ($target_domain,$target_user) = @_;
1.383 albertel 6922: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6923: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6924: # We know already the user has no data
6925: return 1;
6926: } else {
6927: return 0;
6928: }
6929: }
6930:
6931: sub EXT_cache_set {
6932: my ($target_domain,$target_user) = @_;
1.383 albertel 6933: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 6934: #&appenv({$cachename => time});
1.379 matthew 6935: }
6936:
1.28 www 6937: # --------------------------------------------------------- Value of a Variable
1.58 www 6938: sub EXT {
1.715 albertel 6939:
1.395 albertel 6940: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6941: unless ($varname) { return ''; }
1.218 albertel 6942: #get real user name/domain, courseid and symb
6943: my $courseid;
1.359 albertel 6944: my $publicuser;
1.427 www 6945: if ($symbparm) {
6946: $symbparm=&get_symb_from_alias($symbparm);
6947: }
1.218 albertel 6948: if (!($uname && $udom)) {
1.790 albertel 6949: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6950: if (!$symbparm) { $symbparm=$cursymb; }
6951: } else {
1.620 albertel 6952: $courseid=$env{'request.course.id'};
1.218 albertel 6953: }
1.48 www 6954: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6955: my $rest;
1.320 albertel 6956: if (defined($therest[0])) {
1.48 www 6957: $rest=join('.',@therest);
6958: } else {
6959: $rest='';
6960: }
1.320 albertel 6961:
1.57 www 6962: my $qualifierrest=$qualifier;
6963: if ($rest) { $qualifierrest.='.'.$rest; }
6964: my $spacequalifierrest=$space;
6965: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6966: if ($realm eq 'user') {
1.48 www 6967: # --------------------------------------------------------------- user.resource
6968: if ($space eq 'resource') {
1.651 albertel 6969: if ( (defined($Apache::lonhomework::parsing_a_problem)
6970: || defined($Apache::lonhomework::parsing_a_task))
6971: &&
1.744 albertel 6972: ($symbparm eq &symbread()) ) {
6973: # if we are in the middle of processing the resource the
6974: # get the value we are planning on committing
6975: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6976: return $Apache::lonhomework::results{$qualifierrest};
6977: } else {
6978: return $Apache::lonhomework::history{$qualifierrest};
6979: }
1.335 albertel 6980: } else {
1.359 albertel 6981: my %restored;
1.620 albertel 6982: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6983: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6984: } else {
6985: %restored=&restore($symbparm,$courseid,$udom,$uname);
6986: }
1.335 albertel 6987: return $restored{$qualifierrest};
6988: }
1.48 www 6989: # ----------------------------------------------------------------- user.access
6990: } elsif ($space eq 'access') {
1.218 albertel 6991: # FIXME - not supporting calls for a specific user
1.48 www 6992: return &allowed($qualifier,$rest);
6993: # ------------------------------------------ user.preferences, user.environment
6994: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6995: if (($uname eq $env{'user.name'}) &&
6996: ($udom eq $env{'user.domain'})) {
6997: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6998: } else {
1.359 albertel 6999: my %returnhash;
7000: if (!$publicuser) {
7001: %returnhash=&userenvironment($udom,$uname,
7002: $qualifierrest);
7003: }
1.218 albertel 7004: return $returnhash{$qualifierrest};
7005: }
1.48 www 7006: # ----------------------------------------------------------------- user.course
7007: } elsif ($space eq 'course') {
1.218 albertel 7008: # FIXME - not supporting calls for a specific user
1.620 albertel 7009: return $env{join('.',('request.course',$qualifier))};
1.48 www 7010: # ------------------------------------------------------------------- user.role
7011: } elsif ($space eq 'role') {
1.218 albertel 7012: # FIXME - not supporting calls for a specific user
1.620 albertel 7013: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7014: if ($qualifier eq 'value') {
7015: return $role;
7016: } elsif ($qualifier eq 'extent') {
7017: return $where;
7018: }
7019: # ----------------------------------------------------------------- user.domain
7020: } elsif ($space eq 'domain') {
1.218 albertel 7021: return $udom;
1.48 www 7022: # ------------------------------------------------------------------- user.name
7023: } elsif ($space eq 'name') {
1.218 albertel 7024: return $uname;
1.48 www 7025: # ---------------------------------------------------- Any other user namespace
1.29 www 7026: } else {
1.359 albertel 7027: my %reply;
7028: if (!$publicuser) {
7029: %reply=&get($space,[$qualifierrest],$udom,$uname);
7030: }
7031: return $reply{$qualifierrest};
1.48 www 7032: }
1.236 www 7033: } elsif ($realm eq 'query') {
7034: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7035: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7036: [$spacequalifierrest]);
1.620 albertel 7037: return $env{'form.'.$spacequalifierrest};
1.236 www 7038: } elsif ($realm eq 'request') {
1.48 www 7039: # ------------------------------------------------------------- request.browser
7040: if ($space eq 'browser') {
1.430 www 7041: if ($qualifier eq 'textremote') {
1.676 albertel 7042: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7043: return 1;
7044: } else {
7045: return 0;
7046: }
7047: } else {
1.620 albertel 7048: return $env{'browser.'.$qualifier};
1.430 www 7049: }
1.57 www 7050: # ------------------------------------------------------------ request.filename
7051: } else {
1.620 albertel 7052: return $env{'request.'.$spacequalifierrest};
1.29 www 7053: }
1.28 www 7054: } elsif ($realm eq 'course') {
1.48 www 7055: # ---------------------------------------------------------- course.description
1.620 albertel 7056: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7057: } elsif ($realm eq 'resource') {
1.165 www 7058:
1.620 albertel 7059: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7060: if (!$symbparm) { $symbparm=&symbread(); }
7061: }
1.693 albertel 7062:
7063: if ($space eq 'title') {
7064: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7065: return &gettitle($symbparm);
7066: }
7067:
7068: if ($space eq 'map') {
7069: my ($map) = &decode_symb($symbparm);
7070: return &symbread($map);
7071: }
1.905 albertel 7072: if ($space eq 'filename') {
7073: if ($symbparm) {
7074: return &clutter((&decode_symb($symbparm))[2]);
7075: }
7076: return &hreflocation('',$env{'request.filename'});
7077: }
1.693 albertel 7078:
7079: my ($section, $group, @groups);
1.593 albertel 7080: my ($courselevelm,$courselevel);
1.539 albertel 7081: if ($symbparm && defined($courseid) &&
1.620 albertel 7082: $courseid eq $env{'request.course.id'}) {
1.165 www 7083:
1.218 albertel 7084: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7085:
1.60 www 7086: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7087: my $symbp=$symbparm;
1.735 albertel 7088: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7089:
7090: my $symbparm=$symbp.'.'.$spacequalifierrest;
7091: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7092:
1.620 albertel 7093: if (($env{'user.name'} eq $uname) &&
7094: ($env{'user.domain'} eq $udom)) {
7095: $section=$env{'request.course.sec'};
1.733 raeburn 7096: @groups = split(/:/,$env{'request.course.groups'});
7097: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7098: } else {
1.539 albertel 7099: if (! defined($usection)) {
1.551 albertel 7100: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7101: } else {
7102: $section = $usection;
7103: }
1.733 raeburn 7104: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7105: }
7106:
7107: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7108: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7109: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7110:
1.593 albertel 7111: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7112: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7113: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7114:
1.60 www 7115: # ----------------------------------------------------------- first, check user
1.624 albertel 7116:
7117: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7118: ([$courselevelr,'resource'],
7119: [$courselevelm,'map' ],
7120: [$courselevel, 'course' ]));
1.931 albertel 7121: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7122:
1.594 albertel 7123: # ------------------------------------------------ second, check some of course
1.684 raeburn 7124: my $coursereply;
1.691 raeburn 7125: if (@groups > 0) {
7126: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7127: $mapparm,$spacequalifierrest);
1.927 albertel 7128: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7129: }
1.96 www 7130:
1.684 raeburn 7131: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7132: $env{'course.'.$courseid.'.domain'},
7133: 'course',
7134: ([$seclevelr, 'resource'],
7135: [$seclevelm, 'map' ],
7136: [$seclevel, 'course' ],
7137: [$courselevelr,'resource']));
7138: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7139:
1.60 www 7140: # ------------------------------------------------------ third, check map parms
1.218 albertel 7141: my %parmhash=();
7142: my $thisparm='';
7143: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7144: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7145: &GDBM_READER(),0640)) {
1.218 albertel 7146: $thisparm=$parmhash{$symbparm};
7147: untie(%parmhash);
7148: }
1.927 albertel 7149: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7150: }
1.594 albertel 7151: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7152:
1.218 albertel 7153: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7154: my $filename;
7155: if (!$symbparm) { $symbparm=&symbread(); }
7156: if ($symbparm) {
1.409 www 7157: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7158: } else {
1.620 albertel 7159: $filename=$env{'request.filename'};
1.282 albertel 7160: }
7161: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7162: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7163: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7164: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7165:
1.927 albertel 7166: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7167: if ($symbparm && defined($courseid) &&
1.620 albertel 7168: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7169: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7170: $env{'course.'.$courseid.'.domain'},
7171: 'course',
1.927 albertel 7172: ([$courselevelm,'map' ],
7173: [$courselevel, 'course']));
7174: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7175: }
1.145 www 7176: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7177: unless ($space eq '0') {
1.336 albertel 7178: my @parts=split(/_/,$space);
7179: my $id=pop(@parts);
7180: my $part=join('_',@parts);
7181: if ($part eq '') { $part='0'; }
1.927 albertel 7182: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7183: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7184: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7185: }
1.395 albertel 7186: if ($recurse) { return undef; }
7187: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7188: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7189: # ---------------------------------------------------- Any other user namespace
7190: } elsif ($realm eq 'environment') {
7191: # ----------------------------------------------------------------- environment
1.620 albertel 7192: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7193: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7194: } else {
1.770 albertel 7195: if ($uname eq 'anonymous' && $udom eq '') {
7196: return '';
7197: }
1.219 albertel 7198: my %returnhash=&userenvironment($udom,$uname,
7199: $spacequalifierrest);
7200: return $returnhash{$spacequalifierrest};
7201: }
1.28 www 7202: } elsif ($realm eq 'system') {
1.48 www 7203: # ----------------------------------------------------------------- system.time
7204: if ($space eq 'time') {
7205: return time;
7206: }
1.696 albertel 7207: } elsif ($realm eq 'server') {
7208: # ----------------------------------------------------------------- system.time
7209: if ($space eq 'name') {
7210: return $ENV{'SERVER_NAME'};
7211: }
1.28 www 7212: }
1.48 www 7213: return '';
1.61 www 7214: }
7215:
1.927 albertel 7216: sub get_reply {
7217: my ($reply_value) = @_;
1.940 raeburn 7218: if (ref($reply_value) eq 'ARRAY') {
7219: if (wantarray) {
7220: return @$reply_value;
7221: }
7222: return $reply_value->[0];
7223: } else {
7224: return $reply_value;
1.927 albertel 7225: }
7226: }
7227:
1.691 raeburn 7228: sub check_group_parms {
7229: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7230: my @groupitems = ();
7231: my $resultitem;
1.927 albertel 7232: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7233: foreach my $group (@{$groups}) {
7234: foreach my $level (@levels) {
1.927 albertel 7235: my $item = $courseid.'.['.$group.'].'.$level->[0];
7236: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7237: }
7238: }
7239: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7240: $env{'course.'.$courseid.'.domain'},
7241: 'course',@groupitems);
7242: return $coursereply;
7243: }
7244:
7245: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7246: my ($courseid,@groups) = @_;
7247: @groups = sort(@groups);
1.691 raeburn 7248: return @groups;
7249: }
7250:
1.395 albertel 7251: sub packages_tab_default {
7252: my ($uri,$varname)=@_;
7253: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7254:
7255: my (@extension,@specifics,$do_default);
7256: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7257: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7258: if ($pack_type eq 'default') {
7259: $do_default=1;
7260: } elsif ($pack_type eq 'extension') {
7261: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7262: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7263: # only look at packages defaults for packages that this id is
1.738 albertel 7264: push(@specifics,[$package,$pack_type,$pack_part]);
7265: }
7266: }
7267: # first look for a package that matches the requested part id
7268: foreach my $package (@specifics) {
7269: my (undef,$pack_type,$pack_part)=@{$package};
7270: next if ($pack_part ne $part);
7271: if (defined($packagetab{"$pack_type&$name&default"})) {
7272: return $packagetab{"$pack_type&$name&default"};
7273: }
7274: }
7275: # look for any possible matching non extension_ package
7276: foreach my $package (@specifics) {
7277: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7278: if (defined($packagetab{"$pack_type&$name&default"})) {
7279: return $packagetab{"$pack_type&$name&default"};
7280: }
1.585 albertel 7281: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7282: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7283: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7284: }
7285: }
1.738 albertel 7286: # look for any posible extension_ match
7287: foreach my $package (@extension) {
7288: my ($package,$pack_type)=@{$package};
7289: if (defined($packagetab{"$pack_type&$name&default"})) {
7290: return $packagetab{"$pack_type&$name&default"};
7291: }
7292: if (defined($packagetab{$package."&$name&default"})) {
7293: return $packagetab{$package."&$name&default"};
7294: }
7295: }
7296: # look for a global default setting
7297: if ($do_default && defined($packagetab{"default&$name&default"})) {
7298: return $packagetab{"default&$name&default"};
7299: }
1.395 albertel 7300: return undef;
7301: }
7302:
1.334 albertel 7303: sub add_prefix_and_part {
7304: my ($prefix,$part)=@_;
7305: my $keyroot;
7306: if (defined($prefix) && $prefix !~ /^__/) {
7307: # prefix that has a part already
7308: $keyroot=$prefix;
7309: } elsif (defined($prefix)) {
7310: # prefix that is missing a part
7311: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7312: } else {
7313: # no prefix at all
7314: if (defined($part)) { $keyroot='_'.$part; }
7315: }
7316: return $keyroot;
7317: }
7318:
1.71 www 7319: # ---------------------------------------------------------------- Get metadata
7320:
1.599 albertel 7321: my %metaentry;
1.71 www 7322: sub metadata {
1.176 www 7323: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7324: $uri=&declutter($uri);
1.288 albertel 7325: # if it is a non metadata possible uri return quickly
1.529 albertel 7326: if (($uri eq '') ||
7327: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7328: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7329: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7330: return undef;
7331: }
7332: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7333: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7334: return undef;
1.288 albertel 7335: }
1.73 www 7336: my $filename=$uri;
7337: $uri=~s/\.meta$//;
1.172 www 7338: #
7339: # Is the metadata already cached?
1.177 www 7340: # Look at timestamp of caching
1.172 www 7341: # Everything is cached by the main uri, libraries are never directly cached
7342: #
1.428 albertel 7343: if (!defined($liburi)) {
1.599 albertel 7344: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7345: if (defined($cached)) { return $result->{':'.$what}; }
7346: }
7347: {
1.172 www 7348: #
7349: # Is this a recursive call for a library?
7350: #
1.599 albertel 7351: # if (! exists($metacache{$uri})) {
7352: # $metacache{$uri}={};
7353: # }
1.924 albertel 7354: my $cachetime = 60*60;
1.171 www 7355: if ($liburi) {
7356: $liburi=&declutter($liburi);
7357: $filename=$liburi;
1.401 bowersj2 7358: } else {
1.599 albertel 7359: &devalidate_cache_new('meta',$uri);
7360: undef(%metaentry);
1.401 bowersj2 7361: }
1.140 www 7362: my %metathesekeys=();
1.73 www 7363: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7364: my $metastring;
1.924 albertel 7365: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7366: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7367: $metastring =
1.929 albertel 7368: &Apache::lonnet::ssi_body($which,
1.924 albertel 7369: ('grade_target' => 'meta'));
7370: $cachetime = 1; # only want this cached in the child not long term
7371: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7372: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7373: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7374: $metastring=&getfile($file);
1.489 albertel 7375: }
1.208 albertel 7376: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7377: my $token;
1.140 www 7378: undef %metathesekeys;
1.71 www 7379: while ($token=$parser->get_token) {
1.339 albertel 7380: if ($token->[0] eq 'S') {
7381: if (defined($token->[2]->{'package'})) {
1.172 www 7382: #
7383: # This is a package - get package info
7384: #
1.339 albertel 7385: my $package=$token->[2]->{'package'};
7386: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7387: if (defined($token->[2]->{'id'})) {
7388: $keyroot.='_'.$token->[2]->{'id'};
7389: }
1.599 albertel 7390: if ($metaentry{':packages'}) {
7391: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7392: } else {
1.599 albertel 7393: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7394: }
1.736 albertel 7395: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7396: my $part=$keyroot;
7397: $part=~s/^\_//;
1.736 albertel 7398: if ($pack_entry=~/^\Q$package\E\&/ ||
7399: $pack_entry=~/^\Q$package\E_0\&/) {
7400: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7401: # ignore package.tab specified default values
7402: # here &package_tab_default() will fetch those
7403: if ($subp eq 'default') { next; }
1.736 albertel 7404: my $value=$packagetab{$pack_entry};
1.432 albertel 7405: my $unikey;
7406: if ($pack =~ /_0$/) {
7407: $unikey='parameter_0_'.$name;
7408: $part=0;
7409: } else {
7410: $unikey='parameter'.$keyroot.'_'.$name;
7411: }
1.339 albertel 7412: if ($subp eq 'display') {
7413: $value.=' [Part: '.$part.']';
7414: }
1.599 albertel 7415: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7416: $metathesekeys{$unikey}=1;
1.599 albertel 7417: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7418: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7419: }
1.599 albertel 7420: if (defined($metaentry{':'.$unikey.'.default'})) {
7421: $metaentry{':'.$unikey}=
7422: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7423: }
1.339 albertel 7424: }
7425: }
7426: } else {
1.172 www 7427: #
7428: # This is not a package - some other kind of start tag
1.339 albertel 7429: #
7430: my $entry=$token->[1];
7431: my $unikey;
7432: if ($entry eq 'import') {
7433: $unikey='';
7434: } else {
7435: $unikey=$entry;
7436: }
7437: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7438:
7439: if (defined($token->[2]->{'id'})) {
7440: $unikey.='_'.$token->[2]->{'id'};
7441: }
1.175 www 7442:
1.339 albertel 7443: if ($entry eq 'import') {
1.175 www 7444: #
7445: # Importing a library here
1.339 albertel 7446: #
7447: if ($depthcount<20) {
7448: my $location=$parser->get_text('/import');
7449: my $dir=$filename;
7450: $dir=~s|[^/]*$||;
7451: $location=&filelocation($dir,$location);
1.736 albertel 7452: my $metadata =
7453: &metadata($uri,'keys', $location,$unikey,
7454: $depthcount+1);
7455: foreach my $meta (split(',',$metadata)) {
7456: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7457: $metathesekeys{$meta}=1;
1.339 albertel 7458: }
7459: }
7460: } else {
7461:
7462: if (defined($token->[2]->{'name'})) {
7463: $unikey.='_'.$token->[2]->{'name'};
7464: }
7465: $metathesekeys{$unikey}=1;
1.736 albertel 7466: foreach my $param (@{$token->[3]}) {
7467: $metaentry{':'.$unikey.'.'.$param} =
7468: $token->[2]->{$param};
1.339 albertel 7469: }
7470: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7471: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7472: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7473: # only ws inside the tag, and not in default, so use default
7474: # as value
1.599 albertel 7475: $metaentry{':'.$unikey}=$default;
1.908 albertel 7476: } elsif ( $internaltext =~ /\S/ ) {
7477: # something interesting inside the tag
7478: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7479: } else {
1.908 albertel 7480: # no interesting values, don't set a default
1.339 albertel 7481: }
1.172 www 7482: # end of not-a-package not-a-library import
1.339 albertel 7483: }
1.172 www 7484: # end of not-a-package start tag
1.339 albertel 7485: }
1.172 www 7486: # the next is the end of "start tag"
1.339 albertel 7487: }
7488: }
1.483 albertel 7489: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7490: $extension = lc($extension);
7491: if ($extension eq 'htm') { $extension='html'; }
7492:
1.737 albertel 7493: foreach my $key (keys(%packagetab)) {
1.483 albertel 7494: #no specific packages #how's our extension
7495: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7496: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7497: \%metathesekeys);
7498: }
1.883 albertel 7499:
7500: if (!exists($metaentry{':packages'})
7501: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7502: foreach my $key (keys(%packagetab)) {
1.483 albertel 7503: #no specific packages well let's get default then
7504: if ($key!~/^default&/) { next; }
1.488 albertel 7505: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7506: \%metathesekeys);
7507: }
7508: }
1.338 www 7509: # are there custom rights to evaluate
1.599 albertel 7510: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7511:
1.338 www 7512: #
7513: # Importing a rights file here
1.339 albertel 7514: #
7515: unless ($depthcount) {
1.599 albertel 7516: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7517: my $dir=$filename;
7518: $dir=~s|[^/]*$||;
7519: $location=&filelocation($dir,$location);
1.736 albertel 7520: my $rights_metadata =
7521: &metadata($uri,'keys',$location,'_rights',
7522: $depthcount+1);
7523: foreach my $rights (split(',',$rights_metadata)) {
7524: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7525: $metathesekeys{$rights}=1;
1.339 albertel 7526: }
7527: }
7528: }
1.737 albertel 7529: # uniqifiy package listing
7530: my %seen;
7531: my @uniq_packages =
7532: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7533: $metaentry{':packages'} = join(',',@uniq_packages);
7534:
7535: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7536: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7537: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7538: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7539: # this is the end of "was not already recently cached
1.71 www 7540: }
1.599 albertel 7541: return $metaentry{':'.$what};
1.261 albertel 7542: }
7543:
1.488 albertel 7544: sub metadata_create_package_def {
1.483 albertel 7545: my ($uri,$key,$package,$metathesekeys)=@_;
7546: my ($pack,$name,$subp)=split(/\&/,$key);
7547: if ($subp eq 'default') { next; }
7548:
1.599 albertel 7549: if (defined($metaentry{':packages'})) {
7550: $metaentry{':packages'}.=','.$package;
1.483 albertel 7551: } else {
1.599 albertel 7552: $metaentry{':packages'}=$package;
1.483 albertel 7553: }
7554: my $value=$packagetab{$key};
7555: my $unikey;
7556: $unikey='parameter_0_'.$name;
1.599 albertel 7557: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7558: $$metathesekeys{$unikey}=1;
1.599 albertel 7559: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7560: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7561: }
1.599 albertel 7562: if (defined($metaentry{':'.$unikey.'.default'})) {
7563: $metaentry{':'.$unikey}=
7564: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7565: }
7566: }
7567:
1.261 albertel 7568: sub metadata_generate_part0 {
7569: my ($metadata,$metacache,$uri) = @_;
7570: my %allnames;
1.737 albertel 7571: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7572: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7573: my $part=$$metacache{':'.$metakey.'.part'};
7574: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7575: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7576: $allnames{$name}=$part;
7577: }
7578: }
7579: }
7580: foreach my $name (keys(%allnames)) {
7581: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7582: my $key=":parameter_0_$name";
1.261 albertel 7583: $$metacache{"$key.part"}='0';
7584: $$metacache{"$key.name"}=$name;
1.428 albertel 7585: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7586: $allnames{$name}.'_'.$name.
7587: '.type'};
1.428 albertel 7588: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7589: '.display'};
1.644 www 7590: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7591: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7592: $$metacache{"$key.display"}=$olddis;
7593: }
1.71 www 7594: }
7595:
1.764 albertel 7596: # ------------------------------------------------------ Devalidate title cache
7597:
7598: sub devalidate_title_cache {
7599: my ($url)=@_;
7600: if (!$env{'request.course.id'}) { return; }
7601: my $symb=&symbread($url);
7602: if (!$symb) { return; }
7603: my $key=$env{'request.course.id'}."\0".$symb;
7604: &devalidate_cache_new('title',$key);
7605: }
7606:
1.301 www 7607: # ------------------------------------------------- Get the title of a resource
7608:
7609: sub gettitle {
7610: my $urlsymb=shift;
7611: my $symb=&symbread($urlsymb);
1.534 albertel 7612: if ($symb) {
1.620 albertel 7613: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7614: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7615: if (defined($cached)) {
7616: return $result;
7617: }
1.534 albertel 7618: my ($map,$resid,$url)=&decode_symb($symb);
7619: my $title='';
1.907 albertel 7620: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7621: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7622: } else {
7623: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7624: &GDBM_READER(),0640)) {
7625: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7626: $title=$bighash{'title_'.$mapid.'.'.$resid};
7627: untie(%bighash);
7628: }
1.534 albertel 7629: }
7630: $title=~s/\&colon\;/\:/gs;
7631: if ($title) {
1.599 albertel 7632: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7633: }
7634: $urlsymb=$url;
7635: }
7636: my $title=&metadata($urlsymb,'title');
7637: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7638: return $title;
1.301 www 7639: }
1.613 albertel 7640:
1.614 albertel 7641: sub get_slot {
7642: my ($which,$cnum,$cdom)=@_;
7643: if (!$cnum || !$cdom) {
1.790 albertel 7644: (undef,my $courseid)=&whichuser();
1.620 albertel 7645: $cdom=$env{'course.'.$courseid.'.domain'};
7646: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7647: }
1.703 albertel 7648: my $key=join("\0",'slots',$cdom,$cnum,$which);
7649: my %slotinfo;
7650: if (exists($remembered{$key})) {
7651: $slotinfo{$which} = $remembered{$key};
7652: } else {
7653: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7654: &Apache::lonhomework::showhash(%slotinfo);
7655: my ($tmp)=keys(%slotinfo);
7656: if ($tmp=~/^error:/) { return (); }
7657: $remembered{$key} = $slotinfo{$which};
7658: }
1.616 albertel 7659: if (ref($slotinfo{$which}) eq 'HASH') {
7660: return %{$slotinfo{$which}};
7661: }
7662: return $slotinfo{$which};
1.614 albertel 7663: }
1.31 www 7664: # ------------------------------------------------- Update symbolic store links
7665:
7666: sub symblist {
7667: my ($mapname,%newhash)=@_;
1.438 www 7668: $mapname=&deversion(&declutter($mapname));
1.31 www 7669: my %hash;
1.620 albertel 7670: if (($env{'request.course.fn'}) && (%newhash)) {
7671: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7672: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7673: foreach my $url (keys %newhash) {
7674: next if ($url eq 'last_known'
7675: && $env{'form.no_update_last_known'});
7676: $hash{declutter($url)}=&encode_symb($mapname,
7677: $newhash{$url}->[1],
7678: $newhash{$url}->[0]);
1.191 harris41 7679: }
1.31 www 7680: if (untie(%hash)) {
7681: return 'ok';
7682: }
7683: }
7684: }
7685: return 'error';
1.212 www 7686: }
7687:
7688: # --------------------------------------------------------------- Verify a symb
7689:
7690: sub symbverify {
1.510 www 7691: my ($symb,$thisurl)=@_;
7692: my $thisfn=$thisurl;
1.439 www 7693: $thisfn=&declutter($thisfn);
1.215 www 7694: # direct jump to resource in page or to a sequence - will construct own symbs
7695: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7696: # check URL part
1.409 www 7697: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7698:
1.431 www 7699: unless ($url eq $thisfn) { return 0; }
1.213 www 7700:
1.216 www 7701: $symb=&symbclean($symb);
1.510 www 7702: $thisurl=&deversion($thisurl);
1.439 www 7703: $thisfn=&deversion($thisfn);
1.213 www 7704:
7705: my %bighash;
7706: my $okay=0;
1.431 www 7707:
1.620 albertel 7708: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7709: &GDBM_READER(),0640)) {
1.510 www 7710: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7711: unless ($ids) {
1.510 www 7712: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7713: }
7714: if ($ids) {
7715: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7716: foreach my $id (split(/\,/,$ids)) {
7717: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7718: if (
7719: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7720: eq $symb) {
1.620 albertel 7721: if (($env{'request.role.adv'}) ||
1.800 albertel 7722: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7723: $okay=1;
7724: }
7725: }
1.216 www 7726: }
7727: }
1.213 www 7728: untie(%bighash);
7729: }
7730: return $okay;
1.31 www 7731: }
7732:
1.210 www 7733: # --------------------------------------------------------------- Clean-up symb
7734:
7735: sub symbclean {
7736: my $symb=shift;
1.568 albertel 7737: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7738: # remove version from map
7739: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7740:
1.210 www 7741: # remove version from URL
7742: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7743:
1.507 www 7744: # remove wrapper
7745:
1.510 www 7746: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7747: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7748: return $symb;
1.409 www 7749: }
7750:
7751: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7752:
7753: sub encode_symb {
7754: my ($map,$resid,$url)=@_;
7755: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7756: }
1.409 www 7757:
7758: sub decode_symb {
1.568 albertel 7759: my $symb=shift;
7760: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7761: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7762: return (&fixversion($map),$resid,&fixversion($url));
7763: }
7764:
7765: sub fixversion {
7766: my $fn=shift;
1.609 banghart 7767: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7768: my %bighash;
7769: my $uri=&clutter($fn);
1.620 albertel 7770: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7771: # is this cached?
1.599 albertel 7772: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7773: if (defined($cached)) { return $result; }
7774: # unfortunately not cached, or expired
1.620 albertel 7775: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7776: &GDBM_READER(),0640)) {
7777: if ($bighash{'version_'.$uri}) {
7778: my $version=$bighash{'version_'.$uri};
1.444 www 7779: unless (($version eq 'mostrecent') ||
7780: ($version==&getversion($uri))) {
1.440 www 7781: $uri=~s/\.(\w+)$/\.$version\.$1/;
7782: }
7783: }
7784: untie %bighash;
1.413 www 7785: }
1.599 albertel 7786: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7787: }
7788:
7789: sub deversion {
7790: my $url=shift;
7791: $url=~s/\.\d+\.(\w+)$/\.$1/;
7792: return $url;
1.210 www 7793: }
7794:
1.31 www 7795: # ------------------------------------------------------ Return symb list entry
7796:
7797: sub symbread {
1.249 www 7798: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7799: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7800: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7801: # no filename provided? try from environment
1.44 www 7802: unless ($thisfn) {
1.620 albertel 7803: if ($env{'request.symb'}) {
7804: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7805: }
1.620 albertel 7806: $thisfn=$env{'request.filename'};
1.44 www 7807: }
1.569 albertel 7808: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7809: # is that filename actually a symb? Verify, clean, and return
7810: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7811: if (&symbverify($thisfn,$1)) {
1.620 albertel 7812: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7813: }
1.242 www 7814: }
1.44 www 7815: $thisfn=declutter($thisfn);
1.31 www 7816: my %hash;
1.37 www 7817: my %bighash;
7818: my $syval='';
1.620 albertel 7819: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7820: my $targetfn = $thisfn;
1.609 banghart 7821: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7822: $targetfn = 'adm/wrapper/'.$thisfn;
7823: }
1.687 albertel 7824: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7825: $targetfn=$1;
7826: }
1.620 albertel 7827: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7828: &GDBM_READER(),0640)) {
1.481 raeburn 7829: $syval=$hash{$targetfn};
1.37 www 7830: untie(%hash);
7831: }
7832: # ---------------------------------------------------------- There was an entry
7833: if ($syval) {
1.601 albertel 7834: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7835: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 7836: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7837: #return $env{$cache_str}='';
1.601 albertel 7838: #}
7839: #$syval.=$1;
7840: #}
1.37 www 7841: } else {
7842: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7843: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7844: &GDBM_READER(),0640)) {
1.37 www 7845: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7846: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7847: unless ($ids) {
7848: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7849: }
7850: unless ($ids) {
7851: # alias?
7852: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7853: }
1.37 www 7854: if ($ids) {
7855: # ------------------------------------------------------------------- Has ID(s)
7856: my @possibilities=split(/\,/,$ids);
1.39 www 7857: if ($#possibilities==0) {
7858: # ----------------------------------------------- There is only one possibility
1.37 www 7859: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7860: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7861: $resid,$thisfn);
1.249 www 7862: } elsif (!$donotrecurse) {
1.39 www 7863: # ------------------------------------------ There is more than one possibility
7864: my $realpossible=0;
1.800 albertel 7865: foreach my $id (@possibilities) {
7866: my $file=$bighash{'src_'.$id};
1.39 www 7867: if (&allowed('bre',$file)) {
1.800 albertel 7868: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7869: if ($bighash{'map_type_'.$mapid} ne 'page') {
7870: $realpossible++;
1.626 albertel 7871: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7872: $resid,$thisfn);
1.39 www 7873: }
7874: }
1.191 harris41 7875: }
1.39 www 7876: if ($realpossible!=1) { $syval=''; }
1.249 www 7877: } else {
7878: $syval='';
1.37 www 7879: }
7880: }
7881: untie(%bighash)
1.481 raeburn 7882: }
1.31 www 7883: }
1.62 www 7884: if ($syval) {
1.620 albertel 7885: return $env{$cache_str}=$syval;
1.62 www 7886: }
1.31 www 7887: }
1.949 raeburn 7888: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7889: return $env{$cache_str}='';
1.31 www 7890: }
7891:
7892: # ---------------------------------------------------------- Return random seed
7893:
1.32 www 7894: sub numval {
7895: my $txt=shift;
7896: $txt=~tr/A-J/0-9/;
7897: $txt=~tr/a-j/0-9/;
7898: $txt=~tr/K-T/0-9/;
7899: $txt=~tr/k-t/0-9/;
7900: $txt=~tr/U-Z/0-5/;
7901: $txt=~tr/u-z/0-5/;
7902: $txt=~s/\D//g;
1.564 albertel 7903: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7904: return int($txt);
1.368 albertel 7905: }
7906:
1.484 albertel 7907: sub numval2 {
7908: my $txt=shift;
7909: $txt=~tr/A-J/0-9/;
7910: $txt=~tr/a-j/0-9/;
7911: $txt=~tr/K-T/0-9/;
7912: $txt=~tr/k-t/0-9/;
7913: $txt=~tr/U-Z/0-5/;
7914: $txt=~tr/u-z/0-5/;
7915: $txt=~s/\D//g;
7916: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7917: my $total;
7918: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7919: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7920: return int($total);
7921: }
7922:
1.575 albertel 7923: sub numval3 {
7924: use integer;
7925: my $txt=shift;
7926: $txt=~tr/A-J/0-9/;
7927: $txt=~tr/a-j/0-9/;
7928: $txt=~tr/K-T/0-9/;
7929: $txt=~tr/k-t/0-9/;
7930: $txt=~tr/U-Z/0-5/;
7931: $txt=~tr/u-z/0-5/;
7932: $txt=~s/\D//g;
7933: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7934: my $total;
7935: foreach my $val (@txts) { $total+=$val; }
7936: if ($_64bit) { $total=(($total<<32)>>32); }
7937: return $total;
7938: }
7939:
1.675 albertel 7940: sub digest {
7941: my ($data)=@_;
7942: my $digest=&Digest::MD5::md5($data);
7943: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7944: my ($e,$f);
7945: {
7946: use integer;
7947: $e=($a+$b);
7948: $f=($c+$d);
7949: if ($_64bit) {
7950: $e=(($e<<32)>>32);
7951: $f=(($f<<32)>>32);
7952: }
7953: }
7954: if (wantarray) {
7955: return ($e,$f);
7956: } else {
7957: my $g;
7958: {
7959: use integer;
7960: $g=($e+$f);
7961: if ($_64bit) {
7962: $g=(($g<<32)>>32);
7963: }
7964: }
7965: return $g;
7966: }
7967: }
7968:
1.368 albertel 7969: sub latest_rnd_algorithm_id {
1.675 albertel 7970: return '64bit5';
1.366 albertel 7971: }
1.32 www 7972:
1.503 albertel 7973: sub get_rand_alg {
7974: my ($courseid)=@_;
1.790 albertel 7975: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7976: if ($courseid) {
1.620 albertel 7977: return $env{"course.$courseid.rndseed"};
1.503 albertel 7978: }
7979: return &latest_rnd_algorithm_id();
7980: }
7981:
1.562 albertel 7982: sub validCODE {
7983: my ($CODE)=@_;
7984: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7985: return 0;
7986: }
7987:
1.491 albertel 7988: sub getCODE {
1.620 albertel 7989: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7990: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7991: defined($Apache::lonhomework::parsing_a_task) ) &&
7992: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7993: return $Apache::lonhomework::history{'resource.CODE'};
7994: }
7995: return undef;
7996: }
7997:
1.31 www 7998: sub rndseed {
1.155 albertel 7999: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8000: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8001: if (!defined($symb)) {
1.366 albertel 8002: unless ($symb=$wsymb) { return time; }
8003: }
8004: if (!$courseid) { $courseid=$wcourseid; }
8005: if (!$domain) { $domain=$wdomain; }
8006: if (!$username) { $username=$wusername }
1.503 albertel 8007: my $which=&get_rand_alg();
1.803 albertel 8008:
1.491 albertel 8009: if (defined(&getCODE())) {
1.675 albertel 8010: if ($which eq '64bit5') {
8011: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8012: } elsif ($which eq '64bit4') {
1.575 albertel 8013: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8014: } else {
8015: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8016: }
1.675 albertel 8017: } elsif ($which eq '64bit5') {
8018: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8019: } elsif ($which eq '64bit4') {
8020: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8021: } elsif ($which eq '64bit3') {
8022: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8023: } elsif ($which eq '64bit2') {
8024: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8025: } elsif ($which eq '64bit') {
8026: return &rndseed_64bit($symb,$courseid,$domain,$username);
8027: }
8028: return &rndseed_32bit($symb,$courseid,$domain,$username);
8029: }
8030:
8031: sub rndseed_32bit {
8032: my ($symb,$courseid,$domain,$username)=@_;
8033: {
8034: use integer;
8035: my $symbchck=unpack("%32C*",$symb) << 27;
8036: my $symbseed=numval($symb) << 22;
8037: my $namechck=unpack("%32C*",$username) << 17;
8038: my $nameseed=numval($username) << 12;
8039: my $domainseed=unpack("%32C*",$domain) << 7;
8040: my $courseseed=unpack("%32C*",$courseid);
8041: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8042: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8043: #&logthis("rndseed :$num:$symb");
1.564 albertel 8044: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8045: return $num;
8046: }
8047: }
8048:
8049: sub rndseed_64bit {
8050: my ($symb,$courseid,$domain,$username)=@_;
8051: {
8052: use integer;
8053: my $symbchck=unpack("%32S*",$symb) << 21;
8054: my $symbseed=numval($symb) << 10;
8055: my $namechck=unpack("%32S*",$username);
8056:
8057: my $nameseed=numval($username) << 21;
8058: my $domainseed=unpack("%32S*",$domain) << 10;
8059: my $courseseed=unpack("%32S*",$courseid);
8060:
8061: my $num1=$symbchck+$symbseed+$namechck;
8062: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8063: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8064: #&logthis("rndseed :$num:$symb");
1.564 albertel 8065: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8066: return "$num1,$num2";
1.155 albertel 8067: }
1.366 albertel 8068: }
8069:
1.443 albertel 8070: sub rndseed_64bit2 {
8071: my ($symb,$courseid,$domain,$username)=@_;
8072: {
8073: use integer;
8074: # strings need to be an even # of cahracters long, it it is odd the
8075: # last characters gets thrown away
8076: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8077: my $symbseed=numval($symb) << 10;
8078: my $namechck=unpack("%32S*",$username.' ');
8079:
8080: my $nameseed=numval($username) << 21;
1.501 albertel 8081: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8082: my $courseseed=unpack("%32S*",$courseid.' ');
8083:
8084: my $num1=$symbchck+$symbseed+$namechck;
8085: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8086: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8087: #&logthis("rndseed :$num:$symb");
1.803 albertel 8088: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8089: return "$num1,$num2";
8090: }
8091: }
8092:
8093: sub rndseed_64bit3 {
8094: my ($symb,$courseid,$domain,$username)=@_;
8095: {
8096: use integer;
8097: # strings need to be an even # of cahracters long, it it is odd the
8098: # last characters gets thrown away
8099: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8100: my $symbseed=numval2($symb) << 10;
8101: my $namechck=unpack("%32S*",$username.' ');
8102:
8103: my $nameseed=numval2($username) << 21;
1.443 albertel 8104: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8105: my $courseseed=unpack("%32S*",$courseid.' ');
8106:
8107: my $num1=$symbchck+$symbseed+$namechck;
8108: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8109: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8110: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8111: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8112:
1.503 albertel 8113: return "$num1:$num2";
1.443 albertel 8114: }
8115: }
8116:
1.575 albertel 8117: sub rndseed_64bit4 {
8118: my ($symb,$courseid,$domain,$username)=@_;
8119: {
8120: use integer;
8121: # strings need to be an even # of cahracters long, it it is odd the
8122: # last characters gets thrown away
8123: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8124: my $symbseed=numval3($symb) << 10;
8125: my $namechck=unpack("%32S*",$username.' ');
8126:
8127: my $nameseed=numval3($username) << 21;
8128: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8129: my $courseseed=unpack("%32S*",$courseid.' ');
8130:
8131: my $num1=$symbchck+$symbseed+$namechck;
8132: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8133: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8134: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8135: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8136:
8137: return "$num1:$num2";
8138: }
8139: }
8140:
1.675 albertel 8141: sub rndseed_64bit5 {
8142: my ($symb,$courseid,$domain,$username)=@_;
8143: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8144: return "$num1:$num2";
8145: }
8146:
1.366 albertel 8147: sub rndseed_CODE_64bit {
8148: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8149: {
1.366 albertel 8150: use integer;
1.443 albertel 8151: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8152: my $symbseed=numval2($symb);
1.491 albertel 8153: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8154: my $CODEseed=numval(&getCODE());
1.443 albertel 8155: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8156: my $num1=$symbseed+$CODEchck;
8157: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8158: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8159: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8160: if ($_64bit) { $num1=(($num1<<32)>>32); }
8161: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8162: return "$num1:$num2";
1.366 albertel 8163: }
8164: }
8165:
1.575 albertel 8166: sub rndseed_CODE_64bit4 {
8167: my ($symb,$courseid,$domain,$username)=@_;
8168: {
8169: use integer;
8170: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8171: my $symbseed=numval3($symb);
8172: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8173: my $CODEseed=numval3(&getCODE());
8174: my $courseseed=unpack("%32S*",$courseid.' ');
8175: my $num1=$symbseed+$CODEchck;
8176: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8177: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8178: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8179: if ($_64bit) { $num1=(($num1<<32)>>32); }
8180: if ($_64bit) { $num2=(($num2<<32)>>32); }
8181: return "$num1:$num2";
8182: }
8183: }
8184:
1.675 albertel 8185: sub rndseed_CODE_64bit5 {
8186: my ($symb,$courseid,$domain,$username)=@_;
8187: my $code = &getCODE();
8188: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8189: return "$num1:$num2";
8190: }
8191:
1.366 albertel 8192: sub setup_random_from_rndseed {
8193: my ($rndseed)=@_;
1.503 albertel 8194: if ($rndseed =~/([,:])/) {
8195: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8196: &Math::Random::random_set_seed(abs($num1),abs($num2));
8197: } else {
8198: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8199: }
1.36 albertel 8200: }
8201:
1.474 albertel 8202: sub latest_receipt_algorithm_id {
1.835 albertel 8203: return 'receipt3';
1.474 albertel 8204: }
8205:
1.480 www 8206: sub recunique {
8207: my $fucourseid=shift;
8208: my $unique;
1.835 albertel 8209: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8210: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8211: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8212: } else {
8213: $unique=$perlvar{'lonReceipt'};
8214: }
8215: return unpack("%32C*",$unique);
8216: }
8217:
8218: sub recprefix {
8219: my $fucourseid=shift;
8220: my $prefix;
1.835 albertel 8221: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8222: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8223: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8224: } else {
8225: $prefix=$perlvar{'lonHostID'};
8226: }
8227: return unpack("%32C*",$prefix);
8228: }
8229:
1.76 www 8230: sub ireceipt {
1.474 albertel 8231: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8232:
8233: my $return =&recprefix($fucourseid).'-';
8234:
8235: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8236: $env{'request.state'} eq 'construct') {
8237: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8238: return $return;
8239: }
8240:
1.76 www 8241: my $cuname=unpack("%32C*",$funame);
8242: my $cudom=unpack("%32C*",$fudom);
8243: my $cucourseid=unpack("%32C*",$fucourseid);
8244: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8245: my $cunique=&recunique($fucourseid);
1.474 albertel 8246: my $cpart=unpack("%32S*",$part);
1.835 albertel 8247: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8248:
1.790 albertel 8249: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8250:
8251: $return.= ($cunique%$cuname+
8252: $cunique%$cudom+
8253: $cusymb%$cuname+
8254: $cusymb%$cudom+
8255: $cucourseid%$cuname+
8256: $cucourseid%$cudom+
8257: $cpart%$cuname+
8258: $cpart%$cudom);
8259: } else {
8260: $return.= ($cunique%$cuname+
8261: $cunique%$cudom+
8262: $cusymb%$cuname+
8263: $cusymb%$cudom+
8264: $cucourseid%$cuname+
8265: $cucourseid%$cudom);
8266: }
8267: return $return;
1.76 www 8268: }
8269:
8270: sub receipt {
1.474 albertel 8271: my ($part)=@_;
1.790 albertel 8272: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8273: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8274: }
1.260 ng 8275:
1.790 albertel 8276: sub whichuser {
8277: my ($passedsymb)=@_;
8278: my ($symb,$courseid,$domain,$name,$publicuser);
8279: if (defined($env{'form.grade_symb'})) {
8280: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8281: my $allowed=&allowed('vgr',$tmp_courseid);
8282: if (!$allowed &&
8283: exists($env{'request.course.sec'}) &&
8284: $env{'request.course.sec'} !~ /^\s*$/) {
8285: $allowed=&allowed('vgr',$tmp_courseid.
8286: '/'.$env{'request.course.sec'});
8287: }
8288: if ($allowed) {
8289: ($symb)=&get_env_multiple('form.grade_symb');
8290: $courseid=$tmp_courseid;
8291: ($domain)=&get_env_multiple('form.grade_domain');
8292: ($name)=&get_env_multiple('form.grade_username');
8293: return ($symb,$courseid,$domain,$name,$publicuser);
8294: }
8295: }
8296: if (!$passedsymb) {
8297: $symb=&symbread();
8298: } else {
8299: $symb=$passedsymb;
8300: }
8301: $courseid=$env{'request.course.id'};
8302: $domain=$env{'user.domain'};
8303: $name=$env{'user.name'};
8304: if ($name eq 'public' && $domain eq 'public') {
8305: if (!defined($env{'form.username'})) {
8306: $env{'form.username'}.=time.rand(10000000);
8307: }
8308: $name.=$env{'form.username'};
8309: }
8310: return ($symb,$courseid,$domain,$name,$publicuser);
8311:
8312: }
8313:
1.36 albertel 8314: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8315: # returns either the contents of the file or
8316: # -1 if the file doesn't exist
1.481 raeburn 8317: #
8318: # if the target is a file that was uploaded via DOCS,
8319: # a check will be made to see if a current copy exists on the local server,
8320: # if it does this will be served, otherwise a copy will be retrieved from
8321: # the home server for the course and stored in /home/httpd/html/userfiles on
8322: # the local server.
1.472 albertel 8323:
1.36 albertel 8324: sub getfile {
1.538 albertel 8325: my ($file) = @_;
1.609 banghart 8326: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8327: &repcopy($file);
8328: return &readfile($file);
8329: }
8330:
8331: sub repcopy_userfile {
8332: my ($file)=@_;
1.609 banghart 8333: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8334: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8335: my ($cdom,$cnum,$filename) =
1.811 albertel 8336: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8337: my $uri="/uploaded/$cdom/$cnum/$filename";
8338: if (-e "$file") {
1.828 www 8339: # we already have a local copy, check it out
1.538 albertel 8340: my @fileinfo = stat($file);
1.828 www 8341: my $rtncode;
8342: my $info;
1.538 albertel 8343: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8344: if ($lwpresp ne 'ok') {
1.828 www 8345: # there is no such file anymore, even though we had a local copy
1.482 albertel 8346: if ($rtncode eq '404') {
1.538 albertel 8347: unlink($file);
1.482 albertel 8348: }
8349: return -1;
8350: }
8351: if ($info < $fileinfo[9]) {
1.828 www 8352: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8353: return 'ok';
1.828 www 8354: } else {
8355: # the file is outdated, get rid of it
8356: unlink($file);
1.482 albertel 8357: }
1.828 www 8358: }
8359: # one way or the other, at this point, we don't have the file
8360: # construct the correct path for the file
8361: my @parts = ($cdom,$cnum);
8362: if ($filename =~ m|^(.+)/[^/]+$|) {
8363: push @parts, split(/\//,$1);
8364: }
8365: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8366: foreach my $part (@parts) {
8367: $path .= '/'.$part;
8368: if (!-e $path) {
8369: mkdir($path,0770);
1.482 albertel 8370: }
8371: }
1.828 www 8372: # now the path exists for sure
8373: # get a user agent
8374: my $ua=new LWP::UserAgent;
8375: my $transferfile=$file.'.in.transfer';
8376: # FIXME: this should flock
8377: if (-e $transferfile) { return 'ok'; }
8378: my $request;
8379: $uri=~s/^\///;
1.980 raeburn 8380: my $homeserver = &homeserver($cnum,$cdom);
8381: my $protocol = $protocol{$homeserver};
8382: $protocol = 'http' if ($protocol ne 'https');
8383: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8384: my $response=$ua->request($request,$transferfile);
8385: # did it work?
8386: if ($response->is_error()) {
8387: unlink($transferfile);
8388: &logthis("Userfile repcopy failed for $uri");
8389: return -1;
8390: }
8391: # worked, rename the transfer file
8392: rename($transferfile,$file);
1.607 raeburn 8393: return 'ok';
1.481 raeburn 8394: }
8395:
1.517 albertel 8396: sub tokenwrapper {
8397: my $uri=shift;
1.980 raeburn 8398: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8399: $uri=~s|^/||;
1.620 albertel 8400: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8401: my $token=$1;
1.552 albertel 8402: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8403: if ($udom && $uname && $file) {
8404: $file=~s|(\?\.*)*$||;
1.949 raeburn 8405: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 8406: my $homeserver = &homeserver($uname,$udom);
8407: my $protocol = $protocol{$homeserver};
8408: $protocol = 'http' if ($protocol ne 'https');
8409: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8410: (($uri=~/\?/)?'&':'?').'token='.$token.
8411: '&tokenissued='.$perlvar{'lonHostID'};
8412: } else {
8413: return '/adm/notfound.html';
8414: }
8415: }
8416:
1.828 www 8417: # call with reqtype HEAD: get last modification time
8418: # call with reqtype GET: get the file contents
8419: # Do not call this with reqtype GET for large files! It loads everything into memory
8420: #
1.481 raeburn 8421: sub getuploaded {
8422: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8423: $uri=~s/^\///;
1.980 raeburn 8424: my $homeserver = &homeserver($cnum,$cdom);
8425: my $protocol = $protocol{$homeserver};
8426: $protocol = 'http' if ($protocol ne 'https');
8427: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8428: my $ua=new LWP::UserAgent;
8429: my $request=new HTTP::Request($reqtype,$uri);
8430: my $response=$ua->request($request);
8431: $$rtncode = $response->code;
1.482 albertel 8432: if (! $response->is_success()) {
8433: return 'failed';
8434: }
8435: if ($reqtype eq 'HEAD') {
1.486 www 8436: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8437: } elsif ($reqtype eq 'GET') {
8438: $$info = $response->content;
1.472 albertel 8439: }
1.482 albertel 8440: return 'ok';
1.36 albertel 8441: }
8442:
1.481 raeburn 8443: sub readfile {
8444: my $file = shift;
8445: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8446: my $fh;
8447: open($fh,"<$file");
8448: my $a='';
1.800 albertel 8449: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8450: return $a;
8451: }
8452:
1.36 albertel 8453: sub filelocation {
1.590 banghart 8454: my ($dir,$file) = @_;
8455: my $location;
8456: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8457:
8458: if ($file =~ m-^/adm/-) {
8459: $file=~s-^/adm/wrapper/-/-;
8460: $file=~s-^/adm/coursedocs/showdoc/-/-;
8461: }
1.882 albertel 8462:
1.590 banghart 8463: if ($file=~m:^/~:) { # is a contruction space reference
8464: $location = $file;
8465: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8466: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8467: # is a correct contruction space reference
8468: $location = $file;
1.956 raeburn 8469: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8470: $location = $file;
1.609 banghart 8471: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8472: my ($udom,$uname,$filename)=
1.811 albertel 8473: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8474: my $home=&homeserver($uname,$udom);
8475: my $is_me=0;
8476: my @ids=¤t_machine_ids();
8477: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8478: if ($is_me) {
1.955 raeburn 8479: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8480: } else {
8481: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8482: $udom.'/'.$uname.'/'.$filename;
8483: }
1.882 albertel 8484: } elsif ($file =~ m-^/adm/-) {
8485: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8486: } else {
8487: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8488: $file=~s:^/res/:/:;
8489: if ( !( $file =~ m:^/:) ) {
8490: $location = $dir. '/'.$file;
8491: } else {
8492: $location = '/home/httpd/html/res'.$file;
8493: }
1.59 albertel 8494: }
1.590 banghart 8495: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8496: while ($location=~m{/\.\./}) {
8497: if ($location =~ m{/[^/]+/\.\./}) {
8498: $location=~ s{/[^/]+/\.\./}{/}g;
8499: } else {
8500: $location=~ s{/\.\./}{/}g;
8501: }
8502: } #remove dir/..
1.590 banghart 8503: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8504: return $location;
1.46 www 8505: }
1.36 albertel 8506:
1.46 www 8507: sub hreflocation {
8508: my ($dir,$file)=@_;
1.980 raeburn 8509: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8510: $file=filelocation($dir,$file);
1.700 albertel 8511: } elsif ($file=~m-^/adm/-) {
8512: $file=~s-^/adm/wrapper/-/-;
8513: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8514: }
8515: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8516: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8517: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8518: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8519: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8520: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8521: -/uploaded/$1/$2/-x;
1.46 www 8522: }
1.913 albertel 8523: if ($file=~ m{^/userfiles/}) {
8524: $file =~ s{^/userfiles/}{/uploaded/};
8525: }
1.462 albertel 8526: return $file;
1.465 albertel 8527: }
8528:
8529: sub current_machine_domains {
1.853 albertel 8530: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8531: }
8532:
8533: sub machine_domains {
8534: my ($hostname) = @_;
1.465 albertel 8535: my @domains;
1.838 albertel 8536: my %hostname = &all_hostnames();
1.465 albertel 8537: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8538: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8539: if ($hostname eq $name) {
1.844 albertel 8540: push(@domains,&host_domain($id));
1.465 albertel 8541: }
8542: }
8543: return @domains;
8544: }
8545:
8546: sub current_machine_ids {
1.853 albertel 8547: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8548: }
8549:
8550: sub machine_ids {
8551: my ($hostname) = @_;
8552: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8553: my @ids;
1.888 albertel 8554: my %name_to_host = &all_names();
1.889 albertel 8555: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8556: return @{ $name_to_host{$hostname} };
8557: }
8558: return;
1.31 www 8559: }
8560:
1.824 raeburn 8561: sub additional_machine_domains {
8562: my @domains;
8563: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8564: while( my $line = <$fh>) {
8565: $line =~ s/\s//g;
8566: push(@domains,$line);
8567: }
8568: return @domains;
8569: }
8570:
8571: sub default_login_domain {
8572: my $domain = $perlvar{'lonDefDomain'};
8573: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8574: foreach my $posdom (¤t_machine_domains(),
8575: &additional_machine_domains()) {
8576: if (lc($posdom) eq lc($testdomain)) {
8577: $domain=$posdom;
8578: last;
8579: }
8580: }
8581: return $domain;
8582: }
8583:
1.31 www 8584: # ------------------------------------------------------------- Declutters URLs
8585:
8586: sub declutter {
8587: my $thisfn=shift;
1.569 albertel 8588: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8589: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8590: $thisfn=~s/^\///;
1.697 albertel 8591: $thisfn=~s|^adm/wrapper/||;
8592: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8593: $thisfn=~s/^res\///;
1.235 www 8594: $thisfn=~s/\?.+$//;
1.268 www 8595: return $thisfn;
8596: }
8597:
8598: # ------------------------------------------------------------- Clutter up URLs
8599:
8600: sub clutter {
8601: my $thisfn='/'.&declutter(shift);
1.887 albertel 8602: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8603: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8604: $thisfn='/res'.$thisfn;
8605: }
1.694 albertel 8606: if ($thisfn !~m|/adm|) {
1.695 albertel 8607: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8608: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8609: } else {
8610: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8611: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8612: if ($embstyle eq 'ssi'
8613: || ($embstyle eq 'hdn')
8614: || ($embstyle eq 'rat')
8615: || ($embstyle eq 'prv')
8616: || ($embstyle eq 'ign')) {
8617: #do nothing with these
8618: } elsif (($embstyle eq 'img')
1.695 albertel 8619: || ($embstyle eq 'emb')
8620: || ($embstyle eq 'wrp')) {
8621: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8622: } elsif ($embstyle eq 'unk'
8623: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8624: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8625: } else {
1.718 www 8626: # &logthis("Got a blank emb style");
1.695 albertel 8627: }
1.694 albertel 8628: }
8629: }
1.31 www 8630: return $thisfn;
1.12 www 8631: }
8632:
1.787 albertel 8633: sub clutter_with_no_wrapper {
8634: my $uri = &clutter(shift);
8635: if ($uri =~ m-^/adm/-) {
8636: $uri =~ s-^/adm/wrapper/-/-;
8637: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8638: }
8639: return $uri;
8640: }
8641:
1.557 albertel 8642: sub freeze_escape {
8643: my ($value)=@_;
8644: if (ref($value)) {
8645: $value=&nfreeze($value);
8646: return '__FROZEN__'.&escape($value);
8647: }
8648: return &escape($value);
8649: }
8650:
1.11 www 8651:
1.557 albertel 8652: sub thaw_unescape {
8653: my ($value)=@_;
8654: if ($value =~ /^__FROZEN__/) {
8655: substr($value,0,10,undef);
8656: $value=&unescape($value);
8657: return &thaw($value);
8658: }
8659: return &unescape($value);
8660: }
8661:
1.436 albertel 8662: sub correct_line_ends {
8663: my ($result)=@_;
8664: $$result =~s/\r\n/\n/mg;
8665: $$result =~s/\r/\n/mg;
1.415 albertel 8666: }
1.1 albertel 8667: # ================================================================ Main Program
8668:
1.184 www 8669: sub goodbye {
1.204 albertel 8670: &logthis("Starting Shut down");
1.443 albertel 8671: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8672: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8673: #converted
1.599 albertel 8674: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8675: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8676: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8677: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8678: #1.1 only
1.870 albertel 8679: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8680: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8681: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8682: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8683: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8684: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8685: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8686: &flushcourselogs();
8687: &logthis("Shutting down");
8688: }
8689:
1.852 albertel 8690: sub get_dns {
1.869 albertel 8691: my ($url,$func,$ignore_cache) = @_;
8692: if (!$ignore_cache) {
8693: my ($content,$cached)=
8694: &Apache::lonnet::is_cached_new('dns',$url);
8695: if ($cached) {
8696: &$func($content);
8697: return;
8698: }
8699: }
8700:
8701: my %alldns;
1.852 albertel 8702: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8703: foreach my $dns (<$config>) {
8704: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 8705: my $line = $1;
8706: my ($host,$protocol) = split(/:/,$line);
8707: if ($protocol ne 'https') {
8708: $protocol = 'http';
8709: }
8710: $alldns{$host} = $protocol;
1.869 albertel 8711: }
8712: while (%alldns) {
8713: my ($dns) = keys(%alldns);
1.852 albertel 8714: my $ua=new LWP::UserAgent;
1.979 raeburn 8715: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 8716: my $response=$ua->request($request);
1.979 raeburn 8717: delete($alldns{$dns});
1.852 albertel 8718: next if ($response->is_error());
8719: my @content = split("\n",$response->content);
1.869 albertel 8720: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8721: &$func(\@content);
1.869 albertel 8722: return;
1.852 albertel 8723: }
8724: close($config);
1.871 albertel 8725: my $which = (split('/',$url))[3];
8726: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8727: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8728: my @content = <$config>;
8729: &$func(\@content);
8730: return;
1.852 albertel 8731: }
1.327 albertel 8732: # ------------------------------------------------------------ Read domain file
8733: {
1.852 albertel 8734: my $loaded;
1.846 albertel 8735: my %domain;
8736:
1.852 albertel 8737: sub parse_domain_tab {
8738: my ($lines) = @_;
8739: foreach my $line (@$lines) {
8740: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8741:
1.846 albertel 8742: chomp($line);
1.852 albertel 8743: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8744: my %this_domain;
8745: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8746: 'lang_def', 'city', 'longi', 'lati',
8747: 'primary') {
8748: $this_domain{$field} = shift(@elements);
8749: }
8750: $domain{$name} = \%this_domain;
1.852 albertel 8751: }
8752: }
1.864 albertel 8753:
8754: sub reset_domain_info {
8755: undef($loaded);
8756: undef(%domain);
8757: }
8758:
1.852 albertel 8759: sub load_domain_tab {
1.869 albertel 8760: my ($ignore_cache) = @_;
8761: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8762: my $fh;
8763: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8764: my @lines = <$fh>;
8765: &parse_domain_tab(\@lines);
1.448 albertel 8766: }
1.852 albertel 8767: close($fh);
8768: $loaded = 1;
1.327 albertel 8769: }
1.846 albertel 8770:
8771: sub domain {
1.852 albertel 8772: &load_domain_tab() if (!$loaded);
8773:
1.846 albertel 8774: my ($name,$what) = @_;
8775: return if ( !exists($domain{$name}) );
8776:
8777: if (!$what) {
8778: return $domain{$name}{'description'};
8779: }
8780: return $domain{$name}{$what};
8781: }
1.974 raeburn 8782:
8783: sub domain_info {
8784: &load_domain_tab() if (!$loaded);
8785: return %domain;
8786: }
8787:
1.327 albertel 8788: }
8789:
8790:
1.1 albertel 8791: # ------------------------------------------------------------- Read hosts file
8792: {
1.838 albertel 8793: my %hostname;
1.844 albertel 8794: my %hostdom;
1.845 albertel 8795: my %libserv;
1.852 albertel 8796: my $loaded;
1.888 albertel 8797: my %name_to_host;
1.852 albertel 8798:
8799: sub parse_hosts_tab {
8800: my ($file) = @_;
8801: foreach my $configline (@$file) {
8802: next if ($configline =~ /^(\#|\s*$ )/x);
8803: next if ($configline =~ /^\^/);
8804: chomp($configline);
1.968 raeburn 8805: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 8806: $name=~s/\s//g;
8807: if ($id && $domain && $role && $name) {
8808: $hostname{$id}=$name;
1.888 albertel 8809: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8810: $hostdom{$id}=$domain;
8811: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 8812: if (defined($protocol)) {
8813: if ($protocol eq 'https') {
8814: $protocol{$id} = $protocol;
8815: } else {
8816: $protocol{$id} = 'http';
8817: }
1.968 raeburn 8818: } else {
1.969 raeburn 8819: $protocol{$id} = 'http';
1.968 raeburn 8820: }
1.852 albertel 8821: }
8822: }
8823: }
1.864 albertel 8824:
8825: sub reset_hosts_info {
1.897 albertel 8826: &purge_remembered();
1.864 albertel 8827: &reset_domain_info();
8828: &reset_hosts_ip_info();
1.892 albertel 8829: undef(%name_to_host);
1.864 albertel 8830: undef(%hostname);
8831: undef(%hostdom);
8832: undef(%libserv);
8833: undef($loaded);
8834: }
1.1 albertel 8835:
1.852 albertel 8836: sub load_hosts_tab {
1.869 albertel 8837: my ($ignore_cache) = @_;
8838: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8839: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8840: my @config = <$config>;
8841: &parse_hosts_tab(\@config);
8842: close($config);
8843: $loaded=1;
1.1 albertel 8844: }
1.852 albertel 8845:
1.838 albertel 8846: sub hostname {
1.852 albertel 8847: &load_hosts_tab() if (!$loaded);
8848:
1.838 albertel 8849: my ($lonid) = @_;
8850: return $hostname{$lonid};
8851: }
1.845 albertel 8852:
1.838 albertel 8853: sub all_hostnames {
1.852 albertel 8854: &load_hosts_tab() if (!$loaded);
8855:
1.838 albertel 8856: return %hostname;
8857: }
1.845 albertel 8858:
1.888 albertel 8859: sub all_names {
8860: &load_hosts_tab() if (!$loaded);
8861:
8862: return %name_to_host;
8863: }
8864:
1.974 raeburn 8865: sub all_host_domain {
8866: &load_hosts_tab() if (!$loaded);
8867: return %hostdom;
8868: }
8869:
1.845 albertel 8870: sub is_library {
1.852 albertel 8871: &load_hosts_tab() if (!$loaded);
8872:
1.845 albertel 8873: return exists($libserv{$_[0]});
8874: }
8875:
8876: sub all_library {
1.852 albertel 8877: &load_hosts_tab() if (!$loaded);
8878:
1.845 albertel 8879: return %libserv;
8880: }
8881:
1.841 albertel 8882: sub get_servers {
1.852 albertel 8883: &load_hosts_tab() if (!$loaded);
8884:
1.841 albertel 8885: my ($domain,$type) = @_;
8886: my %possible_hosts = ($type eq 'library') ? %libserv
8887: : %hostname;
8888: my %result;
1.842 albertel 8889: if (ref($domain) eq 'ARRAY') {
8890: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8891: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8892: $result{$host} = $hostname;
8893: }
8894: }
8895: } else {
8896: while ( my ($host,$hostname) = each(%possible_hosts)) {
8897: if ($hostdom{$host} eq $domain) {
8898: $result{$host} = $hostname;
8899: }
1.841 albertel 8900: }
8901: }
8902: return %result;
8903: }
1.845 albertel 8904:
1.844 albertel 8905: sub host_domain {
1.852 albertel 8906: &load_hosts_tab() if (!$loaded);
8907:
1.844 albertel 8908: my ($lonid) = @_;
8909: return $hostdom{$lonid};
8910: }
8911:
1.841 albertel 8912: sub all_domains {
1.852 albertel 8913: &load_hosts_tab() if (!$loaded);
8914:
1.841 albertel 8915: my %seen;
8916: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8917: return @uniq;
8918: }
1.1 albertel 8919: }
8920:
1.847 albertel 8921: {
8922: my %iphost;
1.856 albertel 8923: my %name_to_ip;
8924: my %lonid_to_ip;
1.869 albertel 8925:
1.847 albertel 8926: sub get_hosts_from_ip {
8927: my ($ip) = @_;
8928: my %iphosts = &get_iphost();
8929: if (ref($iphosts{$ip})) {
8930: return @{$iphosts{$ip}};
8931: }
8932: return;
1.839 albertel 8933: }
1.864 albertel 8934:
8935: sub reset_hosts_ip_info {
8936: undef(%iphost);
8937: undef(%name_to_ip);
8938: undef(%lonid_to_ip);
8939: }
1.856 albertel 8940:
8941: sub get_host_ip {
8942: my ($lonid) = @_;
8943: if (exists($lonid_to_ip{$lonid})) {
8944: return $lonid_to_ip{$lonid};
8945: }
8946: my $name=&hostname($lonid);
8947: my $ip = gethostbyname($name);
8948: return if (!$ip || length($ip) ne 4);
8949: $ip=inet_ntoa($ip);
8950: $name_to_ip{$name} = $ip;
8951: $lonid_to_ip{$lonid} = $ip;
8952: return $ip;
8953: }
1.847 albertel 8954:
8955: sub get_iphost {
1.869 albertel 8956: my ($ignore_cache) = @_;
1.894 albertel 8957:
1.869 albertel 8958: if (!$ignore_cache) {
8959: if (%iphost) {
8960: return %iphost;
8961: }
8962: my ($ip_info,$cached)=
8963: &Apache::lonnet::is_cached_new('iphost','iphost');
8964: if ($cached) {
8965: %iphost = %{$ip_info->[0]};
8966: %name_to_ip = %{$ip_info->[1]};
8967: %lonid_to_ip = %{$ip_info->[2]};
8968: return %iphost;
8969: }
8970: }
1.894 albertel 8971:
8972: # get yesterday's info for fallback
8973: my %old_name_to_ip;
8974: my ($ip_info,$cached)=
8975: &Apache::lonnet::is_cached_new('iphost','iphost');
8976: if ($cached) {
8977: %old_name_to_ip = %{$ip_info->[1]};
8978: }
8979:
1.888 albertel 8980: my %name_to_host = &all_names();
8981: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8982: my $ip;
8983: if (!exists($name_to_ip{$name})) {
8984: $ip = gethostbyname($name);
8985: if (!$ip || length($ip) ne 4) {
1.894 albertel 8986: if (defined($old_name_to_ip{$name})) {
8987: $ip = $old_name_to_ip{$name};
8988: &logthis("Can't find $name defaulting to old $ip");
8989: } else {
8990: &logthis("Name $name no IP found");
8991: next;
8992: }
8993: } else {
8994: $ip=inet_ntoa($ip);
1.847 albertel 8995: }
8996: $name_to_ip{$name} = $ip;
8997: } else {
8998: $ip = $name_to_ip{$name};
1.653 albertel 8999: }
1.888 albertel 9000: foreach my $id (@{ $name_to_host{$name} }) {
9001: $lonid_to_ip{$id} = $ip;
9002: }
9003: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9004: }
1.869 albertel 9005: &Apache::lonnet::do_cache_new('iphost','iphost',
9006: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9007: 48*60*60);
1.869 albertel 9008:
1.847 albertel 9009: return %iphost;
1.598 albertel 9010: }
9011: }
9012:
1.862 albertel 9013: BEGIN {
9014:
9015: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9016: unless ($readit) {
9017: {
9018: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9019: %perlvar = (%perlvar,%{$configvars});
9020: }
9021:
9022:
1.1 albertel 9023: # ------------------------------------------------------ Read spare server file
9024: {
1.448 albertel 9025: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9026:
9027: while (my $configline=<$config>) {
9028: chomp($configline);
1.284 matthew 9029: if ($configline) {
1.784 albertel 9030: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9031: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9032: push(@{ $spareid{$type} }, $host);
1.1 albertel 9033: }
9034: }
1.448 albertel 9035: close($config);
1.1 albertel 9036: }
1.11 www 9037: # ------------------------------------------------------------ Read permissions
9038: {
1.448 albertel 9039: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9040:
9041: while (my $configline=<$config>) {
1.448 albertel 9042: chomp($configline);
9043: if ($configline) {
9044: my ($role,$perm)=split(/ /,$configline);
9045: if ($perm ne '') { $pr{$role}=$perm; }
9046: }
1.11 www 9047: }
1.448 albertel 9048: close($config);
1.11 www 9049: }
9050:
9051: # -------------------------------------------- Read plain texts for permissions
9052: {
1.448 albertel 9053: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9054:
9055: while (my $configline=<$config>) {
1.448 albertel 9056: chomp($configline);
9057: if ($configline) {
1.742 raeburn 9058: my ($short,@plain)=split(/:/,$configline);
9059: %{$prp{$short}} = ();
9060: if (@plain > 0) {
9061: $prp{$short}{'std'} = $plain[0];
9062: for (my $i=1; $i<@plain; $i++) {
9063: $prp{$short}{'alt'.$i} = $plain[$i];
9064: }
9065: }
1.448 albertel 9066: }
1.135 www 9067: }
1.448 albertel 9068: close($config);
1.135 www 9069: }
9070:
9071: # ---------------------------------------------------------- Read package table
9072: {
1.448 albertel 9073: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9074:
9075: while (my $configline=<$config>) {
1.483 albertel 9076: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9077: chomp($configline);
9078: my ($short,$plain)=split(/:/,$configline);
9079: my ($pack,$name)=split(/\&/,$short);
9080: if ($plain ne '') {
9081: $packagetab{$pack.'&'.$name.'&name'}=$name;
9082: $packagetab{$short}=$plain;
9083: }
1.11 www 9084: }
1.448 albertel 9085: close($config);
1.329 matthew 9086: }
9087:
9088: # ------------- set up temporary directory
9089: {
9090: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9091:
1.11 www 9092: }
9093:
1.794 albertel 9094: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9095: 'compress_threshold'=> 20_000,
9096: });
1.185 www 9097:
1.281 www 9098: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9099: $dumpcount=0;
1.958 www 9100: $locknum=0;
1.22 www 9101:
1.163 harris41 9102: &logtouch();
1.672 albertel 9103: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9104: $readit=1;
1.564 albertel 9105: {
9106: use integer;
9107: my $test=(2**32)+1;
1.568 albertel 9108: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9109: &logthis(" Detected 64bit platform ($_64bit)");
9110: }
1.195 www 9111: }
1.1 albertel 9112: }
1.179 www 9113:
1.1 albertel 9114: 1;
1.191 harris41 9115: __END__
9116:
1.243 albertel 9117: =pod
9118:
1.191 harris41 9119: =head1 NAME
9120:
1.243 albertel 9121: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9122:
9123: =head1 SYNOPSIS
9124:
1.243 albertel 9125: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9126:
9127: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9128:
1.243 albertel 9129: Common parameters:
9130:
9131: =over 4
9132:
9133: =item *
9134:
9135: $uname : an internal username (if $cname expecting a course Id specifically)
9136:
9137: =item *
9138:
9139: $udom : a domain (if $cdom expecting a course's domain specifically)
9140:
9141: =item *
9142:
9143: $symb : a resource instance identifier
9144:
9145: =item *
9146:
9147: $namespace : the name of a .db file that contains the data needed or
9148: being set.
9149:
9150: =back
9151:
1.394 bowersj2 9152: =head1 OVERVIEW
1.191 harris41 9153:
1.394 bowersj2 9154: lonnet provides subroutines which interact with the
9155: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9156: about classes, users, and resources.
1.243 albertel 9157:
9158: For many of these objects you can also use this to store data about
9159: them or modify them in various ways.
1.191 harris41 9160:
1.394 bowersj2 9161: =head2 Symbs
1.191 harris41 9162:
1.394 bowersj2 9163: To identify a specific instance of a resource, LON-CAPA uses symbols
9164: or "symbs"X<symb>. These identifiers are built from the URL of the
9165: map, the resource number of the resource in the map, and the URL of
9166: the resource itself. The latter is somewhat redundant, but might help
9167: if maps change.
9168:
9169: An example is
9170:
9171: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9172:
9173: The respective map entry is
9174:
9175: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9176: title="Problem 2">
9177: </resource>
9178:
9179: Symbs are used by the random number generator, as well as to store and
9180: restore data specific to a certain instance of for example a problem.
9181:
9182: =head2 Storing And Retrieving Data
9183:
9184: X<store()>X<cstore()>X<restore()>Three of the most important functions
9185: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9186: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9187: is is the non-critical message twin of cstore. These functions are for
9188: handlers to store a perl hash to a user's permanent data space in an
9189: easy manner, and to retrieve it again on another call. It is expected
9190: that a handler would use this once at the beginning to retrieve data,
9191: and then again once at the end to send only the new data back.
9192:
9193: The data is stored in the user's data directory on the user's
9194: homeserver under the ID of the course.
9195:
9196: The hash that is returned by restore will have all of the previous
9197: value for all of the elements of the hash.
9198:
9199: Example:
9200:
9201: #creating a hash
9202: my %hash;
9203: $hash{'foo'}='bar';
9204:
9205: #storing it
9206: &Apache::lonnet::cstore(\%hash);
9207:
9208: #changing a value
9209: $hash{'foo'}='notbar';
9210:
9211: #adding a new value
9212: $hash{'bar'}='foo';
9213: &Apache::lonnet::cstore(\%hash);
9214:
9215: #retrieving the hash
9216: my %history=&Apache::lonnet::restore();
9217:
9218: #print the hash
9219: foreach my $key (sort(keys(%history))) {
9220: print("\%history{$key} = $history{$key}");
9221: }
9222:
9223: Will print out:
1.191 harris41 9224:
1.394 bowersj2 9225: %history{1:foo} = bar
9226: %history{1:keys} = foo:timestamp
9227: %history{1:timestamp} = 990455579
9228: %history{2:bar} = foo
9229: %history{2:foo} = notbar
9230: %history{2:keys} = foo:bar:timestamp
9231: %history{2:timestamp} = 990455580
9232: %history{bar} = foo
9233: %history{foo} = notbar
9234: %history{timestamp} = 990455580
9235: %history{version} = 2
9236:
9237: Note that the special hash entries C<keys>, C<version> and
9238: C<timestamp> were added to the hash. C<version> will be equal to the
9239: total number of versions of the data that have been stored. The
9240: C<timestamp> attribute will be the UNIX time the hash was
9241: stored. C<keys> is available in every historical section to list which
9242: keys were added or changed at a specific historical revision of a
9243: hash.
9244:
9245: B<Warning>: do not store the hash that restore returns directly. This
9246: will cause a mess since it will restore the historical keys as if the
9247: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9248:
1.394 bowersj2 9249: Calling convention:
1.191 harris41 9250:
1.394 bowersj2 9251: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9252: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9253:
1.394 bowersj2 9254: For more detailed information, see lonnet specific documentation.
1.191 harris41 9255:
1.394 bowersj2 9256: =head1 RETURN MESSAGES
1.191 harris41 9257:
1.394 bowersj2 9258: =over 4
1.191 harris41 9259:
1.394 bowersj2 9260: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9261:
1.394 bowersj2 9262: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9263: when the connection is brought back up
1.191 harris41 9264:
1.394 bowersj2 9265: =item * B<con_failed>: unable to contact remote host and unable to save message
9266: for later delivery
1.191 harris41 9267:
1.967 bisitz 9268: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9269:
1.394 bowersj2 9270: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9271: that was requested
1.191 harris41 9272:
1.243 albertel 9273: =back
1.191 harris41 9274:
1.243 albertel 9275: =head1 PUBLIC SUBROUTINES
1.191 harris41 9276:
1.243 albertel 9277: =head2 Session Environment Functions
1.191 harris41 9278:
1.243 albertel 9279: =over 4
1.191 harris41 9280:
1.394 bowersj2 9281: =item *
9282: X<appenv()>
1.949 raeburn 9283: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9284: the user envirnoment file, and will be restored for each access this
1.620 albertel 9285: user makes during this session, also modifies the %env for the current
1.949 raeburn 9286: process. Optional rolesarrayref - if defined contains a reference to an array
9287: of roles which are exempt from the restriction on modifying user.role entries
9288: in the user's environment.db and in %env.
1.191 harris41 9289:
9290: =item *
1.394 bowersj2 9291: X<delenv()>
9292: B<delenv($regexp)>: removes all items from the session
9293: environment file that matches the regular expression in $regexp. The
1.620 albertel 9294: values are also delted from the current processes %env.
1.191 harris41 9295:
1.795 albertel 9296: =item * get_env_multiple($name)
9297:
9298: gets $name from the %env hash, it seemlessly handles the cases where multiple
9299: values may be defined and end up as an array ref.
9300:
9301: returns an array of values
9302:
1.243 albertel 9303: =back
9304:
9305: =head2 User Information
1.191 harris41 9306:
1.243 albertel 9307: =over 4
1.191 harris41 9308:
9309: =item *
1.394 bowersj2 9310: X<queryauthenticate()>
9311: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9312: authentication scheme
9313:
9314: =item *
1.394 bowersj2 9315: X<authenticate()>
9316: B<authenticate($uname,$upass,$udom)>: try to
9317: authenticate user from domain's lib servers (first use the current
9318: one). C<$upass> should be the users password.
1.191 harris41 9319:
9320: =item *
1.394 bowersj2 9321: X<homeserver()>
9322: B<homeserver($uname,$udom)>: find the server which has
9323: the user's directory and files (there must be only one), this caches
9324: the answer, and also caches if there is a borken connection.
1.191 harris41 9325:
9326: =item *
1.394 bowersj2 9327: X<idget()>
9328: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9329: (IDs are a unique resource in a domain, there must be only 1 ID per
9330: username, and only 1 username per ID in a specific domain) (returns
9331: hash: id=>name,id=>name)
1.191 harris41 9332:
9333: =item *
1.394 bowersj2 9334: X<idrget()>
9335: B<idrget($udom,@unames)>: find the IDs behind a list of
9336: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9337:
9338: =item *
1.394 bowersj2 9339: X<idput()>
9340: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9341:
9342: =item *
1.394 bowersj2 9343: X<rolesinit()>
9344: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9345:
9346: =item *
1.551 albertel 9347: X<getsection()>
9348: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9349: course $cname, return section name/number or '' for "not in course"
9350: and '-1' for "no section"
9351:
9352: =item *
1.394 bowersj2 9353: X<userenvironment()>
9354: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9355: passed in @what from the requested user's environment, returns a hash
9356:
1.858 raeburn 9357: =item *
9358: X<userlog_query()>
1.859 albertel 9359: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9360: activity.log file. %filters defines filters applied when parsing the
9361: log file. These can be start or end timestamps, or the type of action
9362: - log to look for Login or Logout events, check for Checkin or
9363: Checkout, role for role selection. The response is in the form
9364: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9365: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9366:
1.243 albertel 9367: =back
9368:
9369: =head2 User Roles
9370:
9371: =over 4
9372:
9373: =item *
9374:
1.810 raeburn 9375: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9376: F: full access
9377: U,I,K: authentication modes (cxx only)
9378: '': forbidden
9379: 1: user needs to choose course
9380: 2: browse allowed
1.766 albertel 9381: A: passphrase authentication needed
1.243 albertel 9382:
9383: =item *
9384:
9385: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9386: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9387: and course level
9388:
9389: =item *
9390:
9391: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
9392: explanation of a user role term
9393:
1.832 raeburn 9394: =item *
9395:
1.935 raeburn 9396: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9397: All arguments are optional. Returns a hash of a roles, either for
9398: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9399: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9400: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9401: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9402: For each key, value is set to colon-separated start and end times for
9403: the role. If no username and domain are specified, will default to
1.934 raeburn 9404: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9405: of role statuses (active, future or previous), roles
9406: (e.g., cc,in, st etc.) and domains of the roles which can be used
9407: to restrict the list of roles reported. If no array ref is
9408: provided for types, will default to return only active roles.
1.834 albertel 9409:
1.243 albertel 9410: =back
9411:
9412: =head2 User Modification
9413:
9414: =over 4
9415:
9416: =item *
9417:
1.957 raeburn 9418: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9419: user for the level given by URL. Optional start and end dates (leave empty
9420: string or zero for "no date")
1.191 harris41 9421:
9422: =item *
9423:
1.243 albertel 9424: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9425: change a users, password, possible return values are: ok,
9426: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9427: refused
1.191 harris41 9428:
9429: =item *
9430:
1.243 albertel 9431: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9432:
9433: =item *
9434:
1.963 raeburn 9435: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9436: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9437: modify user
1.191 harris41 9438:
9439: =item *
9440:
1.286 matthew 9441: modifystudent
9442:
1.957 raeburn 9443: modify a student's enrollment and identification information.
1.286 matthew 9444: The course id is resolved based on the current users environment.
9445: This means the envoking user must be a course coordinator or otherwise
9446: associated with a course.
9447:
1.297 matthew 9448: This call is essentially a wrapper for lonnet::modifyuser and
9449: lonnet::modify_student_enrollment
1.286 matthew 9450:
9451: Inputs:
9452:
9453: =over 4
9454:
1.957 raeburn 9455: =item B<$udom> Student's loncapa domain
1.286 matthew 9456:
1.957 raeburn 9457: =item B<$uname> Student's loncapa login name
1.286 matthew 9458:
1.964 bisitz 9459: =item B<$uid> Student/Employee ID
1.286 matthew 9460:
1.957 raeburn 9461: =item B<$umode> Student's authentication mode
1.286 matthew 9462:
1.957 raeburn 9463: =item B<$upass> Student's password
1.286 matthew 9464:
1.957 raeburn 9465: =item B<$first> Student's first name
1.286 matthew 9466:
1.957 raeburn 9467: =item B<$middle> Student's middle name
1.286 matthew 9468:
1.957 raeburn 9469: =item B<$last> Student's last name
1.286 matthew 9470:
1.957 raeburn 9471: =item B<$gene> Student's generation
1.286 matthew 9472:
1.957 raeburn 9473: =item B<$usec> Student's section in course
1.286 matthew 9474:
9475: =item B<$end> Unix time of the roles expiration
9476:
9477: =item B<$start> Unix time of the roles start date
9478:
9479: =item B<$forceid> If defined, allow $uid to be changed
9480:
9481: =item B<$desiredhome> server to use as home server for student
9482:
1.957 raeburn 9483: =item B<$email> Student's permanent e-mail address
9484:
9485: =item B<$type> Type of enrollment (auto or manual)
9486:
1.963 raeburn 9487: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9488:
9489: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9490:
1.963 raeburn 9491: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9492:
1.963 raeburn 9493: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9494:
1.963 raeburn 9495: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9496:
1.286 matthew 9497: =back
1.297 matthew 9498:
9499: =item *
9500:
9501: modify_student_enrollment
9502:
9503: Change a students enrollment status in a class. The environment variable
9504: 'role.request.course' must be defined for this function to proceed.
9505:
9506: Inputs:
9507:
9508: =over 4
9509:
9510: =item $udom, students domain
9511:
9512: =item $uname, students name
9513:
9514: =item $uid, students user id
9515:
9516: =item $first, students first name
9517:
9518: =item $middle
9519:
9520: =item $last
9521:
9522: =item $gene
9523:
9524: =item $usec
9525:
9526: =item $end
9527:
9528: =item $start
9529:
1.957 raeburn 9530: =item $type
9531:
9532: =item $locktype
9533:
9534: =item $cid
9535:
9536: =item $selfenroll
9537:
9538: =item $context
9539:
1.297 matthew 9540: =back
9541:
1.191 harris41 9542:
9543: =item *
9544:
1.243 albertel 9545: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9546: custom role; give a custom role to a user for the level given by URL. Specify
9547: name and domain of role author, and role name
1.191 harris41 9548:
9549: =item *
9550:
1.243 albertel 9551: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9552:
9553: =item *
9554:
1.243 albertel 9555: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9556:
9557: =back
9558:
9559: =head2 Course Infomation
9560:
9561: =over 4
1.191 harris41 9562:
9563: =item *
9564:
1.631 albertel 9565: coursedescription($courseid) : returns a hash of information about the
9566: specified course id, including all environment settings for the
9567: course, the description of the course will be in the hash under the
9568: key 'description'
1.191 harris41 9569:
9570: =item *
9571:
1.624 albertel 9572: resdata($name,$domain,$type,@which) : request for current parameter
9573: setting for a specific $type, where $type is either 'course' or 'user',
9574: @what should be a list of parameters to ask about. This routine caches
9575: answers for 5 minutes.
1.243 albertel 9576:
1.877 foxr 9577: =item *
9578:
9579: get_courseresdata($courseid, $domain) : dump the entire course resource
9580: data base, returning a hash that is keyed by the resource name and has
9581: values that are the resource value. I believe that the timestamps and
9582: versions are also returned.
9583:
9584:
1.243 albertel 9585: =back
9586:
9587: =head2 Course Modification
9588:
9589: =over 4
1.191 harris41 9590:
9591: =item *
9592:
1.243 albertel 9593: writecoursepref($courseid,%prefs) : write preferences (environment
9594: database) for a course
1.191 harris41 9595:
9596: =item *
9597:
1.243 albertel 9598: createcourse($udom,$description,$url) : make/modify course
9599:
9600: =back
9601:
9602: =head2 Resource Subroutines
9603:
9604: =over 4
1.191 harris41 9605:
9606: =item *
9607:
1.243 albertel 9608: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9609:
9610: =item *
9611:
1.243 albertel 9612: repcopy($filename) : subscribes to the requested file, and attempts to
9613: replicate from the owning library server, Might return
1.607 raeburn 9614: 'unavailable', 'not_found', 'forbidden', 'ok', or
9615: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9616: resource. Expects the local filesystem pathname
9617: (/home/httpd/html/res/....)
9618:
9619: =back
9620:
9621: =head2 Resource Information
9622:
9623: =over 4
1.191 harris41 9624:
9625: =item *
9626:
1.243 albertel 9627: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9628: a vairety of different possible values, $varname should be a request
9629: string, and the other parameters can be used to specify who and what
9630: one is asking about.
9631:
9632: Possible values for $varname are environment.lastname (or other item
9633: from the envirnment hash), user.name (or someother aspect about the
9634: user), resource.0.maxtries (or some other part and parameter of a
9635: resource)
1.204 albertel 9636:
9637: =item *
9638:
1.243 albertel 9639: directcondval($number) : get current value of a condition; reads from a state
9640: string
1.204 albertel 9641:
9642: =item *
9643:
1.243 albertel 9644: condval($condidx) : value of condition index based on state
1.204 albertel 9645:
9646: =item *
9647:
1.243 albertel 9648: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9649: resource's metadata, $what should be either a specific key, or either
9650: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9651: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9652:
9653: this function automatically caches all requests
1.191 harris41 9654:
9655: =item *
9656:
1.243 albertel 9657: metadata_query($query,$custom,$customshow) : make a metadata query against the
9658: network of library servers; returns file handle of where SQL and regex results
9659: will be stored for query
1.191 harris41 9660:
9661: =item *
9662:
1.243 albertel 9663: symbread($filename) : return symbolic list entry (filename argument optional);
9664: returns the data handle
1.191 harris41 9665:
9666: =item *
9667:
1.243 albertel 9668: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9669: a possible symb for the URL in $thisfn, and if is an encryypted
9670: resource that the user accessed using /enc/ returns a 1 on success, 0
9671: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9672: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9673:
1.191 harris41 9674:
9675: =item *
9676:
1.243 albertel 9677: symbclean($symb) : removes versions numbers from a symb, returns the
9678: cleaned symb
1.191 harris41 9679:
9680: =item *
9681:
1.243 albertel 9682: is_on_map($uri) : checks if the $uri is somewhere on the current
9683: course map, user must be in a course for it to work.
1.191 harris41 9684:
9685: =item *
9686:
1.243 albertel 9687: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9688:
9689: =item *
9690:
1.243 albertel 9691: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9692: a random seed, all arguments are optional, if they aren't sent it uses the
9693: environment to derive them. Note: if symb isn't sent and it can't get one
9694: from &symbread it will use the current time as its return value
1.191 harris41 9695:
9696: =item *
9697:
1.243 albertel 9698: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9699: unfakeable, receipt
1.191 harris41 9700:
9701: =item *
9702:
1.620 albertel 9703: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9704:
9705: =item *
9706:
1.243 albertel 9707: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9708:
9709: =item *
9710:
1.243 albertel 9711: 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 9712:
9713: =item *
9714:
1.243 albertel 9715: 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 9716:
9717: =item *
9718:
1.243 albertel 9719: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9720:
9721: =item *
9722:
1.243 albertel 9723: devalidate($symb) : devalidate temporary spreadsheet calculations,
9724: forcing spreadsheet to reevaluate the resource scores next time.
9725:
9726: =back
9727:
9728: =head2 Storing/Retreiving Data
9729:
9730: =over 4
1.191 harris41 9731:
9732: =item *
9733:
1.243 albertel 9734: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9735: for this url; hashref needs to be given and should be a \%hashname; the
9736: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9737: be derived from the env
1.191 harris41 9738:
9739: =item *
9740:
1.243 albertel 9741: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9742: uses critical subroutine
1.191 harris41 9743:
9744: =item *
9745:
1.243 albertel 9746: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9747: all args are optional
1.191 harris41 9748:
9749: =item *
9750:
1.717 albertel 9751: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9752: dumps the complete (or key matching regexp) namespace into a hash
9753: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9754: normally &store()ed into
9755:
9756: $range should be either an integer '100' (give me the first 100
9757: matching records)
9758: or be two integers sperated by a - with no spaces
9759: '30-50' (give me the 30th through the 50th matching
9760: records)
9761:
9762:
9763: =item *
9764:
9765: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9766: replaces a &store() version of data with a replacement set of data
9767: for a particular resource in a namespace passed in the $storehash hash
9768: reference
9769:
9770: =item *
9771:
1.243 albertel 9772: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9773: works very similar to store/cstore, but all data is stored in a
9774: temporary location and can be reset using tmpreset, $storehash should
9775: be a hash reference, returns nothing on success
1.191 harris41 9776:
9777: =item *
9778:
1.243 albertel 9779: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9780: similar to restore, but all data is stored in a temporary location and
9781: can be reset using tmpreset. Returns a hash of values on success,
9782: error string otherwise.
1.191 harris41 9783:
9784: =item *
9785:
1.243 albertel 9786: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9787: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9788:
9789: =item *
9790:
1.243 albertel 9791: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9792: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9793:
9794: =item *
9795:
1.243 albertel 9796: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9797: namesp ($udom and $uname are optional)
1.191 harris41 9798:
9799: =item *
9800:
1.702 albertel 9801: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9802: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9803: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9804:
1.702 albertel 9805: $range should be either an integer '100' (give me the first 100
9806: matching records)
9807: or be two integers sperated by a - with no spaces
9808: '30-50' (give me the 30th through the 50th matching
9809: records)
1.449 matthew 9810: =item *
9811:
9812: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9813: $store can be a scalar, an array reference, or if the amount to be
9814: incremented is > 1, a hash reference.
9815:
9816: ($udom and $uname are optional)
1.191 harris41 9817:
9818: =item *
9819:
1.243 albertel 9820: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9821: ($udom and $uname are optional)
1.191 harris41 9822:
9823: =item *
9824:
1.243 albertel 9825: cput($namespace,$storehash,$udom,$uname) : critical put
9826: ($udom and $uname are optional)
1.191 harris41 9827:
9828: =item *
9829:
1.748 albertel 9830: newput($namespace,$storehash,$udom,$uname) :
9831:
9832: Attempts to store the items in the $storehash, but only if they don't
9833: currently exist, if this succeeds you can be certain that you have
9834: successfully created a new key value pair in the $namespace db.
9835:
9836:
9837: Args:
9838: $namespace: name of database to store values to
9839: $storehash: hashref to store to the db
9840: $udom: (optional) domain of user containing the db
9841: $uname: (optional) name of user caontaining the db
9842:
9843: Returns:
9844: 'ok' -> succeeded in storing all keys of $storehash
9845: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9846: least <key> already existed in the db (other
9847: requested keys may also already exist)
1.967 bisitz 9848: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 9849: 'con_lost' -> unable to contact request server
9850: 'refused' -> action was not allowed by remote machine
9851:
9852:
9853: =item *
9854:
1.243 albertel 9855: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9856: reference filled in from namesp (encrypts the return communication)
9857: ($udom and $uname are optional)
1.191 harris41 9858:
9859: =item *
9860:
1.243 albertel 9861: log($udom,$name,$home,$message) : write to permanent log for user; use
9862: critical subroutine
9863:
1.806 raeburn 9864: =item *
9865:
1.860 raeburn 9866: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9867: array reference filled in from namespace found in domain level on either
9868: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9869:
9870: =item *
9871:
1.860 raeburn 9872: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9873: domain level either on specified domain server ($uhome) or primary domain
9874: server ($udom and $uhome are optional)
1.806 raeburn 9875:
1.943 raeburn 9876: =item *
9877:
9878: get_domain_defaults($target_domain) : returns hash with defaults for
9879: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9880: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9881: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9882: Values are retrieved from cache (if current), or from domain's configuration.db
9883: (if available), or lastly from values in lonTabs/dns_domain,tab,
9884: or lonTabs/domain.tab.
9885:
9886: %domdefaults = &get_auth_defaults($target_domain);
9887:
1.243 albertel 9888: =back
9889:
9890: =head2 Network Status Functions
9891:
9892: =over 4
1.191 harris41 9893:
9894: =item *
9895:
9896: dirlist($uri) : return directory list based on URI
9897:
9898: =item *
9899:
1.243 albertel 9900: spareserver() : find server with least workload from spare.tab
9901:
9902: =back
9903:
9904: =head2 Apache Request
9905:
9906: =over 4
1.191 harris41 9907:
9908: =item *
9909:
1.243 albertel 9910: ssi($url,%hash) : server side include, does a complete request cycle on url to
9911: localhost, posts hash
9912:
9913: =back
9914:
9915: =head2 Data to String to Data
9916:
9917: =over 4
1.191 harris41 9918:
9919: =item *
9920:
1.243 albertel 9921: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9922: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9923:
9924: =item *
9925:
1.243 albertel 9926: hashref2str($hashref) : convert a hashref into a string complete with
9927: escaping and '=' and '&' separators, supports elements that are
9928: arrayrefs and hashrefs
1.191 harris41 9929:
9930: =item *
9931:
1.243 albertel 9932: arrayref2str($arrayref) : convert an arrayref into a string complete
9933: with escaping and '&' separators, supports elements that are arrayrefs
9934: and hashrefs
1.191 harris41 9935:
9936: =item *
9937:
1.243 albertel 9938: str2hash($string) : convert string to hash using unescaping and
9939: splitting on '=' and '&', supports elements that are arrayrefs and
9940: hashrefs
1.191 harris41 9941:
9942: =item *
9943:
1.243 albertel 9944: str2array($string) : convert string to hash using unescaping and
9945: splitting on '&', supports elements that are arrayrefs and hashrefs
9946:
9947: =back
9948:
9949: =head2 Logging Routines
9950:
9951: =over 4
9952:
9953: These routines allow one to make log messages in the lonnet.log and
9954: lonnet.perm logfiles.
1.191 harris41 9955:
9956: =item *
9957:
1.243 albertel 9958: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9959:
9960: =item *
9961:
1.243 albertel 9962: logthis() : append message to the normal lonnet.log file, it gets
9963: preiodically rolled over and deleted.
1.191 harris41 9964:
9965: =item *
9966:
1.243 albertel 9967: logperm() : append a permanent message to lonnet.perm.log, this log
9968: file never gets deleted by any automated portion of the system, only
9969: messages of critical importance should go in here.
9970:
9971: =back
9972:
9973: =head2 General File Helper Routines
9974:
9975: =over 4
1.191 harris41 9976:
9977: =item *
9978:
1.481 raeburn 9979: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9980: (a) files in /uploaded
9981: (i) If a local copy of the file exists -
9982: compares modification date of local copy with last-modified date for
9983: definitive version stored on home server for course. If local copy is
9984: stale, requests a new version from the home server and stores it.
9985: If the original has been removed from the home server, then local copy
9986: is unlinked.
9987: (ii) If local copy does not exist -
9988: requests the file from the home server and stores it.
9989:
9990: If $caller is 'uploadrep':
9991: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9992: for request for files originally uploaded via DOCS.
9993: - returns 'ok' if fresh local copy now available, -1 otherwise.
9994:
9995: Otherwise:
9996: This indicates a call from the content generation phase of the request.
9997: - returns the entire contents of the file or -1.
9998:
9999: (b) files in /res
10000: - returns the entire contents of a file or -1;
10001: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 10002:
1.712 albertel 10003:
10004: =item *
10005:
10006: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10007: reference
10008:
10009: returns either a stat() list of data about the file or an empty list
10010: if the file doesn't exist or couldn't find out about it (connection
10011: problems or user unknown)
10012:
1.191 harris41 10013: =item *
10014:
1.243 albertel 10015: filelocation($dir,$file) : returns file system location of a file
10016: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10017: directory that relative $file lookups are to looked in ($dir of /a/dir
10018: and a file of ../bob will become /a/bob)
1.191 harris41 10019:
10020: =item *
10021:
10022: hreflocation($dir,$file) : returns file system location or a URL; same as
10023: filelocation except for hrefs
10024:
10025: =item *
10026:
10027: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10028:
1.243 albertel 10029: =back
10030:
1.608 albertel 10031: =head2 Usererfile file routines (/uploaded*)
10032:
10033: =over 4
10034:
10035: =item *
10036:
10037: userfileupload(): main rotine for putting a file in a user or course's
10038: filespace, arguments are,
10039:
1.620 albertel 10040: formname - required - this is the name of the element in $env where the
1.608 albertel 10041: filename, and the contents of the file to create/modifed exist
1.620 albertel 10042: the filename is in $env{'form.'.$formname.'.filename'} and the
10043: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10044: coursedoc - if true, store the file in the course of the active role
10045: of the current user
10046: subdir - required - subdirectory to put the file in under ../userfiles/
10047: if undefined, it will be placed in "unknown"
10048:
10049: (This routine calls clean_filename() to remove any dangerous
10050: characters from the filename, and then calls finuserfileupload() to
10051: complete the transaction)
10052:
10053: returns either the url of the uploaded file (/uploaded/....) if successful
10054: and /adm/notfound.html if unsuccessful
10055:
10056: =item *
10057:
10058: clean_filename(): routine for cleaing a filename up for storage in
10059: userfile space, argument is:
10060:
10061: filename - proposed filename
10062:
10063: returns: the new clean filename
10064:
10065: =item *
10066:
10067: finishuserfileupload(): routine that creaes and sends the file to
10068: userspace, probably shouldn't be called directly
10069:
10070: docuname: username or courseid of destination for the file
10071: docudom: domain of user/course of destination for the file
10072: formname: same as for userfileupload()
10073: fname: filename (inculding subdirectories) for the file
10074:
10075: returns either the url of the uploaded file (/uploaded/....) if successful
10076: and /adm/notfound.html if unsuccessful
10077:
10078: =item *
10079:
10080: renameuserfile(): renames an existing userfile to a new name
10081:
10082: Args:
10083: docuname: username or courseid of destination for the file
10084: docudom: domain of user/course of destination for the file
10085: old: current file name (including any subdirs under userfiles)
10086: new: desired file name (including any subdirs under userfiles)
10087:
10088: =item *
10089:
10090: mkdiruserfile(): creates a directory is a userfiles dir
10091:
10092: Args:
10093: docuname: username or courseid of destination for the file
10094: docudom: domain of user/course of destination for the file
10095: dir: dir to create (including any subdirs under userfiles)
10096:
10097: =item *
10098:
10099: removeuserfile(): removes a file that exists in userfiles
10100:
10101: Args:
10102: docuname: username or courseid of destination for the file
10103: docudom: domain of user/course of destination for the file
10104: fname: filname to delete (including any subdirs under userfiles)
10105:
10106: =item *
10107:
10108: removeuploadedurl(): convience function for removeuserfile()
10109:
10110: Args:
10111: url: a full /uploaded/... url to delete
10112:
1.747 albertel 10113: =item *
10114:
10115: get_portfile_permissions():
10116: Args:
10117: domain: domain of user or course contain the portfolio files
10118: user: name of user or num of course contain the portfolio files
10119: Returns:
10120: hashref of a dump of the proper file_permissions.db
10121:
10122:
10123: =item *
10124:
10125: get_access_controls():
10126:
10127: Args:
10128: current_permissions: the hash ref returned from get_portfile_permissions()
10129: group: (optional) the group you want the files associated with
10130: file: (optional) the file you want access info on
10131:
10132: Returns:
1.749 raeburn 10133: a hash (keys are file names) of hashes containing
10134: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10135: values are XML containing access control settings (see below)
1.747 albertel 10136:
10137: Internal notes:
10138:
1.749 raeburn 10139: access controls are stored in file_permissions.db as key=value pairs.
10140: key -> path to file/file_name\0uniqueID:scope_end_start
10141: where scope -> public,guest,course,group,domains or users.
10142: end -> UNIX time for end of access (0 -> no end date)
10143: start -> UNIX time for start of access
10144:
10145: value -> XML description of access control
10146: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10147: <start></start>
10148: <end></end>
10149:
10150: <password></password> for scope type = guest
10151:
10152: <domain></domain> for scope type = course or group
10153: <number></number>
10154: <roles id="">
10155: <role></role>
10156: <access></access>
10157: <section></section>
10158: <group></group>
10159: </roles>
10160:
10161: <dom></dom> for scope type = domains
10162:
10163: <users> for scope type = users
10164: <user>
10165: <uname></uname>
10166: <udom></udom>
10167: </user>
10168: </users>
10169: </scope>
10170:
10171: Access data is also aggregated for each file in an additional key=value pair:
10172: key -> path to file/file_name\0accesscontrol
10173: value -> reference to hash
10174: hash contains key = value pairs
10175: where key = uniqueID:scope_end_start
10176: value = UNIX time record was last updated
10177:
10178: Used to improve speed of look-ups of access controls for each file.
10179:
10180: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10181:
10182: modify_access_controls():
10183:
10184: Modifies access controls for a portfolio file
10185: Args
10186: 1. file name
10187: 2. reference to hash of required changes,
10188: 3. domain
10189: 4. username
10190: where domain,username are the domain of the portfolio owner
10191: (either a user or a course)
10192:
10193: Returns:
10194: 1. result of additions or updates ('ok' or 'error', with error message).
10195: 2. result of deletions ('ok' or 'error', with error message).
10196: 3. reference to hash of any new or updated access controls.
10197: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10198: key = integer (inbound ID)
10199: value = uniqueID
1.747 albertel 10200:
1.608 albertel 10201: =back
10202:
1.243 albertel 10203: =head2 HTTP Helper Routines
10204:
10205: =over 4
10206:
1.191 harris41 10207: =item *
10208:
10209: escape() : unpack non-word characters into CGI-compatible hex codes
10210:
10211: =item *
10212:
10213: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10214:
1.243 albertel 10215: =back
10216:
10217: =head1 PRIVATE SUBROUTINES
10218:
10219: =head2 Underlying communication routines (Shouldn't call)
10220:
10221: =over 4
10222:
10223: =item *
10224:
10225: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10226:
10227: =item *
10228:
10229: reply() : uses subreply to send a message to remote machine, logs all failures
10230:
10231: =item *
10232:
10233: critical() : passes a critical message to another server; if cannot
10234: get through then place message in connection buffer directory and
10235: returns con_delayed, if incapable of saving message, returns
10236: con_failed
10237:
10238: =item *
10239:
10240: reconlonc() : tries to reconnect lonc client processes.
10241:
10242: =back
10243:
10244: =head2 Resource Access Logging
10245:
10246: =over 4
10247:
10248: =item *
10249:
10250: flushcourselogs() : flush (save) buffer logs and access logs
10251:
10252: =item *
10253:
10254: courselog($what) : save message for course in hash
10255:
10256: =item *
10257:
10258: courseacclog($what) : save message for course using &courselog(). Perform
10259: special processing for specific resource types (problems, exams, quizzes, etc).
10260:
1.191 harris41 10261: =item *
10262:
10263: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10264: as a PerlChildExitHandler
1.243 albertel 10265:
10266: =back
10267:
10268: =head2 Other
10269:
10270: =over 4
10271:
10272: =item *
10273:
10274: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10275:
10276: =back
10277:
10278: =cut
1.877 foxr 10279:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>