Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.976.2.11
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.976.2.11! raeburn 4: # $Id: lonnet.pm,v 1.976.2.10 2009/10/09 12:42:36 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
76: # use Date::Parse;
1.871 albertel 77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968 raeburn 78: $_64bit %env %protocol);
1.871 albertel 79:
80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
81: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
82: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 83: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 84:
1.1 albertel 85: use IO::Socket;
1.31 www 86: use GDBM_File;
1.208 albertel 87: use HTML::LCParser;
1.88 www 88: use Fcntl qw(:flock);
1.870 albertel 89: use Storable qw(thaw nfreeze);
1.539 albertel 90: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 91: use Cache::Memcached;
1.676 albertel 92: use Digest::MD5;
1.790 albertel 93: use Math::Random;
1.807 albertel 94: use LONCAPA qw(:DEFAULT :match);
1.740 www 95: use LONCAPA::Configuration;
1.676 albertel 96:
1.195 www 97: my $readit;
1.550 foxr 98: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 99:
1.619 albertel 100: require Exporter;
101:
102: our @ISA = qw (Exporter);
103: our @EXPORT = qw(%env);
104:
1.449 matthew 105:
1.1 albertel 106: # --------------------------------------------------------------------- Logging
1.729 www 107: {
108: my $logid;
109: sub instructor_log {
1.957 raeburn 110: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
111: if (($cnum eq '') || ($cdom eq '')) {
112: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
113: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
114: }
1.729 www 115: $logid++;
1.957 raeburn 116: my $now = time();
117: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 118: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 119: { $id => {
120: 'exe_uname' => $env{'user.name'},
121: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 122: 'exe_time' => $now,
1.730 www 123: 'exe_ip' => $ENV{'REMOTE_ADDR'},
124: 'delflag' => $delflag,
125: 'logentry' => $storehash,
126: 'uname' => $uname,
127: 'udom' => $udom,
128: }
1.957 raeburn 129: },$cdom,$cnum);
1.729 www 130: }
131: }
1.1 albertel 132:
1.163 harris41 133: sub logtouch {
134: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 135: unless (-e "$execdir/logs/lonnet.log") {
136: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 137: close $fh;
138: }
139: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
140: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
141: }
142:
1.1 albertel 143: sub logthis {
144: my $message=shift;
145: my $execdir=$perlvar{'lonDaemons'};
146: my $now=time;
147: my $local=localtime($now);
1.448 albertel 148: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
149: print $fh "$local ($$): $message\n";
150: close($fh);
151: }
1.1 albertel 152: return 1;
153: }
154:
155: sub logperm {
156: my $message=shift;
157: my $execdir=$perlvar{'lonDaemons'};
158: my $now=time;
159: my $local=localtime($now);
1.448 albertel 160: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
161: print $fh "$now:$message:$local\n";
162: close($fh);
163: }
1.1 albertel 164: return 1;
165: }
166:
1.850 albertel 167: sub create_connection {
1.853 albertel 168: my ($hostname,$lonid) = @_;
1.851 albertel 169: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 170: Type => SOCK_STREAM,
171: Timeout => 10);
172: return 0 if (!$client);
1.890 albertel 173: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 174: my $result = <$client>;
175: chomp($result);
176: return 1 if ($result eq 'done');
177: return 0;
178: }
179:
1.976.2.6 raeburn 180: sub get_server_timezone {
181: my ($cnum,$cdom) = @_;
182: my $home=&homeserver($cnum,$cdom);
183: if ($home ne 'no_host') {
184: my $cachetime = 24*3600;
185: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
186: if (defined($cached)) {
187: return $timezone;
188: } else {
189: my $timezone = &reply('servertimezone',$home);
190: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
191: }
192: }
193: }
1.850 albertel 194:
1.1 albertel 195: # -------------------------------------------------- Non-critical communication
196: sub subreply {
197: my ($cmd,$server)=@_;
1.838 albertel 198: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 199: #
200: # With loncnew process trimming, there's a timing hole between lonc server
201: # process exit and the master server picking up the listen on the AF_UNIX
202: # socket. In that time interval, a lock file will exist:
203:
204: my $lockfile=$peerfile.".lock";
205: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
206: sleep(1);
207: }
208: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 209: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 210: #
1.550 foxr 211: # We'll give the connection a few tries before abandoning it. If
212: # connection is not possible, we'll con_lost back to the client.
213: #
214: my $client;
215: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
216: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
217: Type => SOCK_STREAM,
218: Timeout => 10);
1.869 albertel 219: if ($client) {
1.550 foxr 220: last; # Connected!
1.850 albertel 221: } else {
1.853 albertel 222: &create_connection(&hostname($server),$server);
1.550 foxr 223: }
1.850 albertel 224: sleep(1); # Try again later if failed connection.
1.550 foxr 225: }
226: my $answer;
227: if ($client) {
1.704 albertel 228: print $client "sethost:$server:$cmd\n";
1.550 foxr 229: $answer=<$client>;
230: if (!$answer) { $answer="con_lost"; }
231: chomp($answer);
232: } else {
233: $answer = 'con_lost'; # Failed connection.
234: }
1.1 albertel 235: return $answer;
236: }
237:
238: sub reply {
239: my ($cmd,$server)=@_;
1.838 albertel 240: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 241: my $answer=subreply($cmd,$server);
1.65 www 242: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 243: &logthis("<font color=\"blue\">WARNING:".
1.12 www 244: " $cmd to $server returned $answer</font>");
245: }
1.1 albertel 246: return $answer;
247: }
248:
249: # ----------------------------------------------------------- Send USR1 to lonc
250:
251: sub reconlonc {
1.891 albertel 252: my ($lonid) = @_;
253: my $hostname = &hostname($lonid);
254: if ($lonid) {
255: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
256: if ($hostname && -e $peerfile) {
257: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
258: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
259: Type => SOCK_STREAM,
260: Timeout => 10);
261: if ($client) {
262: print $client ("reset_retries\n");
263: my $answer=<$client>;
264: #reset just this one.
265: }
266: }
267: return;
268: }
269:
1.836 www 270: &logthis("Trying to reconnect lonc");
1.1 albertel 271: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 272: if (open(my $fh,"<$loncfile")) {
1.1 albertel 273: my $loncpid=<$fh>;
274: chomp($loncpid);
275: if (kill 0 => $loncpid) {
276: &logthis("lonc at pid $loncpid responding, sending USR1");
277: kill USR1 => $loncpid;
278: sleep 1;
1.836 www 279: } else {
1.12 www 280: &logthis(
1.672 albertel 281: "<font color=\"blue\">WARNING:".
1.12 www 282: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 283: }
284: } else {
1.836 www 285: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 286: }
287: }
288:
289: # ------------------------------------------------------ Critical communication
1.12 www 290:
1.1 albertel 291: sub critical {
292: my ($cmd,$server)=@_;
1.838 albertel 293: unless (&hostname($server)) {
1.672 albertel 294: &logthis("<font color=\"blue\">WARNING:".
1.89 www 295: " Critical message to unknown server ($server)</font>");
296: return 'no_such_host';
297: }
1.1 albertel 298: my $answer=reply($cmd,$server);
299: if ($answer eq 'con_lost') {
300: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 301: my $answer=reply($cmd,$server);
1.1 albertel 302: if ($answer eq 'con_lost') {
303: my $now=time;
304: my $middlename=$cmd;
1.5 www 305: $middlename=substr($middlename,0,16);
1.1 albertel 306: $middlename=~s/\W//g;
307: my $dfilename=
1.305 www 308: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
309: $dumpcount++;
1.1 albertel 310: {
1.448 albertel 311: my $dfh;
312: if (open($dfh,">$dfilename")) {
313: print $dfh "$cmd\n";
314: close($dfh);
315: }
1.1 albertel 316: }
317: sleep 2;
318: my $wcmd='';
319: {
1.448 albertel 320: my $dfh;
321: if (open($dfh,"<$dfilename")) {
322: $wcmd=<$dfh>;
323: close($dfh);
324: }
1.1 albertel 325: }
326: chomp($wcmd);
1.7 www 327: if ($wcmd eq $cmd) {
1.672 albertel 328: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 329: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 330: &logperm("D:$server:$cmd");
331: return 'con_delayed';
332: } else {
1.672 albertel 333: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 334: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 335: &logperm("F:$server:$cmd");
336: return 'con_failed';
337: }
338: }
339: }
340: return $answer;
1.405 albertel 341: }
342:
1.755 albertel 343: # ------------------------------------------- check if return value is an error
344:
345: sub error {
346: my ($result) = @_;
1.756 albertel 347: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 348: if ($2 == 2) { return undef; }
349: return $1;
350: }
351: return undef;
352: }
353:
1.783 albertel 354: sub convert_and_load_session_env {
355: my ($lonidsdir,$handle)=@_;
356: my @profile;
357: {
1.917 albertel 358: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
359: if (!$opened) {
1.915 albertel 360: return 0;
361: }
1.783 albertel 362: flock($idf,LOCK_SH);
363: @profile=<$idf>;
364: close($idf);
365: }
366: my %temp_env;
367: foreach my $line (@profile) {
1.786 albertel 368: if ($line !~ m/=/) {
369: return 0;
370: }
1.783 albertel 371: chomp($line);
372: my ($envname,$envvalue)=split(/=/,$line,2);
373: $temp_env{&unescape($envname)} = &unescape($envvalue);
374: }
375: unlink("$lonidsdir/$handle.id");
376: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
377: 0640)) {
378: %disk_env = %temp_env;
379: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
380: untie(%disk_env);
381: }
1.786 albertel 382: return 1;
1.783 albertel 383: }
384:
1.374 www 385: # ------------------------------------------- Transfer profile into environment
1.780 albertel 386: my $env_loaded;
387: sub transfer_profile_to_env {
1.788 albertel 388: my ($lonidsdir,$handle,$force_transfer) = @_;
389: if (!$force_transfer && $env_loaded) { return; }
1.374 www 390:
1.720 albertel 391: if (!defined($lonidsdir)) {
392: $lonidsdir = $perlvar{'lonIDsDir'};
393: }
394: if (!defined($handle)) {
395: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
396: }
397:
1.786 albertel 398: my $convert;
399: {
1.917 albertel 400: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
401: if (!$opened) {
1.915 albertel 402: return;
403: }
1.786 albertel 404: flock($idf,LOCK_SH);
405: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
406: &GDBM_READER(),0640)) {
407: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
408: untie(%disk_env);
409: } else {
410: $convert = 1;
411: }
412: }
413: if ($convert) {
414: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
415: &logthis("Failed to load session, or convert session.");
416: }
1.374 www 417: }
1.783 albertel 418:
1.786 albertel 419: my %remove;
1.783 albertel 420: while ( my $envname = each(%env) ) {
1.433 matthew 421: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
422: if ($time < time-300) {
1.783 albertel 423: $remove{$key}++;
1.433 matthew 424: }
425: }
426: }
1.783 albertel 427:
1.619 albertel 428: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 429: $env_loaded=1;
1.783 albertel 430: foreach my $expired_key (keys(%remove)) {
1.433 matthew 431: &delenv($expired_key);
1.374 www 432: }
1.1 albertel 433: }
434:
1.916 albertel 435: # ---------------------------------------------------- Check for valid session
436: sub check_for_valid_session {
437: my ($r) = @_;
438: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
439: my $lonid=$cookies{'lonID'};
440: return undef if (!$lonid);
441:
442: my $handle=&LONCAPA::clean_handle($lonid->value);
443: my $lonidsdir=$r->dir_config('lonIDsDir');
444: return undef if (!-e "$lonidsdir/$handle.id");
445:
1.917 albertel 446: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
447: return undef if (!$opened);
1.916 albertel 448:
449: flock($idf,LOCK_SH);
450: my %disk_env;
451: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
452: &GDBM_READER(),0640)) {
453: return undef;
454: }
455:
456: if (!defined($disk_env{'user.name'})
457: || !defined($disk_env{'user.domain'})) {
458: return undef;
459: }
460: return $handle;
461: }
462:
1.830 albertel 463: sub timed_flock {
464: my ($file,$lock_type) = @_;
465: my $failed=0;
466: eval {
467: local $SIG{__DIE__}='DEFAULT';
468: local $SIG{ALRM}=sub {
469: $failed=1;
470: die("failed lock");
471: };
472: alarm(13);
473: flock($file,$lock_type);
474: alarm(0);
475: };
476: if ($failed) {
477: return undef;
478: } else {
479: return 1;
480: }
481: }
482:
1.5 www 483: # ---------------------------------------------------------- Append Environment
484:
485: sub appenv {
1.949 raeburn 486: my ($newenv,$roles) = @_;
487: if (ref($newenv) eq 'HASH') {
488: foreach my $key (keys(%{$newenv})) {
489: my $refused = 0;
490: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
491: $refused = 1;
492: if (ref($roles) eq 'ARRAY') {
493: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
494: if (grep(/^\Q$role\E$/,@{$roles})) {
495: $refused = 0;
496: }
497: }
498: }
499: if ($refused) {
500: &logthis("<font color=\"blue\">WARNING: ".
501: "Attempt to modify environment ".$key." to ".$newenv->{$key}
502: .'</font>');
503: delete($newenv->{$key});
504: } else {
505: $env{$key}=$newenv->{$key};
506: }
507: }
508: my $opened = open(my $env_file,'+<',$env{'user.environment'});
509: if ($opened
510: && &timed_flock($env_file,LOCK_EX)
511: &&
512: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
513: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
514: while (my ($key,$value) = each(%{$newenv})) {
515: $disk_env{$key} = $value;
516: }
517: untie(%disk_env);
1.35 www 518: }
1.191 harris41 519: }
1.56 www 520: return 'ok';
521: }
522: # ----------------------------------------------------- Delete from Environment
523:
524: sub delenv {
1.976.2.7 raeburn 525: my ($delthis,$regexp) = @_;
1.56 www 526: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 527: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 528: "Attempt to delete from environment ".$delthis);
529: return 'error';
530: }
1.917 albertel 531: my $opened = open(my $env_file,'+<',$env{'user.environment'});
532: if ($opened
1.915 albertel 533: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 534: &&
535: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
536: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 537: foreach my $key (keys(%disk_env)) {
1.976.2.7 raeburn 538: if ($regexp) {
539: if ($key=~/^$delthis/) {
540: delete($env{$key});
541: delete($disk_env{$key});
542: }
543: } else {
544: if ($key=~/^\Q$delthis\E/) {
545: delete($env{$key});
546: delete($disk_env{$key});
547: }
548: }
1.448 albertel 549: }
1.783 albertel 550: untie(%disk_env);
1.5 www 551: }
552: return 'ok';
1.369 albertel 553: }
554:
1.790 albertel 555: sub get_env_multiple {
556: my ($name) = @_;
557: my @values;
558: if (defined($env{$name})) {
559: # exists is it an array
560: if (ref($env{$name})) {
561: @values=@{ $env{$name} };
562: } else {
563: $values[0]=$env{$name};
564: }
565: }
566: return(@values);
567: }
568:
1.958 www 569: # ------------------------------------------------------------------- Locking
570:
571: sub set_lock {
572: my ($text)=@_;
573: $locknum++;
574: my $id=$$.'-'.$locknum;
575: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
576: 'session.lock.'.$id => $text});
577: return $id;
578: }
579:
580: sub get_locks {
581: my $num=0;
582: my %texts=();
583: foreach my $lock (split(/\,/,$env{'session.locks'})) {
584: if ($lock=~/\w/) {
585: $num++;
586: $texts{$lock}=$env{'session.lock.'.$lock};
587: }
588: }
589: return ($num,%texts);
590: }
591:
592: sub remove_lock {
593: my ($id)=@_;
594: my $newlocks='';
595: foreach my $lock (split(/\,/,$env{'session.locks'})) {
596: if (($lock=~/\w/) && ($lock ne $id)) {
597: $newlocks.=','.$lock;
598: }
599: }
600: &appenv({'session.locks' => $newlocks});
601: &delenv('session.lock.'.$id);
602: }
603:
604: sub remove_all_locks {
605: my $activelocks=$env{'session.locks'};
606: foreach my $lock (split(/\,/,$env{'session.locks'})) {
607: if ($lock=~/\w/) {
608: &remove_lock($lock);
609: }
610: }
611: }
612:
613:
1.369 albertel 614: # ------------------------------------------ Find out current server userload
615: sub userload {
616: my $numusers=0;
617: {
618: opendir(LONIDS,$perlvar{'lonIDsDir'});
619: my $filename;
620: my $curtime=time;
621: while ($filename=readdir(LONIDS)) {
1.925 albertel 622: next if ($filename eq '.' || $filename eq '..');
623: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 624: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 625: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 626: }
627: closedir(LONIDS);
628: }
629: my $userloadpercent=0;
630: my $maxuserload=$perlvar{'lonUserLoadLim'};
631: if ($maxuserload) {
1.371 albertel 632: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 633: }
1.372 albertel 634: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 635: return $userloadpercent;
1.283 www 636: }
637:
638: # ------------------------------------------ Fight off request when overloaded
639:
640: sub overloaderror {
641: my ($r,$checkserver)=@_;
642: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
643: my $loadavg;
644: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 645: open(my $loadfile,'/proc/loadavg');
1.283 www 646: $loadavg=<$loadfile>;
647: $loadavg =~ s/\s.*//g;
1.285 matthew 648: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 649: close($loadfile);
1.283 www 650: } else {
651: $loadavg=&reply('load',$checkserver);
652: }
1.285 matthew 653: my $overload=$loadavg-100;
1.283 www 654: if ($overload>0) {
1.285 matthew 655: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 656: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 657: return 413;
1.283 www 658: }
659: return '';
1.5 www 660: }
1.1 albertel 661:
662: # ------------------------------ Find server with least workload from spare.tab
1.11 www 663:
1.1 albertel 664: sub spareserver {
1.670 albertel 665: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 666: my $spare_server;
1.370 albertel 667: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 668: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
669: : $userloadpercent;
670:
671: foreach my $try_server (@{ $spareid{'primary'} }) {
672: ($spare_server, $lowest_load) =
673: &compare_server_load($try_server, $spare_server, $lowest_load);
674: }
675:
676: my $found_server = ($spare_server ne '' && $lowest_load < 100);
677:
678: if (!$found_server) {
679: foreach my $try_server (@{ $spareid{'default'} }) {
680: ($spare_server, $lowest_load) =
681: &compare_server_load($try_server, $spare_server, $lowest_load);
682: }
683: }
684:
685: if (!$want_server_name) {
1.968 raeburn 686: my $protocol = 'http';
687: if ($protocol{$spare_server} eq 'https') {
688: $protocol = $protocol{$spare_server};
689: }
690: $spare_server = $protocol.'://'.&hostname($spare_server);
1.784 albertel 691: }
692: return $spare_server;
693: }
694:
695: sub compare_server_load {
696: my ($try_server, $spare_server, $lowest_load) = @_;
697:
698: my $loadans = &reply('load', $try_server);
699: my $userloadans = &reply('userload',$try_server);
700:
701: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
702: next; #didn't get a number from the server
703: }
704:
705: my $load;
706: if ($loadans =~ /\d/) {
707: if ($userloadans =~ /\d/) {
708: #both are numbers, pick the bigger one
709: $load = ($loadans > $userloadans) ? $loadans
710: : $userloadans;
1.411 albertel 711: } else {
1.784 albertel 712: $load = $loadans;
1.411 albertel 713: }
1.784 albertel 714: } else {
715: $load = $userloadans;
716: }
717:
718: if (($load =~ /\d/) && ($load < $lowest_load)) {
719: $spare_server = $try_server;
720: $lowest_load = $load;
1.370 albertel 721: }
1.784 albertel 722: return ($spare_server,$lowest_load);
1.202 matthew 723: }
1.914 albertel 724:
725: # --------------------------- ask offload servers if user already has a session
726: sub find_existing_session {
727: my ($udom,$uname) = @_;
728: foreach my $try_server (@{ $spareid{'primary'} },
729: @{ $spareid{'default'} }) {
730: return $try_server if (&has_user_session($try_server, $udom, $uname));
731: }
732: return;
733: }
734:
735: # -------------------------------- ask if server already has a session for user
736: sub has_user_session {
737: my ($lonid,$udom,$uname) = @_;
738: my $result = &reply(join(':','userhassession',
739: map {&escape($_)} ($udom,$uname)),$lonid);
740: return 1 if ($result eq 'ok');
741:
742: return 0;
743: }
744:
1.202 matthew 745: # --------------------------------------------- Try to change a user's password
746:
747: sub changepass {
1.799 raeburn 748: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 749: $currentpass = &escape($currentpass);
750: $newpass = &escape($newpass);
1.976.2.10 raeburn 751: my $lonhost = $perlvar{'lonHostID'};
752: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 753: $server);
754: if (! $answer) {
755: &logthis("No reply on password change request to $server ".
756: "by $uname in domain $udom.");
757: } elsif ($answer =~ "^ok") {
758: &logthis("$uname in $udom successfully changed their password ".
759: "on $server.");
760: } elsif ($answer =~ "^pwchange_failure") {
761: &logthis("$uname in $udom was unable to change their password ".
762: "on $server. The action was blocked by either lcpasswd ".
763: "or pwchange");
764: } elsif ($answer =~ "^non_authorized") {
765: &logthis("$uname in $udom did not get their password correct when ".
766: "attempting to change it on $server.");
767: } elsif ($answer =~ "^auth_mode_error") {
768: &logthis("$uname in $udom attempted to change their password despite ".
769: "not being locally or internally authenticated on $server.");
770: } elsif ($answer =~ "^unknown_user") {
771: &logthis("$uname in $udom attempted to change their password ".
772: "on $server but were unable to because $server is not ".
773: "their home server.");
774: } elsif ($answer =~ "^refused") {
775: &logthis("$server refused to change $uname in $udom password because ".
776: "it was sent an unencrypted request to change the password.");
1.976.2.10 raeburn 777: } elsif ($answer =~ "invalid_client") {
778: &logthis("$server refused to change $uname in $udom password because ".
779: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 780: }
781: return $answer;
1.1 albertel 782: }
783:
1.169 harris41 784: # ----------------------- Try to determine user's current authentication scheme
785:
786: sub queryauthenticate {
787: my ($uname,$udom)=@_;
1.456 albertel 788: my $uhome=&homeserver($uname,$udom);
789: if (!$uhome) {
790: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
791: return 'no_host';
792: }
793: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
794: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
795: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 796: }
1.456 albertel 797: return $answer;
1.169 harris41 798: }
799:
1.1 albertel 800: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 801:
1.1 albertel 802: sub authenticate {
1.952 raeburn 803: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 804: $upass=&escape($upass);
805: $uname= &LONCAPA::clean_username($uname);
1.836 www 806: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 807: my $newhome;
1.836 www 808: if ((!$uhome) || ($uhome eq 'no_host')) {
809: # Maybe the machine was offline and only re-appeared again recently?
810: &reconlonc();
811: # One more
1.952 raeburn 812: $uhome=&homeserver($uname,$udom,1);
813: if (($uhome eq 'no_host') && $checkdefauth) {
814: if (defined(&domain($udom,'primary'))) {
815: $newhome=&domain($udom,'primary');
816: }
817: if ($newhome ne '') {
818: $uhome = $newhome;
819: }
820: }
1.836 www 821: if ((!$uhome) || ($uhome eq 'no_host')) {
822: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 823: return 'no_host';
824: }
1.1 albertel 825: }
1.952 raeburn 826: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 827: if ($answer eq 'authorized') {
1.952 raeburn 828: if ($newhome) {
829: &logthis("User $uname at $udom authorized by $uhome, but needs account");
830: return 'no_account_on_host';
831: } else {
832: &logthis("User $uname at $udom authorized by $uhome");
833: return $uhome;
834: }
1.471 albertel 835: }
836: if ($answer eq 'non_authorized') {
837: &logthis("User $uname at $udom rejected by $uhome");
838: return 'no_host';
1.9 www 839: }
1.471 albertel 840: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 841: return 'no_host';
842: }
843:
844: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 845:
1.599 albertel 846: my %homecache;
1.1 albertel 847: sub homeserver {
1.230 stredwic 848: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 849: my $index="$uname:$udom";
1.426 albertel 850:
1.599 albertel 851: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 852:
853: my %servers = &get_servers($udom,'library');
854: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 855: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 856: exists($badServerCache{$tryserver}));
1.841 albertel 857:
858: my $answer=reply("home:$udom:$uname",$tryserver);
859: if ($answer eq 'found') {
860: delete($badServerCache{$tryserver});
861: return $homecache{$index}=$tryserver;
862: } elsif ($answer eq 'no_host') {
863: $badServerCache{$tryserver}=1;
864: }
1.1 albertel 865: }
866: return 'no_host';
1.70 www 867: }
868:
869: # ------------------------------------- Find the usernames behind a list of IDs
870:
871: sub idget {
872: my ($udom,@ids)=@_;
873: my %returnhash=();
874:
1.841 albertel 875: my %servers = &get_servers($udom,'library');
876: foreach my $tryserver (keys(%servers)) {
877: my $idlist=join('&',@ids);
878: $idlist=~tr/A-Z/a-z/;
879: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
880: my @answer=();
881: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
882: @answer=split(/\&/,$reply);
883: } ;
884: my $i;
885: for ($i=0;$i<=$#ids;$i++) {
886: if ($answer[$i]) {
887: $returnhash{$ids[$i]}=$answer[$i];
888: }
889: }
890: }
1.70 www 891: return %returnhash;
892: }
893:
894: # ------------------------------------- Find the IDs behind a list of usernames
895:
896: sub idrget {
897: my ($udom,@unames)=@_;
898: my %returnhash=();
1.800 albertel 899: foreach my $uname (@unames) {
900: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 901: }
1.70 www 902: return %returnhash;
903: }
904:
905: # ------------------------------- Store away a list of names and associated IDs
906:
907: sub idput {
908: my ($udom,%ids)=@_;
909: my %servers=();
1.800 albertel 910: foreach my $uname (keys(%ids)) {
911: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
912: my $uhom=&homeserver($uname,$udom);
1.70 www 913: if ($uhom ne 'no_host') {
1.800 albertel 914: my $id=&escape($ids{$uname});
1.70 www 915: $id=~tr/A-Z/a-z/;
1.800 albertel 916: my $esc_unam=&escape($uname);
1.70 www 917: if ($servers{$uhom}) {
1.800 albertel 918: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 919: } else {
1.800 albertel 920: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 921: }
922: }
1.191 harris41 923: }
1.800 albertel 924: foreach my $server (keys(%servers)) {
925: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 926: }
1.344 www 927: }
928:
1.806 raeburn 929: # ------------------------------------------- get items from domain db files
930:
931: sub get_dom {
1.860 raeburn 932: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 933: my $items='';
934: foreach my $item (@$storearr) {
935: $items.=&escape($item).'&';
936: }
937: $items=~s/\&$//;
1.860 raeburn 938: if (!$udom) {
939: $udom=$env{'user.domain'};
940: if (defined(&domain($udom,'primary'))) {
941: $uhome=&domain($udom,'primary');
942: } else {
1.874 albertel 943: undef($uhome);
1.860 raeburn 944: }
945: } else {
946: if (!$uhome) {
947: if (defined(&domain($udom,'primary'))) {
948: $uhome=&domain($udom,'primary');
949: }
950: }
951: }
952: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 953: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 954: my %returnhash;
1.875 albertel 955: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 956: return %returnhash;
957: }
1.806 raeburn 958: my @pairs=split(/\&/,$rep);
959: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
960: return @pairs;
961: }
962: my $i=0;
963: foreach my $item (@$storearr) {
964: $returnhash{$item}=&thaw_unescape($pairs[$i]);
965: $i++;
966: }
967: return %returnhash;
968: } else {
1.880 banghart 969: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 970: }
971: }
972:
973: # -------------------------------------------- put items in domain db files
974:
975: sub put_dom {
1.860 raeburn 976: my ($namespace,$storehash,$udom,$uhome)=@_;
977: if (!$udom) {
978: $udom=$env{'user.domain'};
979: if (defined(&domain($udom,'primary'))) {
980: $uhome=&domain($udom,'primary');
981: } else {
1.874 albertel 982: undef($uhome);
1.860 raeburn 983: }
984: } else {
985: if (!$uhome) {
986: if (defined(&domain($udom,'primary'))) {
987: $uhome=&domain($udom,'primary');
988: }
989: }
990: }
991: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 992: my $items='';
993: foreach my $item (keys(%$storehash)) {
994: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
995: }
996: $items=~s/\&$//;
997: return &reply("putdom:$udom:$namespace:$items",$uhome);
998: } else {
1.860 raeburn 999: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1000: }
1001: }
1002:
1.837 raeburn 1003: sub retrieve_inst_usertypes {
1004: my ($udom) = @_;
1005: my (%returnhash,@order);
1.846 albertel 1006: if (defined(&domain($udom,'primary'))) {
1007: my $uhome=&domain($udom,'primary');
1.837 raeburn 1008: my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960 raeburn 1009: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1010: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1011: return (\%returnhash,\@order);
1012: }
1.837 raeburn 1013: my ($hashitems,$orderitems) = split(/:/,$rep);
1014: my @pairs=split(/\&/,$hashitems);
1015: foreach my $item (@pairs) {
1016: my ($key,$value)=split(/=/,$item,2);
1017: $key = &unescape($key);
1018: next if ($key =~ /^error: 2 /);
1019: $returnhash{$key}=&thaw_unescape($value);
1020: }
1021: my @esc_order = split(/\&/,$orderitems);
1022: foreach my $item (@esc_order) {
1023: push(@order,&unescape($item));
1024: }
1025: } else {
1026: &logthis("get_dom failed - no primary domain server for $udom");
1027: }
1028: return (\%returnhash,\@order);
1029: }
1030:
1.868 raeburn 1031: sub is_domainimage {
1032: my ($url) = @_;
1033: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1034: if (&domain($1) ne '') {
1035: return '1';
1036: }
1037: }
1038: return;
1039: }
1040:
1.899 raeburn 1041: sub inst_directory_query {
1042: my ($srch) = @_;
1043: my $udom = $srch->{'srchdomain'};
1044: my %results;
1045: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1046: my $outcome;
1.899 raeburn 1047: if ($homeserver ne '') {
1.904 albertel 1048: my $queryid=&reply("querysend:instdirsearch:".
1049: &escape($srch->{'srchby'}).':'.
1050: &escape($srch->{'srchterm'}).':'.
1051: &escape($srch->{'srchtype'}),$homeserver);
1052: my $host=&hostname($homeserver);
1053: if ($queryid !~/^\Q$host\E\_/) {
1054: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1055: return;
1056: }
1057: my $response = &get_query_reply($queryid);
1058: my $maxtries = 5;
1059: my $tries = 1;
1060: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1061: $response = &get_query_reply($queryid);
1062: $tries ++;
1063: }
1064:
1065: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1066: if ($response eq 'unavailable') {
1067: $outcome = $response;
1068: } else {
1069: $outcome = 'ok';
1070: my @matches = split(/\n/,$response);
1071: foreach my $match (@matches) {
1072: my ($key,$value) = split(/=/,$match);
1073: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1074: }
1.899 raeburn 1075: }
1076: }
1077: }
1.909 raeburn 1078: return ($outcome,%results);
1.899 raeburn 1079: }
1080:
1081: sub usersearch {
1082: my ($srch) = @_;
1083: my $dom = $srch->{'srchdomain'};
1084: my %results;
1085: my %libserv = &all_library();
1086: my $query = 'usersearch';
1087: foreach my $tryserver (keys(%libserv)) {
1088: if (&host_domain($tryserver) eq $dom) {
1089: my $host=&hostname($tryserver);
1090: my $queryid=
1.911 raeburn 1091: &reply("querysend:".&escape($query).':'.
1092: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1093: &escape($srch->{'srchtype'}).':'.
1094: &escape($srch->{'srchterm'}),$tryserver);
1095: if ($queryid !~/^\Q$host\E\_/) {
1096: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1097: next;
1.899 raeburn 1098: }
1099: my $reply = &get_query_reply($queryid);
1100: my $maxtries = 1;
1101: my $tries = 1;
1102: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1103: $reply = &get_query_reply($queryid);
1104: $tries ++;
1105: }
1106: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1107: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1108: } else {
1.911 raeburn 1109: my @matches;
1110: if ($reply =~ /\n/) {
1111: @matches = split(/\n/,$reply);
1112: } else {
1113: @matches = split(/\&/,$reply);
1114: }
1.899 raeburn 1115: foreach my $match (@matches) {
1116: my ($uname,$udom,%userhash);
1.911 raeburn 1117: foreach my $entry (split(/:/,$match)) {
1118: my ($key,$value) =
1119: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1120: $userhash{$key} = $value;
1121: if ($key eq 'username') {
1122: $uname = $value;
1123: } elsif ($key eq 'domain') {
1124: $udom = $value;
1.911 raeburn 1125: }
1.899 raeburn 1126: }
1127: $results{$uname.':'.$udom} = \%userhash;
1128: }
1129: }
1130: }
1131: }
1132: return %results;
1133: }
1134:
1.912 raeburn 1135: sub get_instuser {
1136: my ($udom,$uname,$id) = @_;
1137: my $homeserver = &domain($udom,'primary');
1138: my ($outcome,%results);
1139: if ($homeserver ne '') {
1140: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1141: &escape($id).':'.&escape($udom),$homeserver);
1142: my $host=&hostname($homeserver);
1143: if ($queryid !~/^\Q$host\E\_/) {
1144: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1145: return;
1146: }
1147: my $response = &get_query_reply($queryid);
1148: my $maxtries = 5;
1149: my $tries = 1;
1150: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1151: $response = &get_query_reply($queryid);
1152: $tries ++;
1153: }
1154: if (!&error($response) && $response ne 'refused') {
1155: if ($response eq 'unavailable') {
1156: $outcome = $response;
1157: } else {
1158: $outcome = 'ok';
1159: my @matches = split(/\n/,$response);
1160: foreach my $match (@matches) {
1161: my ($key,$value) = split(/=/,$match);
1162: $results{&unescape($key)} = &thaw_unescape($value);
1163: }
1164: }
1165: }
1166: }
1167: my %userinfo;
1168: if (ref($results{$uname}) eq 'HASH') {
1169: %userinfo = %{$results{$uname}};
1170: }
1171: return ($outcome,%userinfo);
1172: }
1173:
1174: sub inst_rulecheck {
1.923 raeburn 1175: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1176: my %returnhash;
1177: if ($udom ne '') {
1178: if (ref($rules) eq 'ARRAY') {
1179: @{$rules} = map {&escape($_);} (@{$rules});
1180: my $rulestr = join(':',@{$rules});
1181: my $homeserver=&domain($udom,'primary');
1182: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1183: my $response;
1184: if ($item eq 'username') {
1185: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1186: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1187: $homeserver));
1.923 raeburn 1188: } elsif ($item eq 'id') {
1189: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1190: ':'.&escape($id).':'.$rulestr,
1191: $homeserver));
1.945 raeburn 1192: } elsif ($item eq 'selfcreate') {
1193: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1194: &escape($udom).':'.&escape($uname).
1195: ':'.$rulestr,$homeserver));
1.923 raeburn 1196: }
1.912 raeburn 1197: if ($response ne 'refused') {
1198: my @pairs=split(/\&/,$response);
1199: foreach my $item (@pairs) {
1200: my ($key,$value)=split(/=/,$item,2);
1201: $key = &unescape($key);
1202: next if ($key =~ /^error: 2 /);
1203: $returnhash{$key}=&thaw_unescape($value);
1204: }
1205: }
1206: }
1207: }
1208: }
1209: return %returnhash;
1210: }
1211:
1212: sub inst_userrules {
1.923 raeburn 1213: my ($udom,$check) = @_;
1.912 raeburn 1214: my (%ruleshash,@ruleorder);
1215: if ($udom ne '') {
1216: my $homeserver=&domain($udom,'primary');
1217: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1218: my $response;
1219: if ($check eq 'id') {
1220: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1221: $homeserver);
1.943 raeburn 1222: } elsif ($check eq 'email') {
1223: $response=&reply('instemailrules:'.&escape($udom),
1224: $homeserver);
1.923 raeburn 1225: } else {
1226: $response=&reply('instuserrules:'.&escape($udom),
1227: $homeserver);
1228: }
1.912 raeburn 1229: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1230: ($response ne 'unknown_cmd') &&
1.912 raeburn 1231: ($response ne 'no_such_host')) {
1232: my ($hashitems,$orderitems) = split(/:/,$response);
1233: my @pairs=split(/\&/,$hashitems);
1234: foreach my $item (@pairs) {
1235: my ($key,$value)=split(/=/,$item,2);
1236: $key = &unescape($key);
1237: next if ($key =~ /^error: 2 /);
1238: $ruleshash{$key}=&thaw_unescape($value);
1239: }
1240: my @esc_order = split(/\&/,$orderitems);
1241: foreach my $item (@esc_order) {
1242: push(@ruleorder,&unescape($item));
1243: }
1244: }
1245: }
1246: }
1247: return (\%ruleshash,\@ruleorder);
1248: }
1249:
1.976 raeburn 1250: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1251:
1252: sub get_domain_defaults {
1253: my ($domain) = @_;
1254: my $cachetime = 60*60*24;
1255: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1256: if (defined($cached)) {
1257: if (ref($result) eq 'HASH') {
1258: return %{$result};
1259: }
1260: }
1261: my %domdefaults;
1262: my %domconfig =
1.976 raeburn 1263: &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943 raeburn 1264: if (ref($domconfig{'defaults'}) eq 'HASH') {
1265: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1266: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1267: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.976.2.5 raeburn 1268: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1269: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1270: } else {
1271: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1272: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1273: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1274: }
1.976 raeburn 1275: if (ref($domconfig{'quotas'}) eq 'HASH') {
1276: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1277: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1278: } else {
1279: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1280: }
1281: my @usertools = ('aboutme','blog','portfolio');
1282: foreach my $item (@usertools) {
1283: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1284: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1285: }
1286: }
1287: }
1.943 raeburn 1288: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1289: $cachetime);
1290: return %domdefaults;
1291: }
1292:
1.344 www 1293: # --------------------------------------------------- Assign a key to a student
1294:
1295: sub assign_access_key {
1.364 www 1296: #
1297: # a valid key looks like uname:udom#comments
1298: # comments are being appended
1299: #
1.498 www 1300: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1301: $kdom=
1.620 albertel 1302: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1303: $knum=
1.620 albertel 1304: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1305: $cdom=
1.620 albertel 1306: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1307: $cnum=
1.620 albertel 1308: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1309: $udom=$env{'user.name'} unless (defined($udom));
1310: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1311: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1312: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1313: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1314: # assigned to this person
1315: # - this should not happen,
1.345 www 1316: # unless something went wrong
1317: # the first time around
1318: # ready to assign
1.364 www 1319: $logentry=$1.'; '.$logentry;
1.496 www 1320: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1321: $kdom,$knum) eq 'ok') {
1.345 www 1322: # key now belongs to user
1.346 www 1323: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1324: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1325: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1326: return 'ok';
1327: } else {
1328: return
1329: 'error: Count not permanently assign key, will need to be re-entered later.';
1330: }
1331: } else {
1332: return 'error: Could not assign key, try again later.';
1333: }
1.364 www 1334: } elsif (!$existing{$ckey}) {
1.345 www 1335: # the key does not exist
1336: return 'error: The key does not exist';
1337: } else {
1338: # the key is somebody else's
1339: return 'error: The key is already in use';
1340: }
1.344 www 1341: }
1342:
1.364 www 1343: # ------------------------------------------ put an additional comment on a key
1344:
1345: sub comment_access_key {
1346: #
1347: # a valid key looks like uname:udom#comments
1348: # comments are being appended
1349: #
1350: my ($ckey,$cdom,$cnum,$logentry)=@_;
1351: $cdom=
1.620 albertel 1352: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1353: $cnum=
1.620 albertel 1354: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1355: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1356: if ($existing{$ckey}) {
1357: $existing{$ckey}.='; '.$logentry;
1358: # ready to assign
1.367 www 1359: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1360: $cdom,$cnum) eq 'ok') {
1361: return 'ok';
1362: } else {
1363: return 'error: Count not store comment.';
1364: }
1365: } else {
1366: # the key does not exist
1367: return 'error: The key does not exist';
1368: }
1369: }
1370:
1.344 www 1371: # ------------------------------------------------------ Generate a set of keys
1372:
1373: sub generate_access_keys {
1.364 www 1374: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1375: $cdom=
1.620 albertel 1376: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1377: $cnum=
1.620 albertel 1378: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1379: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1380: unless (($cdom) && ($cnum)) { return 0; }
1381: if ($number>10000) { return 0; }
1382: sleep(2); # make sure don't get same seed twice
1383: srand(time()^($$+($$<<15))); # from "Programming Perl"
1384: my $total=0;
1385: for (my $i=1;$i<=$number;$i++) {
1386: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1387: sprintf("%lx",int(100000*rand)).'-'.
1388: sprintf("%lx",int(100000*rand));
1389: $newkey=~s/1/g/g; # folks mix up 1 and l
1390: $newkey=~s/0/h/g; # and also 0 and O
1391: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1392: if ($existing{$newkey}) {
1393: $i--;
1394: } else {
1.364 www 1395: if (&put('accesskeys',
1396: { $newkey => '# generated '.localtime().
1.620 albertel 1397: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1398: '; '.$logentry },
1399: $cdom,$cnum) eq 'ok') {
1.344 www 1400: $total++;
1401: }
1402: }
1403: }
1.620 albertel 1404: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1405: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1406: return $total;
1407: }
1408:
1409: # ------------------------------------------------------- Validate an accesskey
1410:
1411: sub validate_access_key {
1412: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1413: $cdom=
1.620 albertel 1414: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1415: $cnum=
1.620 albertel 1416: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1417: $udom=$env{'user.domain'} unless (defined($udom));
1418: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1419: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1420: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1421: }
1422:
1423: # ------------------------------------- Find the section of student in a course
1.652 albertel 1424: sub devalidate_getsection_cache {
1425: my ($udom,$unam,$courseid)=@_;
1426: my $hashid="$udom:$unam:$courseid";
1427: &devalidate_cache_new('getsection',$hashid);
1428: }
1.298 matthew 1429:
1.815 albertel 1430: sub courseid_to_courseurl {
1431: my ($courseid) = @_;
1432: #already url style courseid
1433: return $courseid if ($courseid =~ m{^/});
1434:
1435: if (exists($env{'course.'.$courseid.'.num'})) {
1436: my $cnum = $env{'course.'.$courseid.'.num'};
1437: my $cdom = $env{'course.'.$courseid.'.domain'};
1438: return "/$cdom/$cnum";
1439: }
1440:
1441: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1442: if (exists($courseinfo{'num'})) {
1443: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1444: }
1445:
1446: return undef;
1447: }
1448:
1.298 matthew 1449: sub getsection {
1450: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1451: my $cachetime=1800;
1.551 albertel 1452:
1453: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1454: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1455: if (defined($cached)) { return $result; }
1456:
1.298 matthew 1457: my %Pending;
1458: my %Expired;
1459: #
1460: # Each role can either have not started yet (pending), be active,
1461: # or have expired.
1462: #
1463: # If there is an active role, we are done.
1464: #
1465: # If there is more than one role which has not started yet,
1466: # choose the one which will start sooner
1467: # If there is one role which has not started yet, return it.
1468: #
1469: # If there is more than one expired role, choose the one which ended last.
1470: # If there is a role which has expired, return it.
1471: #
1.815 albertel 1472: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1473: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1474: foreach my $key (keys(%roleshash)) {
1.479 albertel 1475: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1476: my $section=$1;
1477: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1478: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1479: my $now=time;
1.548 albertel 1480: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1481: $Expired{$end}=$section;
1482: next;
1483: }
1.548 albertel 1484: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1485: $Pending{$start}=$section;
1486: next;
1487: }
1.599 albertel 1488: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1489: }
1490: #
1491: # Presumedly there will be few matching roles from the above
1492: # loop and the sorting time will be negligible.
1493: if (scalar(keys(%Pending))) {
1494: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1495: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1496: }
1497: if (scalar(keys(%Expired))) {
1498: my @sorted = sort {$a <=> $b} keys(%Expired);
1499: my $time = pop(@sorted);
1.599 albertel 1500: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1501: }
1.599 albertel 1502: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1503: }
1.70 www 1504:
1.599 albertel 1505: sub save_cache {
1506: &purge_remembered();
1.722 albertel 1507: #&Apache::loncommon::validate_page();
1.620 albertel 1508: undef(%env);
1.780 albertel 1509: undef($env_loaded);
1.599 albertel 1510: }
1.452 albertel 1511:
1.599 albertel 1512: my $to_remember=-1;
1513: my %remembered;
1514: my %accessed;
1515: my $kicks=0;
1516: my $hits=0;
1.849 albertel 1517: sub make_key {
1518: my ($name,$id) = @_;
1.872 albertel 1519: if (length($id) > 65
1520: && length(&escape($id)) > 200) {
1521: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1522: }
1.849 albertel 1523: return &escape($name.':'.$id);
1524: }
1525:
1.599 albertel 1526: sub devalidate_cache_new {
1527: my ($name,$id,$debug) = @_;
1528: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1529: $id=&make_key($name,$id);
1.599 albertel 1530: $memcache->delete($id);
1531: delete($remembered{$id});
1532: delete($accessed{$id});
1533: }
1534:
1535: sub is_cached_new {
1536: my ($name,$id,$debug) = @_;
1.849 albertel 1537: $id=&make_key($name,$id);
1.599 albertel 1538: if (exists($remembered{$id})) {
1539: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1540: $accessed{$id}=[&gettimeofday()];
1541: $hits++;
1542: return ($remembered{$id},1);
1543: }
1544: my $value = $memcache->get($id);
1545: if (!(defined($value))) {
1546: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1547: return (undef,undef);
1.416 albertel 1548: }
1.599 albertel 1549: if ($value eq '__undef__') {
1550: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1551: $value=undef;
1552: }
1553: &make_room($id,$value,$debug);
1554: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1555: return ($value,1);
1556: }
1557:
1558: sub do_cache_new {
1559: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1560: $id=&make_key($name,$id);
1.599 albertel 1561: my $setvalue=$value;
1562: if (!defined($setvalue)) {
1563: $setvalue='__undef__';
1564: }
1.623 albertel 1565: if (!defined($time) ) {
1566: $time=600;
1567: }
1.599 albertel 1568: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1569: my $result = $memcache->set($id,$setvalue,$time);
1570: if (! $result) {
1.872 albertel 1571: &logthis("caching of id -> $id failed");
1.910 albertel 1572: $memcache->disconnect_all();
1.872 albertel 1573: }
1.600 albertel 1574: # need to make a copy of $value
1.919 albertel 1575: &make_room($id,$value,$debug);
1.599 albertel 1576: return $value;
1577: }
1578:
1579: sub make_room {
1580: my ($id,$value,$debug)=@_;
1.919 albertel 1581:
1582: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1583: : $value;
1.599 albertel 1584: if ($to_remember<0) { return; }
1585: $accessed{$id}=[&gettimeofday()];
1586: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1587: my $to_kick;
1588: my $max_time=0;
1589: foreach my $other (keys(%accessed)) {
1590: if (&tv_interval($accessed{$other}) > $max_time) {
1591: $to_kick=$other;
1592: $max_time=&tv_interval($accessed{$other});
1593: }
1594: }
1595: delete($remembered{$to_kick});
1596: delete($accessed{$to_kick});
1597: $kicks++;
1598: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1599: return;
1600: }
1601:
1.599 albertel 1602: sub purge_remembered {
1.604 albertel 1603: #&logthis("Tossing ".scalar(keys(%remembered)));
1604: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1605: undef(%remembered);
1606: undef(%accessed);
1.428 albertel 1607: }
1.70 www 1608: # ------------------------------------- Read an entry from a user's environment
1609:
1610: sub userenvironment {
1611: my ($udom,$unam,@what)=@_;
1.976 raeburn 1612: my $items;
1613: foreach my $item (@what) {
1614: $items.=&escape($item).'&';
1615: }
1616: $items=~s/\&$//;
1.70 www 1617: my %returnhash=();
1618: my @answer=split(/\&/,
1.976 raeburn 1619: &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70 www 1620: &homeserver($unam,$udom)));
1621: my $i;
1622: for ($i=0;$i<=$#what;$i++) {
1623: $returnhash{$what[$i]}=&unescape($answer[$i]);
1624: }
1625: return %returnhash;
1.1 albertel 1626: }
1627:
1.617 albertel 1628: # ---------------------------------------------------------- Get a studentphoto
1629: sub studentphoto {
1630: my ($udom,$unam,$ext) = @_;
1631: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1632: if (defined($env{'request.course.id'})) {
1.708 raeburn 1633: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1634: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1635: return(&retrievestudentphoto($udom,$unam,$ext));
1636: } else {
1637: my ($result,$perm_reqd)=
1.707 albertel 1638: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1639: if ($result eq 'ok') {
1640: if (!($perm_reqd eq 'yes')) {
1641: return(&retrievestudentphoto($udom,$unam,$ext));
1642: }
1643: }
1644: }
1645: }
1646: } else {
1647: my ($result,$perm_reqd) =
1.707 albertel 1648: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1649: if ($result eq 'ok') {
1650: if (!($perm_reqd eq 'yes')) {
1651: return(&retrievestudentphoto($udom,$unam,$ext));
1652: }
1653: }
1654: }
1655: return '/adm/lonKaputt/lonlogo_broken.gif';
1656: }
1657:
1658: sub retrievestudentphoto {
1659: my ($udom,$unam,$ext,$type) = @_;
1660: my $home=&Apache::lonnet::homeserver($unam,$udom);
1661: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1662: if ($ret eq 'ok') {
1663: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1664: if ($type eq 'thumbnail') {
1665: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1666: }
1667: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1668: return $tokenurl;
1669: } else {
1670: if ($type eq 'thumbnail') {
1671: return '/adm/lonKaputt/genericstudent_tn.gif';
1672: } else {
1673: return '/adm/lonKaputt/lonlogo_broken.gif';
1674: }
1.617 albertel 1675: }
1676: }
1677:
1.263 www 1678: # -------------------------------------------------------------------- New chat
1679:
1680: sub chatsend {
1.724 raeburn 1681: my ($newentry,$anon,$group)=@_;
1.620 albertel 1682: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1683: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1684: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1685: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1686: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1687: &escape($newentry)).':'.$group,$chome);
1.292 www 1688: }
1689:
1690: # ------------------------------------------ Find current version of a resource
1691:
1692: sub getversion {
1693: my $fname=&clutter(shift);
1694: unless ($fname=~/^\/res\//) { return -1; }
1695: return ¤tversion(&filelocation('',$fname));
1696: }
1697:
1698: sub currentversion {
1699: my $fname=shift;
1.599 albertel 1700: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1701: if (defined($cached)) { return $result; }
1.292 www 1702: my $author=$fname;
1703: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1704: my ($udom,$uname)=split(/\//,$author);
1705: my $home=homeserver($uname,$udom);
1706: if ($home eq 'no_host') {
1707: return -1;
1708: }
1709: my $answer=reply("currentversion:$fname",$home);
1710: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1711: return -1;
1712: }
1.599 albertel 1713: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1714: }
1715:
1.1 albertel 1716: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1717:
1.1 albertel 1718: sub subscribe {
1719: my $fname=shift;
1.761 raeburn 1720: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1721: $fname=~s/[\n\r]//g;
1.1 albertel 1722: my $author=$fname;
1723: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1724: my ($udom,$uname)=split(/\//,$author);
1725: my $home=homeserver($uname,$udom);
1.335 albertel 1726: if ($home eq 'no_host') {
1727: return 'not_found';
1.1 albertel 1728: }
1729: my $answer=reply("sub:$fname",$home);
1.64 www 1730: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1731: $answer.=' by '.$home;
1732: }
1.1 albertel 1733: return $answer;
1734: }
1735:
1.8 www 1736: # -------------------------------------------------------------- Replicate file
1737:
1738: sub repcopy {
1739: my $filename=shift;
1.23 www 1740: $filename=~s/\/+/\//g;
1.607 raeburn 1741: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1742: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1743: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1744: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1745: return &repcopy_userfile($filename);
1746: }
1.532 albertel 1747: $filename=~s/[\n\r]//g;
1.8 www 1748: my $transname="$filename.in.transfer";
1.828 www 1749: # FIXME: this should flock
1.607 raeburn 1750: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1751: my $remoteurl=subscribe($filename);
1.64 www 1752: if ($remoteurl =~ /^con_lost by/) {
1753: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1754: return 'unavailable';
1.8 www 1755: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1756: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1757: return 'not_found';
1.64 www 1758: } elsif ($remoteurl =~ /^rejected by/) {
1759: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1760: return 'forbidden';
1.20 www 1761: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1762: return 'ok';
1.8 www 1763: } else {
1.290 www 1764: my $author=$filename;
1765: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1766: my ($udom,$uname)=split(/\//,$author);
1767: my $home=homeserver($uname,$udom);
1768: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1769: my @parts=split(/\//,$filename);
1770: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1771: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1772: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1773: return 'bad_request';
1.8 www 1774: }
1775: my $count;
1776: for ($count=5;$count<$#parts;$count++) {
1777: $path.="/$parts[$count]";
1778: if ((-e $path)!=1) {
1779: mkdir($path,0777);
1780: }
1781: }
1782: my $ua=new LWP::UserAgent;
1783: my $request=new HTTP::Request('GET',"$remoteurl");
1784: my $response=$ua->request($request,$transname);
1785: if ($response->is_error()) {
1786: unlink($transname);
1787: my $message=$response->status_line;
1.672 albertel 1788: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1789: ." LWP get: $message: $filename</font>");
1.607 raeburn 1790: return 'unavailable';
1.8 www 1791: } else {
1.16 www 1792: if ($remoteurl!~/\.meta$/) {
1793: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1794: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1795: if ($mresponse->is_error()) {
1796: unlink($filename.'.meta');
1797: &logthis(
1.672 albertel 1798: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1799: }
1800: }
1.8 www 1801: rename($transname,$filename);
1.607 raeburn 1802: return 'ok';
1.8 www 1803: }
1.290 www 1804: }
1.8 www 1805: }
1.330 www 1806: }
1807:
1808: # ------------------------------------------------ Get server side include body
1809: sub ssi_body {
1.381 albertel 1810: my ($filelink,%form)=@_;
1.606 matthew 1811: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1812: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1813: }
1.953 www 1814: my $output='';
1815: my $response;
1.976.2.3 raeburn 1816: if ($filelink=~/^https?\:/) {
1.954 raeburn 1817: ($output,$response)=&externalssi($filelink);
1.953 www 1818: } else {
1819: ($output,$response)=&ssi($filelink,%form);
1820: }
1.778 albertel 1821: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1822: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1823: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1824: if (wantarray) {
1825: return ($output, $response);
1826: } else {
1827: return $output;
1828: }
1.8 www 1829: }
1830:
1.15 www 1831: # --------------------------------------------------------- Server Side Include
1832:
1.782 albertel 1833: sub absolute_url {
1834: my ($host_name) = @_;
1835: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1836: if ($host_name eq '') {
1837: $host_name = $ENV{'SERVER_NAME'};
1838: }
1839: return $protocol.$host_name;
1840: }
1841:
1.942 foxr 1842: #
1843: # Server side include.
1844: # Parameters:
1845: # fn Possibly encrypted resource name/id.
1846: # form Hash that describes how the rendering should be done
1847: # and other things.
1.944 foxr 1848: # Returns:
1.950 raeburn 1849: # Scalar context: The content of the response.
1850: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1851: #
1.15 www 1852: sub ssi {
1853:
1.944 foxr 1854: my ($fn,%form)=@_;
1.15 www 1855: my $ua=new LWP::UserAgent;
1.23 www 1856: my $request;
1.711 albertel 1857:
1858: $form{'no_update_last_known'}=1;
1.895 albertel 1859: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1860: if (%form) {
1.782 albertel 1861: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1862: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1863: } else {
1.782 albertel 1864: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1865: }
1866:
1.15 www 1867: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1868: my $response=$ua->request($request);
1869:
1.944 foxr 1870: if (wantarray) {
1871: return ($response->content, $response);
1872: } else {
1873: return $response->content;
1.942 foxr 1874: }
1.324 www 1875: }
1876:
1877: sub externalssi {
1878: my ($url)=@_;
1879: my $ua=new LWP::UserAgent;
1880: my $request=new HTTP::Request('GET',$url);
1881: my $response=$ua->request($request);
1.954 raeburn 1882: if (wantarray) {
1883: return ($response->content, $response);
1884: } else {
1885: return $response->content;
1886: }
1.15 www 1887: }
1.254 www 1888:
1.492 albertel 1889: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1890:
1891: sub allowuploaded {
1892: my ($srcurl,$url)=@_;
1893: $url=&clutter(&declutter($url));
1894: my $dir=$url;
1895: $dir=~s/\/[^\/]+$//;
1896: my %httpref=();
1897: my $httpurl=&hreflocation('',$url);
1898: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1899: &Apache::lonnet::appenv(\%httpref);
1.254 www 1900: }
1.477 raeburn 1901:
1.478 albertel 1902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1903: # input: action, courseID, current domain, intended
1.637 raeburn 1904: # path to file, source of file, instruction to parse file for objects,
1905: # ref to hash for embedded objects,
1906: # ref to hash for codebase of java objects.
1907: #
1.485 raeburn 1908: # output: url to file (if action was uploaddoc),
1909: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1910: #
1.478 albertel 1911: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1912: # course.
1.477 raeburn 1913: #
1.478 albertel 1914: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1915: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1916: # course's home server.
1.477 raeburn 1917: #
1.478 albertel 1918: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1919: # be copied from $source (current location) to
1920: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1921: # and will then be copied to
1922: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1923: # course's home server.
1.485 raeburn 1924: #
1.481 raeburn 1925: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1926: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1927: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1928: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1929: # in course's home server.
1.637 raeburn 1930: #
1.477 raeburn 1931:
1932: sub process_coursefile {
1.638 albertel 1933: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1934: my $fetchresult;
1.638 albertel 1935: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1936: if ($action eq 'propagate') {
1.638 albertel 1937: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1938: $home);
1.481 raeburn 1939: } else {
1.477 raeburn 1940: my $fpath = '';
1941: my $fname = $file;
1.478 albertel 1942: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1943: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1944: my $filepath = &build_filepath($fpath);
1.481 raeburn 1945: if ($action eq 'copy') {
1946: if ($source eq '') {
1947: $fetchresult = 'no source file';
1948: return $fetchresult;
1949: } else {
1950: my $destination = $filepath.'/'.$fname;
1951: rename($source,$destination);
1952: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1953: $home);
1.481 raeburn 1954: }
1955: } elsif ($action eq 'uploaddoc') {
1956: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1957: print $fh $env{'form.'.$source};
1.481 raeburn 1958: close($fh);
1.637 raeburn 1959: if ($parser eq 'parse') {
1.961 raeburn 1960: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 1961: unless ($parse_result eq 'ok') {
1962: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1963: }
1964: }
1.477 raeburn 1965: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1966: $home);
1.481 raeburn 1967: if ($fetchresult eq 'ok') {
1968: return '/uploaded/'.$fpath.'/'.$fname;
1969: } else {
1970: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1971: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1972: return '/adm/notfound.html';
1973: }
1.477 raeburn 1974: }
1975: }
1.485 raeburn 1976: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1977: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1978: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1979: }
1980: return $fetchresult;
1981: }
1982:
1.637 raeburn 1983: sub build_filepath {
1984: my ($fpath) = @_;
1985: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1986: unless ($fpath eq '') {
1987: my @parts=split('/',$fpath);
1988: foreach my $part (@parts) {
1989: $filepath.= '/'.$part;
1990: if ((-e $filepath)!=1) {
1991: mkdir($filepath,0777);
1992: }
1993: }
1994: }
1995: return $filepath;
1996: }
1997:
1998: sub store_edited_file {
1.638 albertel 1999: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2000: my $file = $primary_url;
2001: $file =~ s#^/uploaded/$docudom/$docuname/##;
2002: my $fpath = '';
2003: my $fname = $file;
2004: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2005: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2006: my $filepath = &build_filepath($fpath);
2007: open(my $fh,'>'.$filepath.'/'.$fname);
2008: print $fh $content;
2009: close($fh);
1.638 albertel 2010: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2011: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2012: $home);
1.637 raeburn 2013: if ($$fetchresult eq 'ok') {
2014: return '/uploaded/'.$fpath.'/'.$fname;
2015: } else {
1.638 albertel 2016: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2017: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2018: return '/adm/notfound.html';
2019: }
2020: }
2021:
1.531 albertel 2022: sub clean_filename {
1.831 albertel 2023: my ($fname,$args)=@_;
1.315 www 2024: # Replace Windows backslashes by forward slashes
1.257 www 2025: $fname=~s/\\/\//g;
1.831 albertel 2026: if (!$args->{'keep_path'}) {
2027: # Get rid of everything but the actual filename
2028: $fname=~s/^.*\/([^\/]+)$/$1/;
2029: }
1.315 www 2030: # Replace spaces by underscores
2031: $fname=~s/\s+/\_/g;
2032: # Replace all other weird characters by nothing
1.831 albertel 2033: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2034: # Replace all .\d. sequences with _\d. so they no longer look like version
2035: # numbers
2036: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2037: return $fname;
2038: }
2039:
1.608 albertel 2040: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2041: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2042: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2043: # $coursedoc - if true up to the current course
2044: # if false
2045: # $subdir - directory in userfile to store the file into
1.858 raeburn 2046: # $parser - instruction to parse file for objects ($parser = parse)
2047: # $allfiles - reference to hash for embedded objects
2048: # $codebase - reference to hash for codebase of java objects
2049: # $desuname - username for permanent storage of uploaded file
2050: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2051: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2052: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 2053: #
1.686 albertel 2054: # output: url of file in userspace, or error: <message>
2055: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2056:
2057:
1.531 albertel 2058: sub userfileupload {
1.860 raeburn 2059: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2060: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 2061: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2062: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2063: $fname=&clean_filename($fname);
1.315 www 2064: # See if there is anything left
1.257 www 2065: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2066: chop($env{'form.'.$formname});
1.523 raeburn 2067: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2068: my $now = time;
2069: my $filepath = 'tmp/helprequests/'.$now;
2070: my @parts=split(/\//,$filepath);
2071: my $fullpath = $perlvar{'lonDaemons'};
2072: for (my $i=0;$i<@parts;$i++) {
2073: $fullpath .= '/'.$parts[$i];
2074: if ((-e $fullpath)!=1) {
2075: mkdir($fullpath,0777);
2076: }
2077: }
2078: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2079: print $fh $env{'form.'.$formname};
1.523 raeburn 2080: close($fh);
1.741 raeburn 2081: return $fullpath.'/'.$fname;
2082: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2083: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2084: '_'.$env{'user.domain'}.'/pending';
2085: my @parts=split(/\//,$filepath);
2086: my $fullpath = $perlvar{'lonDaemons'};
2087: for (my $i=0;$i<@parts;$i++) {
2088: $fullpath .= '/'.$parts[$i];
2089: if ((-e $fullpath)!=1) {
2090: mkdir($fullpath,0777);
2091: }
2092: }
2093: open(my $fh,'>'.$fullpath.'/'.$fname);
2094: print $fh $env{'form.'.$formname};
2095: close($fh);
2096: return $fullpath.'/'.$fname;
1.523 raeburn 2097: }
1.719 banghart 2098:
1.258 www 2099: # Create the directory if not present
1.493 albertel 2100: $fname="$subdir/$fname";
1.259 www 2101: if ($coursedoc) {
1.638 albertel 2102: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2103: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2104: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2105: return &finishuserfileupload($docuname,$docudom,
2106: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2107: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2108: } else {
1.620 albertel 2109: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2110: return &process_coursefile('uploaddoc',$docuname,$docudom,
2111: $fname,$formname,$parser,
2112: $allfiles,$codebase);
1.481 raeburn 2113: }
1.719 banghart 2114: } elsif (defined($destuname)) {
2115: my $docuname=$destuname;
2116: my $docudom=$destudom;
1.860 raeburn 2117: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2118: $parser,$allfiles,$codebase,
2119: $thumbwidth,$thumbheight);
1.719 banghart 2120:
1.259 www 2121: } else {
1.638 albertel 2122: my $docuname=$env{'user.name'};
2123: my $docudom=$env{'user.domain'};
1.714 raeburn 2124: if (exists($env{'form.group'})) {
2125: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2126: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2127: }
1.860 raeburn 2128: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2129: $parser,$allfiles,$codebase,
2130: $thumbwidth,$thumbheight);
1.259 www 2131: }
1.271 www 2132: }
2133:
2134: sub finishuserfileupload {
1.860 raeburn 2135: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2136: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2137: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2138: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 2139: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2140: $file=$fname;
2141: if ($fname=~m|/|) {
2142: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2143: $path.=$fnamepath.'/';
2144: }
1.259 www 2145: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2146: my $count;
2147: for ($count=4;$count<=$#parts;$count++) {
2148: $filepath.="/$parts[$count]";
2149: if ((-e $filepath)!=1) {
2150: mkdir($filepath,0777);
2151: }
2152: }
2153: # Save the file
2154: {
1.701 albertel 2155: if (!open(FH,'>'.$filepath.'/'.$file)) {
2156: &logthis('Failed to create '.$filepath.'/'.$file);
2157: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2158: return '/adm/notfound.html';
2159: }
2160: if (!print FH ($env{'form.'.$formname})) {
2161: &logthis('Failed to write to '.$filepath.'/'.$file);
2162: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2163: return '/adm/notfound.html';
2164: }
1.570 albertel 2165: close(FH);
1.258 www 2166: }
1.637 raeburn 2167: if ($parser eq 'parse') {
1.961 raeburn 2168: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2169: $codebase);
1.637 raeburn 2170: unless ($parse_result eq 'ok') {
1.638 albertel 2171: &logthis('Failed to parse '.$filepath.$file.
2172: ' for embedded media: '.$parse_result);
1.637 raeburn 2173: }
2174: }
1.860 raeburn 2175: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2176: my $input = $filepath.'/'.$file;
2177: my $output = $filepath.'/'.'tn-'.$file;
2178: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2179: system("convert -sample $thumbsize $input $output");
2180: if (-e $filepath.'/'.'tn-'.$file) {
2181: $fetchthumb = 1;
2182: }
2183: }
1.858 raeburn 2184:
1.259 www 2185: # Notify homeserver to grep it
2186: #
1.638 albertel 2187: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2188: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2189: if ($fetchresult eq 'ok') {
1.860 raeburn 2190: if ($fetchthumb) {
2191: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2192: if ($thumbresult ne 'ok') {
2193: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2194: $docuhome.': '.$thumbresult);
2195: }
2196: }
1.259 www 2197: #
1.258 www 2198: # Return the URL to it
1.494 albertel 2199: return '/uploaded/'.$path.$file;
1.263 www 2200: } else {
1.494 albertel 2201: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2202: ': '.$fetchresult);
1.263 www 2203: return '/adm/notfound.html';
1.858 raeburn 2204: }
1.493 albertel 2205: }
2206:
1.637 raeburn 2207: sub extract_embedded_items {
1.961 raeburn 2208: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2209: my @state = ();
2210: my %javafiles = (
2211: codebase => '',
2212: code => '',
2213: archive => ''
2214: );
2215: my %mediafiles = (
2216: src => '',
2217: movie => '',
2218: );
1.648 raeburn 2219: my $p;
2220: if ($content) {
2221: $p = HTML::LCParser->new($content);
2222: } else {
1.961 raeburn 2223: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2224: }
1.641 albertel 2225: while (my $t=$p->get_token()) {
1.640 albertel 2226: if ($t->[0] eq 'S') {
2227: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2228: push(@state, $tagname);
1.648 raeburn 2229: if (lc($tagname) eq 'allow') {
2230: &add_filetype($allfiles,$attr->{'src'},'src');
2231: }
1.640 albertel 2232: if (lc($tagname) eq 'img') {
2233: &add_filetype($allfiles,$attr->{'src'},'src');
2234: }
1.886 albertel 2235: if (lc($tagname) eq 'a') {
2236: &add_filetype($allfiles,$attr->{'href'},'href');
2237: }
1.645 raeburn 2238: if (lc($tagname) eq 'script') {
2239: if ($attr->{'archive'} =~ /\.jar$/i) {
2240: &add_filetype($allfiles,$attr->{'archive'},'archive');
2241: } else {
2242: &add_filetype($allfiles,$attr->{'src'},'src');
2243: }
2244: }
2245: if (lc($tagname) eq 'link') {
2246: if (lc($attr->{'rel'}) eq 'stylesheet') {
2247: &add_filetype($allfiles,$attr->{'href'},'href');
2248: }
2249: }
1.640 albertel 2250: if (lc($tagname) eq 'object' ||
2251: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2252: foreach my $item (keys(%javafiles)) {
2253: $javafiles{$item} = '';
2254: }
2255: }
2256: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2257: my $name = lc($attr->{'name'});
2258: foreach my $item (keys(%javafiles)) {
2259: if ($name eq $item) {
2260: $javafiles{$item} = $attr->{'value'};
2261: last;
2262: }
2263: }
2264: foreach my $item (keys(%mediafiles)) {
2265: if ($name eq $item) {
2266: &add_filetype($allfiles, $attr->{'value'}, 'value');
2267: last;
2268: }
2269: }
2270: }
2271: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2272: foreach my $item (keys(%javafiles)) {
2273: if ($attr->{$item}) {
2274: $javafiles{$item} = $attr->{$item};
2275: last;
2276: }
2277: }
2278: foreach my $item (keys(%mediafiles)) {
2279: if ($attr->{$item}) {
2280: &add_filetype($allfiles,$attr->{$item},$item);
2281: last;
2282: }
2283: }
2284: }
2285: } elsif ($t->[0] eq 'E') {
2286: my ($tagname) = ($t->[1]);
2287: if ($javafiles{'codebase'} ne '') {
2288: $javafiles{'codebase'} .= '/';
2289: }
2290: if (lc($tagname) eq 'applet' ||
2291: lc($tagname) eq 'object' ||
2292: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2293: ) {
2294: foreach my $item (keys(%javafiles)) {
2295: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2296: my $file=$javafiles{'codebase'}.$javafiles{$item};
2297: &add_filetype($allfiles,$file,$item);
2298: }
2299: }
2300: }
2301: pop @state;
2302: }
2303: }
1.637 raeburn 2304: return 'ok';
2305: }
2306:
1.639 albertel 2307: sub add_filetype {
2308: my ($allfiles,$file,$type)=@_;
2309: if (exists($allfiles->{$file})) {
2310: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2311: push(@{$allfiles->{$file}}, &escape($type));
2312: }
2313: } else {
2314: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2315: }
2316: }
2317:
1.493 albertel 2318: sub removeuploadedurl {
2319: my ($url)=@_;
2320: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2321: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2322: }
2323:
2324: sub removeuserfile {
2325: my ($docuname,$docudom,$fname)=@_;
2326: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2327: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2328: if ($result eq 'ok') {
2329: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2330: my $metafile = $fname.'.meta';
2331: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2332: my $url = "/uploaded/$docudom/$docuname/$fname";
2333: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2334: my $sqlresult =
1.823 albertel 2335: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2336: 'portfolio_metadata',$group,
2337: 'delete');
1.798 raeburn 2338: }
2339: }
2340: return $result;
1.257 www 2341: }
1.15 www 2342:
1.530 albertel 2343: sub mkdiruserfile {
2344: my ($docuname,$docudom,$dir)=@_;
2345: my $home=&homeserver($docuname,$docudom);
2346: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2347: }
2348:
1.531 albertel 2349: sub renameuserfile {
2350: my ($docuname,$docudom,$old,$new)=@_;
2351: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2352: my $result = &reply("renameuserfile:$docudom:$docuname:".
2353: &escape("$old").':'.&escape("$new"),$home);
2354: if ($result eq 'ok') {
2355: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2356: my $oldmeta = $old.'.meta';
2357: my $newmeta = $new.'.meta';
2358: my $metaresult =
2359: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2360: my $url = "/uploaded/$docudom/$docuname/$old";
2361: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2362: my $sqlresult =
1.823 albertel 2363: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2364: 'portfolio_metadata',$group,
2365: 'delete');
1.798 raeburn 2366: }
2367: }
2368: return $result;
1.531 albertel 2369: }
2370:
1.14 www 2371: # ------------------------------------------------------------------------- Log
2372:
2373: sub log {
2374: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2375: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2376: }
2377:
2378: # ------------------------------------------------------------------ Course Log
1.352 www 2379: #
2380: # This routine flushes several buffers of non-mission-critical nature
2381: #
1.157 www 2382:
2383: sub flushcourselogs {
1.352 www 2384: &logthis('Flushing log buffers');
2385: #
2386: # course logs
2387: # This is a log of all transactions in a course, which can be used
2388: # for data mining purposes
2389: #
2390: # It also collects the courseid database, which lists last transaction
2391: # times and course titles for all courseids
2392: #
2393: my %courseidbuffer=();
1.921 raeburn 2394: foreach my $crsid (keys(%courselogs)) {
1.352 www 2395: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2396: &escape($courselogs{$crsid}),
2397: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2398: delete $courselogs{$crsid};
2399: } else {
2400: &logthis('Failed to flush log buffer for '.$crsid);
2401: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2402: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2403: " exceeded maximum size, deleting.</font>");
2404: delete $courselogs{$crsid};
2405: }
1.352 www 2406: }
1.920 raeburn 2407: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2408: 'description' => $coursedescrbuf{$crsid},
2409: 'inst_code' => $courseinstcodebuf{$crsid},
2410: 'type' => $coursetypebuf{$crsid},
2411: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2412: };
1.191 harris41 2413: }
1.352 www 2414: #
2415: # Write course id database (reverse lookup) to homeserver of courses
2416: # Is used in pickcourse
2417: #
1.840 albertel 2418: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2419: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2420: $courseidbuffer{$crs_home},
2421: $crs_home,'timeonly');
1.352 www 2422: }
2423: #
2424: # File accesses
2425: # Writes to the dynamic metadata of resources to get hit counts, etc.
2426: #
1.449 matthew 2427: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2428: if ($entry =~ /___count$/) {
2429: my ($dom,$name);
1.807 albertel 2430: ($dom,$name,undef)=
1.811 albertel 2431: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2432: if (! defined($dom) || $dom eq '' ||
2433: ! defined($name) || $name eq '') {
1.620 albertel 2434: my $cid = $env{'request.course.id'};
2435: $dom = $env{'request.'.$cid.'.domain'};
2436: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2437: }
1.450 matthew 2438: my $value = $accesshash{$entry};
2439: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2440: my %temphash=($url => $value);
1.449 matthew 2441: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2442: if ($result eq 'ok') {
2443: delete $accesshash{$entry};
2444: } elsif ($result eq 'unknown_cmd') {
2445: # Target server has old code running on it.
1.450 matthew 2446: my %temphash=($entry => $value);
1.449 matthew 2447: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2448: delete $accesshash{$entry};
2449: }
2450: }
2451: } else {
1.811 albertel 2452: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2453: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2454: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2455: delete $accesshash{$entry};
2456: }
1.185 www 2457: }
1.191 harris41 2458: }
1.352 www 2459: #
2460: # Roles
2461: # Reverse lookup of user roles for course faculty/staff and co-authorship
2462: #
1.800 albertel 2463: foreach my $entry (keys(%userrolehash)) {
1.351 www 2464: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2465: split(/\:/,$entry);
2466: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2467: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2468: $rudom,$runame) eq 'ok') {
2469: delete $userrolehash{$entry};
2470: }
2471: }
1.662 raeburn 2472: #
2473: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2474: #
2475: my %domrolebuffer = ();
2476: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2477: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2478: if ($domrolebuffer{$rudom}) {
2479: $domrolebuffer{$rudom}.='&'.&escape($entry).
2480: '='.&escape($domainrolehash{$entry});
2481: } else {
2482: $domrolebuffer{$rudom}.=&escape($entry).
2483: '='.&escape($domainrolehash{$entry});
2484: }
2485: delete $domainrolehash{$entry};
2486: }
2487: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2488: my %servers = &get_servers($dom,'library');
2489: foreach my $tryserver (keys(%servers)) {
2490: unless (&reply('domroleput:'.$dom.':'.
2491: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2492: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2493: }
1.662 raeburn 2494: }
2495: }
1.186 www 2496: $dumpcount++;
1.157 www 2497: }
2498:
2499: sub courselog {
2500: my $what=shift;
1.158 www 2501: $what=time.':'.$what;
1.620 albertel 2502: unless ($env{'request.course.id'}) { return ''; }
2503: $coursedombuf{$env{'request.course.id'}}=
2504: $env{'course.'.$env{'request.course.id'}.'.domain'};
2505: $coursenumbuf{$env{'request.course.id'}}=
2506: $env{'course.'.$env{'request.course.id'}.'.num'};
2507: $coursehombuf{$env{'request.course.id'}}=
2508: $env{'course.'.$env{'request.course.id'}.'.home'};
2509: $coursedescrbuf{$env{'request.course.id'}}=
2510: $env{'course.'.$env{'request.course.id'}.'.description'};
2511: $courseinstcodebuf{$env{'request.course.id'}}=
2512: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2513: $courseownerbuf{$env{'request.course.id'}}=
2514: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2515: $coursetypebuf{$env{'request.course.id'}}=
2516: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2517: if (defined $courselogs{$env{'request.course.id'}}) {
2518: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2519: } else {
1.620 albertel 2520: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2521: }
1.620 albertel 2522: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2523: &flushcourselogs();
2524: }
1.158 www 2525: }
2526:
2527: sub courseacclog {
2528: my $fnsymb=shift;
1.620 albertel 2529: unless ($env{'request.course.id'}) { return ''; }
2530: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2531: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2532: $what.=':POST';
1.583 matthew 2533: # FIXME: Probably ought to escape things....
1.800 albertel 2534: foreach my $key (keys(%env)) {
2535: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2536: my $formitem = $1;
2537: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2538: $what.=':'.$formitem.'='.$env{$key};
2539: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2540: $what.=':'.$formitem.'='.$env{$key};
2541: }
1.158 www 2542: }
1.191 harris41 2543: }
1.583 matthew 2544: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2545: # FIXME: We should not be depending on a form parameter that someone
2546: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2547: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2548: $what.= ':POST';
2549: # FIXME: Probably ought to escape things....
2550: foreach my $element ('courseexp','crsfulltext','crsrelated',
2551: 'crsdiscuss') {
1.620 albertel 2552: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2553: }
2554: }
1.158 www 2555: }
2556: &courselog($what);
1.149 www 2557: }
2558:
1.185 www 2559: sub countacc {
2560: my $url=&declutter(shift);
1.458 matthew 2561: return if (! defined($url) || $url eq '');
1.620 albertel 2562: unless ($env{'request.course.id'}) { return ''; }
2563: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2564: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2565: $accesshash{$key}++;
1.185 www 2566: }
1.349 www 2567:
1.361 www 2568: sub linklog {
2569: my ($from,$to)=@_;
2570: $from=&declutter($from);
2571: $to=&declutter($to);
2572: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2573: $accesshash{$to.'___'.$from.'___goto'}=1;
2574: }
2575:
1.349 www 2576: sub userrolelog {
2577: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2578: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2579: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2580: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2581: ($trole=~/^ta/)) {
1.350 www 2582: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2583: $userrolehash
2584: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2585: =$tend.':'.$tstart;
1.662 raeburn 2586: }
1.898 albertel 2587: if (($env{'request.role'} =~ /dc\./) &&
2588: (($trole=~/^au/) || ($trole=~/^in/) ||
2589: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2590: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2591: $userrolehash
2592: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2593: =$tend.':'.$tstart;
2594: }
1.662 raeburn 2595: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2596: ($trole=~/^li/) || ($trole=~/^li/) ||
2597: ($trole=~/^au/) || ($trole=~/^dg/) ||
2598: ($trole=~/^sc/)) {
2599: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2600: $domainrolehash
2601: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2602: = $tend.':'.$tstart;
2603: }
1.351 www 2604: }
2605:
1.957 raeburn 2606: sub courserolelog {
2607: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2608: if (($trole eq 'cc') || ($trole eq 'in') ||
2609: ($trole eq 'ep') || ($trole eq 'ad') ||
2610: ($trole eq 'ta') || ($trole eq 'st') ||
2611: ($trole=~/^cr/) || ($trole eq 'gr')) {
2612: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2613: my $cdom = $1;
2614: my $cnum = $2;
2615: my $sec = $3;
2616: my $namespace = 'rolelog';
2617: my %storehash = (
2618: role => $trole,
2619: start => $tstart,
2620: end => $tend,
2621: selfenroll => $selfenroll,
2622: context => $context,
2623: );
2624: if ($trole eq 'gr') {
2625: $namespace = 'groupslog';
2626: $storehash{'group'} = $sec;
2627: } else {
2628: $storehash{'section'} = $sec;
2629: }
2630: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.976.2.8 raeburn 2631: if (($trole ne 'st') || ($sec ne '')) {
2632: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2633: }
1.957 raeburn 2634: }
2635: }
2636: return;
2637: }
2638:
1.351 www 2639: sub get_course_adv_roles {
1.948 raeburn 2640: my ($cid,$codes) = @_;
1.620 albertel 2641: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2642: my %coursehash=&coursedescription($cid);
1.470 www 2643: my %nothide=();
1.800 albertel 2644: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2645: if ($user !~ /:/) {
2646: $nothide{join(':',split(/[\@]/,$user))}=1;
2647: } else {
2648: $nothide{$user}=1;
2649: }
1.470 www 2650: }
1.351 www 2651: my %returnhash=();
2652: my %dumphash=
2653: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2654: my $now=time;
1.976.2.8 raeburn 2655: my %privileged;
1.800 albertel 2656: foreach my $entry (keys %dumphash) {
2657: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2658: if (($tstart) && ($tstart<0)) { next; }
2659: if (($tend) && ($tend<$now)) { next; }
2660: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2661: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2662: if ($username eq '' || $domain eq '') { next; }
1.976.2.8 raeburn 2663: unless (ref($privileged{$domain}) eq 'HASH') {
2664: my %dompersonnel =
2665: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2666: $privileged{$domain} = {};
2667: foreach my $server (keys(%dompersonnel)) {
2668: if (ref($dompersonnel{$server}) eq 'HASH') {
2669: foreach my $user (keys(%{$dompersonnel{$server}})) {
2670: my ($trole,$uname,$udom) = split(/:/,$user);
2671: $privileged{$udom}{$uname} = 1;
2672: }
2673: }
2674: }
2675: }
2676: if ((exists($privileged{$domain}{$username})) &&
2677: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2678: if ($role eq 'cr') { next; }
1.948 raeburn 2679: if ($codes) {
2680: if ($section) { $role .= ':'.$section; }
2681: if ($returnhash{$role}) {
2682: $returnhash{$role}.=','.$username.':'.$domain;
2683: } else {
2684: $returnhash{$role}=$username.':'.$domain;
2685: }
1.351 www 2686: } else {
1.948 raeburn 2687: my $key=&plaintext($role);
1.973 bisitz 2688: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2689: if ($returnhash{$key}) {
2690: $returnhash{$key}.=','.$username.':'.$domain;
2691: } else {
2692: $returnhash{$key}=$username.':'.$domain;
2693: }
1.351 www 2694: }
1.948 raeburn 2695: }
1.400 www 2696: return %returnhash;
2697: }
2698:
2699: sub get_my_roles {
1.937 raeburn 2700: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2701: unless (defined($uname)) { $uname=$env{'user.name'}; }
2702: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2703: my (%dumphash,%nothide);
1.858 raeburn 2704: if ($context eq 'userroles') {
2705: %dumphash = &dump('roles',$udom,$uname);
2706: } else {
2707: %dumphash=
1.400 www 2708: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2709: if ($hidepriv) {
2710: my %coursehash=&coursedescription($udom.'_'.$uname);
2711: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2712: if ($user !~ /:/) {
2713: $nothide{join(':',split(/[\@]/,$user))} = 1;
2714: } else {
2715: $nothide{$user} = 1;
2716: }
2717: }
2718: }
1.858 raeburn 2719: }
1.400 www 2720: my %returnhash=();
2721: my $now=time;
1.976.2.9 raeburn 2722: my %privileged;
1.800 albertel 2723: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2724: my ($role,$tend,$tstart);
2725: if ($context eq 'userroles') {
2726: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2727: } else {
2728: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2729: }
1.400 www 2730: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2731: my $status = 'active';
1.939 raeburn 2732: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2733: $status = 'previous';
2734: }
2735: if (($tstart) && ($now<$tstart)) {
2736: $status = 'future';
2737: }
2738: if (ref($types) eq 'ARRAY') {
2739: if (!grep(/^\Q$status\E$/,@{$types})) {
2740: next;
2741: }
2742: } else {
2743: if ($status ne 'active') {
2744: next;
2745: }
2746: }
1.867 raeburn 2747: my ($rolecode,$username,$domain,$section,$area);
2748: if ($context eq 'userroles') {
2749: ($area,$rolecode) = split(/_/,$entry);
2750: (undef,$domain,$username,$section) = split(/\//,$area);
2751: } else {
2752: ($role,$username,$domain,$section) = split(/\:/,$entry);
2753: }
1.832 raeburn 2754: if (ref($roledoms) eq 'ARRAY') {
2755: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2756: next;
2757: }
2758: }
2759: if (ref($roles) eq 'ARRAY') {
2760: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2761: if ($role =~ /^cr\//) {
2762: if (!grep(/^cr$/,@{$roles})) {
2763: next;
2764: }
2765: } else {
2766: next;
2767: }
1.832 raeburn 2768: }
1.867 raeburn 2769: }
1.937 raeburn 2770: if ($hidepriv) {
1.976.2.8 raeburn 2771: if ($context eq 'userroles') {
2772: if ((&privileged($username,$domain)) &&
2773: (!$nothide{$username.':'.$domain})) {
2774: next;
2775: }
2776: } else {
2777: unless (ref($privileged{$domain}) eq 'HASH') {
2778: my %dompersonnel =
2779: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2780: $privileged{$domain} = {};
2781: if (keys(%dompersonnel)) {
2782: foreach my $server (keys(%dompersonnel)) {
2783: if (ref($dompersonnel{$server}) eq 'HASH') {
2784: foreach my $user (keys(%{$dompersonnel{$server}})) {
2785: my ($trole,$uname,$udom) = split(/:/,$user);
2786: $privileged{$udom}{$uname} = $trole;
2787: }
2788: }
2789: }
2790: }
2791: }
2792: if (exists($privileged{$domain}{$username})) {
2793: if (!$nothide{$username.':'.$domain}) {
2794: next;
2795: }
2796: }
1.937 raeburn 2797: }
2798: }
1.933 raeburn 2799: if ($withsec) {
2800: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2801: $tstart.':'.$tend;
2802: } else {
2803: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2804: }
1.832 raeburn 2805: }
1.373 www 2806: return %returnhash;
1.399 www 2807: }
2808:
2809: # ----------------------------------------------------- Frontpage Announcements
2810: #
2811: #
2812:
2813: sub postannounce {
2814: my ($server,$text)=@_;
1.844 albertel 2815: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2816: unless ($text=~/\w/) { $text=''; }
2817: return &reply('setannounce:'.&escape($text),$server);
2818: }
2819:
2820: sub getannounce {
1.448 albertel 2821:
2822: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2823: my $announcement='';
1.800 albertel 2824: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2825: close($fh);
1.399 www 2826: if ($announcement=~/\w/) {
2827: return
2828: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2829: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2830: } else {
2831: return '';
2832: }
2833: } else {
2834: return '';
2835: }
1.351 www 2836: }
1.353 www 2837:
2838: # ---------------------------------------------------------- Course ID routines
2839: # Deal with domain's nohist_courseid.db files
2840: #
2841:
2842: sub courseidput {
1.921 raeburn 2843: my ($domain,$storehash,$coursehome,$caller) = @_;
2844: my $outcome;
2845: if ($caller eq 'timeonly') {
2846: my $cids = '';
2847: foreach my $item (keys(%$storehash)) {
2848: $cids.=&escape($item).'&';
2849: }
2850: $cids=~s/\&$//;
2851: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2852: $coursehome);
2853: } else {
2854: my $items = '';
2855: foreach my $item (keys(%$storehash)) {
2856: $items.= &escape($item).'='.
2857: &freeze_escape($$storehash{$item}).'&';
2858: }
2859: $items=~s/\&$//;
2860: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2861: $coursehome);
1.918 raeburn 2862: }
2863: if ($outcome eq 'unknown_cmd') {
2864: my $what;
2865: foreach my $cid (keys(%$storehash)) {
2866: $what .= &escape($cid).'=';
1.921 raeburn 2867: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2868: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2869: }
2870: $what =~ s/\:$/&/;
2871: }
2872: $what =~ s/\&$//;
2873: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2874: } else {
2875: return $outcome;
2876: }
1.353 www 2877: }
2878:
2879: sub courseiddump {
1.921 raeburn 2880: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2881: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 raeburn 2882: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2883: my $as_hash = 1;
2884: my %returnhash;
2885: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2886: my %libserv = &all_library();
2887: foreach my $tryserver (keys(%libserv)) {
2888: if ( ( $hostidflag == 1
2889: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2890: || (!defined($hostidflag)) ) {
2891:
1.918 raeburn 2892: if (($domfilter eq '') ||
2893: (&host_domain($tryserver) eq $domfilter)) {
2894: my $rep =
2895: &reply('courseiddump:'.&host_domain($tryserver).':'.
2896: $sincefilter.':'.&escape($descfilter).':'.
2897: &escape($instcodefilter).':'.&escape($ownerfilter).
2898: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2899: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2900: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2901: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2902: my @pairs=split(/\&/,$rep);
2903: foreach my $item (@pairs) {
2904: my ($key,$value)=split(/\=/,$item,2);
2905: $key = &unescape($key);
2906: next if ($key =~ /^error: 2 /);
2907: my $result = &thaw_unescape($value);
2908: if (ref($result) eq 'HASH') {
2909: $returnhash{$key}=$result;
2910: } else {
1.921 raeburn 2911: my @responses = split(/:/,$value);
2912: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2913: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2914: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2915: }
2916: }
1.353 www 2917: }
2918: }
2919: }
2920: }
2921: return %returnhash;
2922: }
2923:
1.658 raeburn 2924: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2925:
2926: sub dcmailput {
1.685 raeburn 2927: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2928: my $status = &Apache::lonnet::critical(
1.740 www 2929: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2930: &escape($message),$server);
1.662 raeburn 2931: return $status;
2932: }
2933:
1.658 raeburn 2934: sub dcmaildump {
2935: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2936: my %returnhash=();
1.846 albertel 2937:
2938: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2939: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2940: &escape($enddate).':';
2941: my @esc_senders=map { &escape($_)} @$senders;
2942: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2943: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2944: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2945: if (($key) && ($value)) {
2946: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2947: }
2948: }
2949: }
2950: return %returnhash;
2951: }
1.662 raeburn 2952: # ---------------------------------------------------------- Domain roles
2953:
2954: sub get_domain_roles {
2955: my ($dom,$roles,$startdate,$enddate)=@_;
2956: if (undef($startdate) || $startdate eq '') {
2957: $startdate = '.';
2958: }
2959: if (undef($enddate) || $enddate eq '') {
2960: $enddate = '.';
2961: }
1.922 raeburn 2962: my $rolelist;
2963: if (ref($roles) eq 'ARRAY') {
2964: $rolelist = join(':',@{$roles});
2965: }
1.662 raeburn 2966: my %personnel = ();
1.841 albertel 2967:
2968: my %servers = &get_servers($dom,'library');
2969: foreach my $tryserver (keys(%servers)) {
2970: %{$personnel{$tryserver}}=();
2971: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2972: &escape($startdate).':'.
2973: &escape($enddate).':'.
2974: &escape($rolelist), $tryserver))) {
2975: my ($key,$value) = split(/\=/,$line,2);
2976: if (($key) && ($value)) {
2977: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2978: }
2979: }
1.662 raeburn 2980: }
2981: return %personnel;
2982: }
1.658 raeburn 2983:
1.149 www 2984: # ----------------------------------------------------------- Check out an item
2985:
1.504 albertel 2986: sub get_first_access {
2987: my ($type,$argsymb)=@_;
1.790 albertel 2988: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2989: if ($argsymb) { $symb=$argsymb; }
2990: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2991: if ($type eq 'course') {
2992: $res='course';
2993: } elsif ($type eq 'map') {
1.588 albertel 2994: $res=&symbread($map);
2995: } else {
2996: $res=$symb;
2997: }
2998: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2999: return $times{"$courseid\0$res"};
1.504 albertel 3000: }
3001:
3002: sub set_first_access {
3003: my ($type)=@_;
1.790 albertel 3004: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3005: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3006: if ($type eq 'course') {
3007: $res='course';
3008: } elsif ($type eq 'map') {
1.588 albertel 3009: $res=&symbread($map);
3010: } else {
3011: $res=$symb;
3012: }
3013: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3014: if (!$firstaccess) {
1.588 albertel 3015: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3016: }
3017: return 'already_set';
1.504 albertel 3018: }
3019:
1.149 www 3020: sub checkout {
3021: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3022: my $now=time;
3023: my $lonhost=$perlvar{'lonHostID'};
3024: my $infostr=&escape(
1.234 www 3025: 'CHECKOUTTOKEN&'.
1.149 www 3026: $tuname.'&'.
3027: $tudom.'&'.
3028: $tcrsid.'&'.
3029: $symb.'&'.
3030: $now.'&'.$ENV{'REMOTE_ADDR'});
3031: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3032: if ($token=~/^error\:/) {
1.672 albertel 3033: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3034: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3035: "</font>");
3036: return '';
3037: }
3038:
1.149 www 3039: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3040: $token=~tr/a-z/A-Z/;
3041:
1.153 www 3042: my %infohash=('resource.0.outtoken' => $token,
3043: 'resource.0.checkouttime' => $now,
3044: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3045:
3046: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3047: return '';
1.151 www 3048: } else {
1.672 albertel 3049: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3050: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3051: "</font>");
1.149 www 3052: }
3053:
3054: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3055: &escape('Checkout '.$infostr.' - '.
3056: $token)) ne 'ok') {
3057: return '';
1.151 www 3058: } else {
1.672 albertel 3059: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3060: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3061: "</font>");
1.149 www 3062: }
1.151 www 3063: return $token;
1.149 www 3064: }
3065:
3066: # ------------------------------------------------------------ Check in an item
3067:
3068: sub checkin {
3069: my $token=shift;
1.150 www 3070: my $now=time;
3071: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3072: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3073: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3074: $dtoken=~s/\W/\_/g;
1.234 www 3075: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3076: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3077:
1.154 www 3078: unless (($tuname) && ($tudom)) {
3079: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3080: return '';
3081: }
3082:
3083: unless (&allowed('mgr',$tcrsid)) {
3084: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3085: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3086: return '';
3087: }
3088:
1.153 www 3089: my %infohash=('resource.0.intoken' => $token,
3090: 'resource.0.checkintime' => $now,
3091: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3092:
3093: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3094: return '';
3095: }
3096:
3097: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3098: &escape('Checkin - '.$token)) ne 'ok') {
3099: return '';
3100: }
3101:
3102: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3103: }
3104:
3105: # --------------------------------------------- Set Expire Date for Spreadsheet
3106:
3107: sub expirespread {
3108: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3109: my $cid=$env{'request.course.id'};
1.110 www 3110: if ($cid) {
3111: my $now=time;
3112: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3113: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3114: $env{'course.'.$cid.'.num'}.
1.110 www 3115: ':nohist_expirationdates:'.
3116: &escape($key).'='.$now,
1.620 albertel 3117: $env{'course.'.$cid.'.home'})
1.110 www 3118: }
3119: return 'ok';
1.14 www 3120: }
3121:
1.109 www 3122: # ----------------------------------------------------- Devalidate Spreadsheets
3123:
3124: sub devalidate {
1.325 www 3125: my ($symb,$uname,$udom)=@_;
1.620 albertel 3126: my $cid=$env{'request.course.id'};
1.109 www 3127: if ($cid) {
1.391 matthew 3128: # delete the stored spreadsheets for
3129: # - the student level sheet of this user in course's homespace
3130: # - the assessment level sheet for this resource
3131: # for this user in user's homespace
1.553 albertel 3132: # - current conditional state info
1.325 www 3133: my $key=$uname.':'.$udom.':';
1.109 www 3134: my $status=
1.299 matthew 3135: &del('nohist_calculatedsheets',
1.391 matthew 3136: [$key.'studentcalc:'],
1.620 albertel 3137: $env{'course.'.$cid.'.domain'},
3138: $env{'course.'.$cid.'.num'})
1.133 albertel 3139: .' '.
3140: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3141: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3142: unless ($status eq 'ok ok') {
3143: &logthis('Could not devalidate spreadsheet '.
1.325 www 3144: $uname.' at '.$udom.' for '.
1.109 www 3145: $symb.': '.$status);
1.133 albertel 3146: }
1.553 albertel 3147: &delenv('user.state.'.$cid);
1.109 www 3148: }
3149: }
3150:
1.265 albertel 3151: sub get_scalar {
3152: my ($string,$end) = @_;
3153: my $value;
3154: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3155: $value = $1;
3156: } elsif ($$string =~ s/^([^&]*?)&//) {
3157: $value = $1;
3158: }
3159: return &unescape($value);
3160: }
3161:
3162: sub array2str {
3163: my (@array) = @_;
3164: my $result=&arrayref2str(\@array);
3165: $result=~s/^__ARRAY_REF__//;
3166: $result=~s/__END_ARRAY_REF__$//;
3167: return $result;
3168: }
3169:
1.204 albertel 3170: sub arrayref2str {
3171: my ($arrayref) = @_;
1.265 albertel 3172: my $result='__ARRAY_REF__';
1.204 albertel 3173: foreach my $elem (@$arrayref) {
1.265 albertel 3174: if(ref($elem) eq 'ARRAY') {
3175: $result.=&arrayref2str($elem).'&';
3176: } elsif(ref($elem) eq 'HASH') {
3177: $result.=&hashref2str($elem).'&';
3178: } elsif(ref($elem)) {
3179: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3180: } else {
3181: $result.=&escape($elem).'&';
3182: }
3183: }
3184: $result=~s/\&$//;
1.265 albertel 3185: $result .= '__END_ARRAY_REF__';
1.204 albertel 3186: return $result;
3187: }
3188:
1.168 albertel 3189: sub hash2str {
1.204 albertel 3190: my (%hash) = @_;
3191: my $result=&hashref2str(\%hash);
1.265 albertel 3192: $result=~s/^__HASH_REF__//;
3193: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3194: return $result;
3195: }
3196:
3197: sub hashref2str {
3198: my ($hashref)=@_;
1.265 albertel 3199: my $result='__HASH_REF__';
1.800 albertel 3200: foreach my $key (sort(keys(%$hashref))) {
3201: if (ref($key) eq 'ARRAY') {
3202: $result.=&arrayref2str($key).'=';
3203: } elsif (ref($key) eq 'HASH') {
3204: $result.=&hashref2str($key).'=';
3205: } elsif (ref($key)) {
1.265 albertel 3206: $result.='=';
1.800 albertel 3207: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3208: } else {
1.800 albertel 3209: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3210: }
3211:
1.800 albertel 3212: if(ref($hashref->{$key}) eq 'ARRAY') {
3213: $result.=&arrayref2str($hashref->{$key}).'&';
3214: } elsif(ref($hashref->{$key}) eq 'HASH') {
3215: $result.=&hashref2str($hashref->{$key}).'&';
3216: } elsif(ref($hashref->{$key})) {
1.265 albertel 3217: $result.='&';
1.800 albertel 3218: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3219: } else {
1.800 albertel 3220: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3221: }
3222: }
1.168 albertel 3223: $result=~s/\&$//;
1.265 albertel 3224: $result .= '__END_HASH_REF__';
1.168 albertel 3225: return $result;
3226: }
3227:
3228: sub str2hash {
1.265 albertel 3229: my ($string)=@_;
3230: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3231: return %$hash;
3232: }
3233:
3234: sub str2hashref {
1.168 albertel 3235: my ($string) = @_;
1.265 albertel 3236:
3237: my %hash;
3238:
3239: if($string !~ /^__HASH_REF__/) {
3240: if (! ($string eq '' || !defined($string))) {
3241: $hash{'error'}='Not hash reference';
3242: }
3243: return (\%hash, $string);
3244: }
3245:
3246: $string =~ s/^__HASH_REF__//;
3247:
3248: while($string !~ /^__END_HASH_REF__/) {
3249: #key
3250: my $key='';
3251: if($string =~ /^__HASH_REF__/) {
3252: ($key, $string)=&str2hashref($string);
3253: if(defined($key->{'error'})) {
3254: $hash{'error'}='Bad data';
3255: return (\%hash, $string);
3256: }
3257: } elsif($string =~ /^__ARRAY_REF__/) {
3258: ($key, $string)=&str2arrayref($string);
3259: if($key->[0] eq 'Array reference error') {
3260: $hash{'error'}='Bad data';
3261: return (\%hash, $string);
3262: }
3263: } else {
3264: $string =~ s/^(.*?)=//;
1.267 albertel 3265: $key=&unescape($1);
1.265 albertel 3266: }
3267: $string =~ s/^=//;
3268:
3269: #value
3270: my $value='';
3271: if($string =~ /^__HASH_REF__/) {
3272: ($value, $string)=&str2hashref($string);
3273: if(defined($value->{'error'})) {
3274: $hash{'error'}='Bad data';
3275: return (\%hash, $string);
3276: }
3277: } elsif($string =~ /^__ARRAY_REF__/) {
3278: ($value, $string)=&str2arrayref($string);
3279: if($value->[0] eq 'Array reference error') {
3280: $hash{'error'}='Bad data';
3281: return (\%hash, $string);
3282: }
3283: } else {
3284: $value=&get_scalar(\$string,'__END_HASH_REF__');
3285: }
3286: $string =~ s/^&//;
3287:
3288: $hash{$key}=$value;
1.204 albertel 3289: }
1.265 albertel 3290:
3291: $string =~ s/^__END_HASH_REF__//;
3292:
3293: return (\%hash, $string);
1.204 albertel 3294: }
3295:
3296: sub str2array {
1.265 albertel 3297: my ($string)=@_;
3298: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3299: return @$array;
3300: }
3301:
3302: sub str2arrayref {
1.204 albertel 3303: my ($string) = @_;
1.265 albertel 3304: my @array;
3305:
3306: if($string !~ /^__ARRAY_REF__/) {
3307: if (! ($string eq '' || !defined($string))) {
3308: $array[0]='Array reference error';
3309: }
3310: return (\@array, $string);
3311: }
3312:
3313: $string =~ s/^__ARRAY_REF__//;
3314:
3315: while($string !~ /^__END_ARRAY_REF__/) {
3316: my $value='';
3317: if($string =~ /^__HASH_REF__/) {
3318: ($value, $string)=&str2hashref($string);
3319: if(defined($value->{'error'})) {
3320: $array[0] ='Array reference error';
3321: return (\@array, $string);
3322: }
3323: } elsif($string =~ /^__ARRAY_REF__/) {
3324: ($value, $string)=&str2arrayref($string);
3325: if($value->[0] eq 'Array reference error') {
3326: $array[0] ='Array reference error';
3327: return (\@array, $string);
3328: }
3329: } else {
3330: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3331: }
3332: $string =~ s/^&//;
3333:
3334: push(@array, $value);
1.191 harris41 3335: }
1.265 albertel 3336:
3337: $string =~ s/^__END_ARRAY_REF__//;
3338:
3339: return (\@array, $string);
1.168 albertel 3340: }
3341:
1.167 albertel 3342: # -------------------------------------------------------------------Temp Store
3343:
1.168 albertel 3344: sub tmpreset {
3345: my ($symb,$namespace,$domain,$stuname) = @_;
3346: if (!$symb) {
3347: $symb=&symbread();
1.620 albertel 3348: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3349: }
3350: $symb=escape($symb);
3351:
1.620 albertel 3352: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3353: $namespace=~s/\//\_/g;
3354: $namespace=~s/\W//g;
3355:
1.620 albertel 3356: if (!$domain) { $domain=$env{'user.domain'}; }
3357: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3358: if ($domain eq 'public' && $stuname eq 'public') {
3359: $stuname=$ENV{'REMOTE_ADDR'};
3360: }
1.168 albertel 3361: my $path=$perlvar{'lonDaemons'}.'/tmp';
3362: my %hash;
3363: if (tie(%hash,'GDBM_File',
3364: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3365: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3366: foreach my $key (keys %hash) {
1.180 albertel 3367: if ($key=~ /:$symb/) {
1.168 albertel 3368: delete($hash{$key});
3369: }
3370: }
3371: }
3372: }
3373:
1.167 albertel 3374: sub tmpstore {
1.168 albertel 3375: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3376:
3377: if (!$symb) {
3378: $symb=&symbread();
1.620 albertel 3379: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3380: }
3381: $symb=escape($symb);
3382:
3383: if (!$namespace) {
3384: # I don't think we would ever want to store this for a course.
3385: # it seems this will only be used if we don't have a course.
1.620 albertel 3386: #$namespace=$env{'request.course.id'};
1.168 albertel 3387: #if (!$namespace) {
1.620 albertel 3388: $namespace=$env{'request.state'};
1.168 albertel 3389: #}
3390: }
3391: $namespace=~s/\//\_/g;
3392: $namespace=~s/\W//g;
1.620 albertel 3393: if (!$domain) { $domain=$env{'user.domain'}; }
3394: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3395: if ($domain eq 'public' && $stuname eq 'public') {
3396: $stuname=$ENV{'REMOTE_ADDR'};
3397: }
1.168 albertel 3398: my $now=time;
3399: my %hash;
3400: my $path=$perlvar{'lonDaemons'}.'/tmp';
3401: if (tie(%hash,'GDBM_File',
3402: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3403: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3404: $hash{"version:$symb"}++;
3405: my $version=$hash{"version:$symb"};
3406: my $allkeys='';
3407: foreach my $key (keys(%$storehash)) {
3408: $allkeys.=$key.':';
1.591 albertel 3409: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3410: }
3411: $hash{"$version:$symb:timestamp"}=$now;
3412: $allkeys.='timestamp';
3413: $hash{"$version:keys:$symb"}=$allkeys;
3414: if (untie(%hash)) {
3415: return 'ok';
3416: } else {
3417: return "error:$!";
3418: }
3419: } else {
3420: return "error:$!";
3421: }
3422: }
1.167 albertel 3423:
1.168 albertel 3424: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3425:
1.168 albertel 3426: sub tmprestore {
3427: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3428:
1.168 albertel 3429: if (!$symb) {
3430: $symb=&symbread();
1.620 albertel 3431: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3432: }
3433: $symb=escape($symb);
3434:
1.620 albertel 3435: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3436:
1.620 albertel 3437: if (!$domain) { $domain=$env{'user.domain'}; }
3438: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3439: if ($domain eq 'public' && $stuname eq 'public') {
3440: $stuname=$ENV{'REMOTE_ADDR'};
3441: }
1.168 albertel 3442: my %returnhash;
3443: $namespace=~s/\//\_/g;
3444: $namespace=~s/\W//g;
3445: my %hash;
3446: my $path=$perlvar{'lonDaemons'}.'/tmp';
3447: if (tie(%hash,'GDBM_File',
3448: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3449: &GDBM_READER(),0640)) {
1.168 albertel 3450: my $version=$hash{"version:$symb"};
3451: $returnhash{'version'}=$version;
3452: my $scope;
3453: for ($scope=1;$scope<=$version;$scope++) {
3454: my $vkeys=$hash{"$scope:keys:$symb"};
3455: my @keys=split(/:/,$vkeys);
3456: my $key;
3457: $returnhash{"$scope:keys"}=$vkeys;
3458: foreach $key (@keys) {
1.591 albertel 3459: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3460: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3461: }
3462: }
1.168 albertel 3463: if (!(untie(%hash))) {
3464: return "error:$!";
3465: }
3466: } else {
3467: return "error:$!";
3468: }
3469: return %returnhash;
1.167 albertel 3470: }
3471:
1.9 www 3472: # ----------------------------------------------------------------------- Store
3473:
3474: sub store {
1.124 www 3475: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3476: my $home='';
3477:
1.168 albertel 3478: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3479:
1.213 www 3480: $symb=&symbclean($symb);
1.122 albertel 3481: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3482:
1.620 albertel 3483: if (!$domain) { $domain=$env{'user.domain'}; }
3484: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3485:
3486: &devalidate($symb,$stuname,$domain);
1.109 www 3487:
3488: $symb=escape($symb);
1.187 www 3489: if (!$namespace) {
1.620 albertel 3490: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3491: return '';
3492: }
3493: }
1.620 albertel 3494: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3495:
3496: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3497: $$storehash{'host'}=$perlvar{'lonHostID'};
3498:
1.12 www 3499: my $namevalue='';
1.800 albertel 3500: foreach my $key (keys(%$storehash)) {
3501: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3502: }
1.12 www 3503: $namevalue=~s/\&$//;
1.187 www 3504: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3505: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3506: }
3507:
1.47 www 3508: # -------------------------------------------------------------- Critical Store
3509:
3510: sub cstore {
1.124 www 3511: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3512: my $home='';
3513:
1.168 albertel 3514: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3515:
1.213 www 3516: $symb=&symbclean($symb);
1.122 albertel 3517: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3518:
1.620 albertel 3519: if (!$domain) { $domain=$env{'user.domain'}; }
3520: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3521:
3522: &devalidate($symb,$stuname,$domain);
1.109 www 3523:
3524: $symb=escape($symb);
1.187 www 3525: if (!$namespace) {
1.620 albertel 3526: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3527: return '';
3528: }
3529: }
1.620 albertel 3530: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3531:
3532: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3533: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3534:
1.47 www 3535: my $namevalue='';
1.800 albertel 3536: foreach my $key (keys(%$storehash)) {
3537: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3538: }
1.47 www 3539: $namevalue=~s/\&$//;
1.187 www 3540: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3541: return critical
3542: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3543: }
3544:
1.9 www 3545: # --------------------------------------------------------------------- Restore
3546:
3547: sub restore {
1.124 www 3548: my ($symb,$namespace,$domain,$stuname) = @_;
3549: my $home='';
3550:
1.168 albertel 3551: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3552:
1.122 albertel 3553: if (!$symb) {
3554: unless ($symb=escape(&symbread())) { return ''; }
3555: } else {
1.213 www 3556: $symb=&escape(&symbclean($symb));
1.122 albertel 3557: }
1.188 www 3558: if (!$namespace) {
1.620 albertel 3559: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3560: return '';
3561: }
3562: }
1.620 albertel 3563: if (!$domain) { $domain=$env{'user.domain'}; }
3564: if (!$stuname) { $stuname=$env{'user.name'}; }
3565: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3566: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3567:
1.12 www 3568: my %returnhash=();
1.800 albertel 3569: foreach my $line (split(/\&/,$answer)) {
3570: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3571: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3572: }
1.75 www 3573: my $version;
3574: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3575: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3576: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3577: }
1.75 www 3578: }
1.13 www 3579: return %returnhash;
1.34 www 3580: }
3581:
3582: # ---------------------------------------------------------- Course Description
3583:
3584: sub coursedescription {
1.731 albertel 3585: my ($courseid,$args)=@_;
1.34 www 3586: $courseid=~s/^\///;
1.49 www 3587: $courseid=~s/\_/\//g;
1.34 www 3588: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3589: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3590: my $normalid=$cdomain.'_'.$cnum;
3591: # need to always cache even if we get errors otherwise we keep
3592: # trying and trying and trying to get the course description.
3593: my %envhash=();
3594: my %returnhash=();
1.731 albertel 3595:
3596: my $expiretime=600;
3597: if ($env{'request.course.id'} eq $normalid) {
3598: $expiretime=120;
3599: }
3600:
3601: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3602: if (!$args->{'freshen_cache'}
3603: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3604: foreach my $key (keys(%env)) {
3605: next if ($key !~ /^\Q$prefix\E(.*)/);
3606: my ($setting) = $1;
3607: $returnhash{$setting} = $env{$key};
3608: }
3609: return %returnhash;
3610: }
3611:
3612: # get the data agin
3613: if (!$args->{'one_time'}) {
3614: $envhash{'course.'.$normalid.'.last_cache'}=time;
3615: }
1.811 albertel 3616:
1.34 www 3617: if ($chome ne 'no_host') {
1.302 albertel 3618: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3619: if (!exists($returnhash{'con_lost'})) {
3620: $returnhash{'home'}= $chome;
3621: $returnhash{'domain'} = $cdomain;
3622: $returnhash{'num'} = $cnum;
1.741 raeburn 3623: if (!defined($returnhash{'type'})) {
3624: $returnhash{'type'} = 'Course';
3625: }
1.130 albertel 3626: while (my ($name,$value) = each %returnhash) {
1.53 www 3627: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3628: }
1.270 www 3629: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3630: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3631: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3632: $envhash{'course.'.$normalid.'.home'}=$chome;
3633: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3634: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3635: }
3636: }
1.731 albertel 3637: if (!$args->{'one_time'}) {
1.949 raeburn 3638: &appenv(\%envhash);
1.731 albertel 3639: }
1.302 albertel 3640: return %returnhash;
1.461 www 3641: }
3642:
3643: # -------------------------------------------------See if a user is privileged
3644:
3645: sub privileged {
3646: my ($username,$domain)=@_;
3647: my $rolesdump=&reply("dump:$domain:$username:roles",
3648: &homeserver($username,$domain));
3649: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3650: my $now=time;
3651: if ($rolesdump ne '') {
1.800 albertel 3652: foreach my $entry (split(/&/,$rolesdump)) {
3653: if ($entry!~/^rolesdef_/) {
3654: my ($area,$role)=split(/=/,$entry);
1.461 www 3655: $area=~s/\_\w\w$//;
3656: my ($trole,$tend,$tstart)=split(/_/,$role);
3657: if (($trole eq 'dc') || ($trole eq 'su')) {
3658: my $active=1;
3659: if ($tend) {
3660: if ($tend<$now) { $active=0; }
3661: }
3662: if ($tstart) {
3663: if ($tstart>$now) { $active=0; }
3664: }
3665: if ($active) { return 1; }
3666: }
3667: }
3668: }
3669: }
3670: return 0;
1.9 www 3671: }
1.1 albertel 3672:
1.103 harris41 3673: # -------------------------------------------------------- Get user privileges
1.11 www 3674:
3675: sub rolesinit {
3676: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3677: my %userroles;
1.11 www 3678: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3679: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3680: my %allroles=();
1.678 raeburn 3681: my %allgroups=();
1.11 www 3682: my $now=time;
1.966 raeburn 3683: %userroles = ('user.login.time' => $now);
1.678 raeburn 3684: my $group_privs;
1.11 www 3685:
3686: if ($rolesdump ne '') {
1.800 albertel 3687: foreach my $entry (split(/&/,$rolesdump)) {
3688: if ($entry!~/^rolesdef_/) {
3689: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3690: $area=~s/\_\w\w$//;
1.678 raeburn 3691: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3692: if ($role=~/^cr/) {
1.807 albertel 3693: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3694: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3695: ($tend,$tstart)=split('_',$trest);
3696: } else {
3697: $trole=$role;
3698: }
1.678 raeburn 3699: } elsif ($role =~ m|^gr/|) {
3700: ($trole,$tend,$tstart) = split(/_/,$role);
3701: ($trole,$group_privs) = split(/\//,$trole);
3702: $group_privs = &unescape($group_privs);
1.587 albertel 3703: } else {
3704: ($trole,$tend,$tstart)=split(/_/,$role);
3705: }
1.743 albertel 3706: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3707: $username);
3708: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3709: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3710: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3711: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3712: my $spec=$trole.'.'.$area;
3713: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3714: if ($trole =~ /^cr\//) {
1.567 raeburn 3715: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3716: } elsif ($trole eq 'gr') {
3717: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3718: } else {
1.567 raeburn 3719: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3720: }
1.12 www 3721: }
1.662 raeburn 3722: }
1.191 harris41 3723: }
1.743 albertel 3724: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3725: $userroles{'user.adv'} = $adv;
3726: $userroles{'user.author'} = $author;
1.620 albertel 3727: $env{'user.adv'}=$adv;
1.11 www 3728: }
1.743 albertel 3729: return \%userroles;
1.11 www 3730: }
3731:
1.567 raeburn 3732: sub set_arearole {
3733: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3734: # log the associated role with the area
3735: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3736: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3737: }
3738:
3739: sub custom_roleprivs {
3740: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3741: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3742: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3743: if (&hostname($homsvr) ne '') {
1.567 raeburn 3744: my ($rdummy,$roledef)=
3745: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3746: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3747: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3748: if (defined($syspriv)) {
3749: $$allroles{'cm./'}.=':'.$syspriv;
3750: $$allroles{$spec.'./'}.=':'.$syspriv;
3751: }
3752: if ($tdomain ne '') {
3753: if (defined($dompriv)) {
3754: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3755: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3756: }
3757: if (($trest ne '') && (defined($coursepriv))) {
3758: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3759: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3760: }
3761: }
3762: }
3763: }
3764: }
3765:
1.678 raeburn 3766: sub group_roleprivs {
3767: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3768: my $access = 1;
3769: my $now = time;
3770: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3771: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3772: if ($access) {
1.811 albertel 3773: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3774: $$allgroups{$course}{$group} .=':'.$group_privs;
3775: }
3776: }
1.567 raeburn 3777:
3778: sub standard_roleprivs {
3779: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3780: if (defined($pr{$trole.':s'})) {
3781: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3782: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3783: }
3784: if ($tdomain ne '') {
3785: if (defined($pr{$trole.':d'})) {
3786: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3787: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3788: }
3789: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3790: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3791: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3792: }
3793: }
3794: }
3795:
3796: sub set_userprivs {
1.678 raeburn 3797: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3798: my $author=0;
3799: my $adv=0;
1.678 raeburn 3800: my %grouproles = ();
3801: if (keys(%{$allgroups}) > 0) {
3802: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3803: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3804: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3805: $trole = $1;
3806: $area = $2;
1.681 raeburn 3807: $sec = $3;
3808: $extendedarea = $area.$sec;
3809: if (exists($$allgroups{$area})) {
3810: foreach my $group (keys(%{$$allgroups{$area}})) {
3811: my $spec = $trole.'.'.$extendedarea;
3812: $grouproles{$spec.'.'.$area.'/'.$group} =
3813: $$allgroups{$area}{$group};
1.678 raeburn 3814: }
3815: }
3816: }
3817: }
3818: }
1.800 albertel 3819: foreach my $group (keys(%grouproles)) {
3820: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3821: }
1.800 albertel 3822: foreach my $role (keys(%{$allroles})) {
3823: my %thesepriv;
1.941 raeburn 3824: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3825: foreach my $item (split(/:/,$$allroles{$role})) {
3826: if ($item ne '') {
3827: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3828: if ($restrictions eq '') {
3829: $thesepriv{$privilege}='F';
3830: } elsif ($thesepriv{$privilege} ne 'F') {
3831: $thesepriv{$privilege}.=$restrictions;
3832: }
3833: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3834: }
3835: }
3836: my $thesestr='';
1.800 albertel 3837: foreach my $priv (keys(%thesepriv)) {
3838: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3839: }
3840: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3841: }
3842: return ($author,$adv);
3843: }
3844:
1.12 www 3845: # --------------------------------------------------------------- get interface
3846:
3847: sub get {
1.131 albertel 3848: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3849: my $items='';
1.800 albertel 3850: foreach my $item (@$storearr) {
3851: $items.=&escape($item).'&';
1.191 harris41 3852: }
1.12 www 3853: $items=~s/\&$//;
1.620 albertel 3854: if (!$udomain) { $udomain=$env{'user.domain'}; }
3855: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3856: my $uhome=&homeserver($uname,$udomain);
3857:
1.133 albertel 3858: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3859: my @pairs=split(/\&/,$rep);
1.273 albertel 3860: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3861: return @pairs;
3862: }
1.15 www 3863: my %returnhash=();
1.42 www 3864: my $i=0;
1.800 albertel 3865: foreach my $item (@$storearr) {
3866: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3867: $i++;
1.191 harris41 3868: }
1.15 www 3869: return %returnhash;
1.27 www 3870: }
3871:
3872: # --------------------------------------------------------------- del interface
3873:
3874: sub del {
1.133 albertel 3875: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3876: my $items='';
1.800 albertel 3877: foreach my $item (@$storearr) {
3878: $items.=&escape($item).'&';
1.191 harris41 3879: }
1.27 www 3880: $items=~s/\&$//;
1.620 albertel 3881: if (!$udomain) { $udomain=$env{'user.domain'}; }
3882: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3883: my $uhome=&homeserver($uname,$udomain);
3884:
3885: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3886: }
3887:
3888: # -------------------------------------------------------------- dump interface
3889:
3890: sub dump {
1.755 albertel 3891: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3892: if (!$udomain) { $udomain=$env{'user.domain'}; }
3893: if (!$uname) { $uname=$env{'user.name'}; }
3894: my $uhome=&homeserver($uname,$udomain);
3895: if ($regexp) {
3896: $regexp=&escape($regexp);
3897: } else {
3898: $regexp='.';
3899: }
3900: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3901: my @pairs=split(/\&/,$rep);
3902: my %returnhash=();
3903: foreach my $item (@pairs) {
3904: my ($key,$value)=split(/=/,$item,2);
3905: $key = &unescape($key);
3906: next if ($key =~ /^error: 2 /);
3907: $returnhash{$key}=&thaw_unescape($value);
3908: }
3909: return %returnhash;
1.407 www 3910: }
3911:
1.717 albertel 3912: # --------------------------------------------------------- dumpstore interface
3913:
3914: sub dumpstore {
3915: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3916: if (!$udomain) { $udomain=$env{'user.domain'}; }
3917: if (!$uname) { $uname=$env{'user.name'}; }
3918: my $uhome=&homeserver($uname,$udomain);
3919: if ($regexp) {
3920: $regexp=&escape($regexp);
3921: } else {
3922: $regexp='.';
3923: }
3924: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3925: my @pairs=split(/\&/,$rep);
3926: my %returnhash=();
3927: foreach my $item (@pairs) {
3928: my ($key,$value)=split(/=/,$item,2);
3929: next if ($key =~ /^error: 2 /);
3930: $returnhash{$key}=&thaw_unescape($value);
3931: }
3932: return %returnhash;
1.717 albertel 3933: }
3934:
1.407 www 3935: # -------------------------------------------------------------- keys interface
3936:
3937: sub getkeys {
3938: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3939: if (!$udomain) { $udomain=$env{'user.domain'}; }
3940: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3941: my $uhome=&homeserver($uname,$udomain);
3942: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3943: my @keyarray=();
1.800 albertel 3944: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3945: next if ($key =~ /^error: 2 /);
1.800 albertel 3946: push(@keyarray,&unescape($key));
1.407 www 3947: }
3948: return @keyarray;
1.318 matthew 3949: }
3950:
1.319 matthew 3951: # --------------------------------------------------------------- currentdump
3952: sub currentdump {
1.328 matthew 3953: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3954: $courseid = $env{'request.course.id'} if (! defined($courseid));
3955: $sdom = $env{'user.domain'} if (! defined($sdom));
3956: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3957: my $uhome = &homeserver($sname,$sdom);
3958: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3959: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3960: #
1.318 matthew 3961: my %returnhash=();
1.319 matthew 3962: #
3963: if ($rep eq "unknown_cmd") {
3964: # an old lond will not know currentdump
3965: # Do a dump and make it look like a currentdump
1.822 albertel 3966: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3967: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3968: my %hash = @tmp;
3969: @tmp=();
1.424 matthew 3970: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3971: } else {
3972: my @pairs=split(/\&/,$rep);
1.800 albertel 3973: foreach my $pair (@pairs) {
3974: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3975: my ($symb,$param) = split(/:/,$key);
3976: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3977: &thaw_unescape($value);
1.319 matthew 3978: }
1.191 harris41 3979: }
1.12 www 3980: return %returnhash;
1.424 matthew 3981: }
3982:
3983: sub convert_dump_to_currentdump{
3984: my %hash = %{shift()};
3985: my %returnhash;
3986: # Code ripped from lond, essentially. The only difference
3987: # here is the unescaping done by lonnet::dump(). Conceivably
3988: # we might run in to problems with parameter names =~ /^v\./
3989: while (my ($key,$value) = each(%hash)) {
3990: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3991: $symb = &unescape($symb);
3992: $param = &unescape($param);
1.424 matthew 3993: next if ($v eq 'version' || $symb eq 'keys');
3994: next if (exists($returnhash{$symb}) &&
3995: exists($returnhash{$symb}->{$param}) &&
3996: $returnhash{$symb}->{'v.'.$param} > $v);
3997: $returnhash{$symb}->{$param}=$value;
3998: $returnhash{$symb}->{'v.'.$param}=$v;
3999: }
4000: #
4001: # Remove all of the keys in the hashes which keep track of
4002: # the version of the parameter.
4003: while (my ($symb,$param_hash) = each(%returnhash)) {
4004: # use a foreach because we are going to delete from the hash.
4005: foreach my $key (keys(%$param_hash)) {
4006: delete($param_hash->{$key}) if ($key =~ /^v\./);
4007: }
4008: }
4009: return \%returnhash;
1.12 www 4010: }
4011:
1.627 albertel 4012: # ------------------------------------------------------ critical inc interface
4013:
4014: sub cinc {
4015: return &inc(@_,'critical');
4016: }
4017:
1.449 matthew 4018: # --------------------------------------------------------------- inc interface
4019:
4020: sub inc {
1.627 albertel 4021: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4022: if (!$udomain) { $udomain=$env{'user.domain'}; }
4023: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4024: my $uhome=&homeserver($uname,$udomain);
4025: my $items='';
4026: if (! ref($store)) {
4027: # got a single value, so use that instead
4028: $items = &escape($store).'=&';
4029: } elsif (ref($store) eq 'SCALAR') {
4030: $items = &escape($$store).'=&';
4031: } elsif (ref($store) eq 'ARRAY') {
4032: $items = join('=&',map {&escape($_);} @{$store});
4033: } elsif (ref($store) eq 'HASH') {
4034: while (my($key,$value) = each(%{$store})) {
4035: $items.= &escape($key).'='.&escape($value).'&';
4036: }
4037: }
4038: $items=~s/\&$//;
1.627 albertel 4039: if ($critical) {
4040: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4041: } else {
4042: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4043: }
1.449 matthew 4044: }
4045:
1.12 www 4046: # --------------------------------------------------------------- put interface
4047:
4048: sub put {
1.134 albertel 4049: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4050: if (!$udomain) { $udomain=$env{'user.domain'}; }
4051: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4052: my $uhome=&homeserver($uname,$udomain);
1.12 www 4053: my $items='';
1.800 albertel 4054: foreach my $item (keys(%$storehash)) {
4055: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4056: }
1.12 www 4057: $items=~s/\&$//;
1.134 albertel 4058: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4059: }
4060:
1.631 albertel 4061: # ------------------------------------------------------------ newput interface
4062:
4063: sub newput {
4064: my ($namespace,$storehash,$udomain,$uname)=@_;
4065: if (!$udomain) { $udomain=$env{'user.domain'}; }
4066: if (!$uname) { $uname=$env{'user.name'}; }
4067: my $uhome=&homeserver($uname,$udomain);
4068: my $items='';
4069: foreach my $key (keys(%$storehash)) {
4070: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4071: }
4072: $items=~s/\&$//;
4073: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4074: }
4075:
4076: # --------------------------------------------------------- putstore interface
4077:
1.524 raeburn 4078: sub putstore {
1.715 albertel 4079: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4080: if (!$udomain) { $udomain=$env{'user.domain'}; }
4081: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4082: my $uhome=&homeserver($uname,$udomain);
4083: my $items='';
1.715 albertel 4084: foreach my $key (keys(%$storehash)) {
4085: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4086: }
1.715 albertel 4087: $items=~s/\&$//;
1.716 albertel 4088: my $esc_symb=&escape($symb);
4089: my $esc_v=&escape($version);
1.715 albertel 4090: my $reply =
1.716 albertel 4091: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4092: $uhome);
4093: if ($reply eq 'unknown_cmd') {
1.716 albertel 4094: # gfall back to way things use to be done
1.715 albertel 4095: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4096: $uname);
1.524 raeburn 4097: }
1.715 albertel 4098: return $reply;
4099: }
4100:
4101: sub old_putstore {
1.716 albertel 4102: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4103: if (!$udomain) { $udomain=$env{'user.domain'}; }
4104: if (!$uname) { $uname=$env{'user.name'}; }
4105: my $uhome=&homeserver($uname,$udomain);
4106: my %newstorehash;
1.800 albertel 4107: foreach my $item (keys(%$storehash)) {
4108: my $key = $version.':'.&escape($symb).':'.$item;
4109: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4110: }
4111: my $items='';
4112: my %allitems = ();
1.800 albertel 4113: foreach my $item (keys(%newstorehash)) {
4114: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4115: my $key = $1.':keys:'.$2;
4116: $allitems{$key} .= $3.':';
4117: }
1.800 albertel 4118: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4119: }
1.800 albertel 4120: foreach my $item (keys(%allitems)) {
4121: $allitems{$item} =~ s/\:$//;
4122: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4123: }
4124: $items=~s/\&$//;
4125: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4126: }
4127:
1.47 www 4128: # ------------------------------------------------------ critical put interface
4129:
4130: sub cput {
1.134 albertel 4131: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4132: if (!$udomain) { $udomain=$env{'user.domain'}; }
4133: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4134: my $uhome=&homeserver($uname,$udomain);
1.47 www 4135: my $items='';
1.800 albertel 4136: foreach my $item (keys(%$storehash)) {
4137: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4138: }
1.47 www 4139: $items=~s/\&$//;
1.134 albertel 4140: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4141: }
4142:
4143: # -------------------------------------------------------------- eget interface
4144:
4145: sub eget {
1.133 albertel 4146: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4147: my $items='';
1.800 albertel 4148: foreach my $item (@$storearr) {
4149: $items.=&escape($item).'&';
1.191 harris41 4150: }
1.12 www 4151: $items=~s/\&$//;
1.620 albertel 4152: if (!$udomain) { $udomain=$env{'user.domain'}; }
4153: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4154: my $uhome=&homeserver($uname,$udomain);
4155: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4156: my @pairs=split(/\&/,$rep);
4157: my %returnhash=();
1.42 www 4158: my $i=0;
1.800 albertel 4159: foreach my $item (@$storearr) {
4160: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4161: $i++;
1.191 harris41 4162: }
1.12 www 4163: return %returnhash;
4164: }
4165:
1.667 albertel 4166: # ------------------------------------------------------------ tmpput interface
4167: sub tmpput {
1.802 raeburn 4168: my ($storehash,$server,$context)=@_;
1.667 albertel 4169: my $items='';
1.800 albertel 4170: foreach my $item (keys(%$storehash)) {
4171: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4172: }
4173: $items=~s/\&$//;
1.802 raeburn 4174: if (defined($context)) {
4175: $items .= ':'.&escape($context);
4176: }
1.667 albertel 4177: return &reply("tmpput:$items",$server);
4178: }
4179:
4180: # ------------------------------------------------------------ tmpget interface
4181: sub tmpget {
1.688 albertel 4182: my ($token,$server)=@_;
4183: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4184: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4185: my %returnhash;
4186: foreach my $item (split(/\&/,$rep)) {
4187: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4188: next if ($key =~ /^error: 2 /);
1.667 albertel 4189: $returnhash{&unescape($key)}=&thaw_unescape($value);
4190: }
4191: return %returnhash;
4192: }
4193:
1.688 albertel 4194: # ------------------------------------------------------------ tmpget interface
4195: sub tmpdel {
4196: my ($token,$server)=@_;
4197: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4198: return &reply("tmpdel:$token",$server);
4199: }
4200:
1.765 albertel 4201: # -------------------------------------------------- portfolio access checking
4202:
4203: sub portfolio_access {
1.766 albertel 4204: my ($requrl) = @_;
1.765 albertel 4205: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4206: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4207: if ($result) {
4208: my %setters;
4209: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4210: my ($startblock,$endblock) =
4211: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4212: if ($startblock && $endblock) {
4213: return 'B';
4214: }
4215: } else {
4216: my ($startblock,$endblock) =
4217: &Apache::loncommon::blockcheck(\%setters,'port');
4218: if ($startblock && $endblock) {
4219: return 'B';
4220: }
4221: }
4222: }
1.765 albertel 4223: if ($result eq 'ok') {
1.766 albertel 4224: return 'F';
1.765 albertel 4225: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4226: return 'A';
1.765 albertel 4227: }
1.766 albertel 4228: return '';
1.765 albertel 4229: }
4230:
4231: sub get_portfolio_access {
1.767 albertel 4232: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4233:
4234: if (!ref($access_hash)) {
4235: my $current_perms = &get_portfile_permissions($udom,$unum);
4236: my %access_controls = &get_access_controls($current_perms,$group,
4237: $file_name);
4238: $access_hash = $access_controls{$file_name};
4239: }
4240:
1.765 albertel 4241: my ($public,$guest,@domains,@users,@courses,@groups);
4242: my $now = time;
4243: if (ref($access_hash) eq 'HASH') {
4244: foreach my $key (keys(%{$access_hash})) {
4245: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4246: if ($start > $now) {
4247: next;
4248: }
4249: if ($end && $end<$now) {
4250: next;
4251: }
4252: if ($scope eq 'public') {
4253: $public = $key;
4254: last;
4255: } elsif ($scope eq 'guest') {
4256: $guest = $key;
4257: } elsif ($scope eq 'domains') {
4258: push(@domains,$key);
4259: } elsif ($scope eq 'users') {
4260: push(@users,$key);
4261: } elsif ($scope eq 'course') {
4262: push(@courses,$key);
4263: } elsif ($scope eq 'group') {
4264: push(@groups,$key);
4265: }
4266: }
4267: if ($public) {
4268: return 'ok';
4269: }
4270: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4271: if ($guest) {
4272: return $guest;
4273: }
4274: } else {
4275: if (@domains > 0) {
4276: foreach my $domkey (@domains) {
4277: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4278: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4279: return 'ok';
4280: }
4281: }
4282: }
4283: }
4284: if (@users > 0) {
4285: foreach my $userkey (@users) {
1.865 raeburn 4286: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4287: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4288: if (ref($item) eq 'HASH') {
4289: if (($item->{'uname'} eq $env{'user.name'}) &&
4290: ($item->{'udom'} eq $env{'user.domain'})) {
4291: return 'ok';
4292: }
4293: }
4294: }
4295: }
1.765 albertel 4296: }
4297: }
4298: my %roleshash;
4299: my @courses_and_groups = @courses;
4300: push(@courses_and_groups,@groups);
4301: if (@courses_and_groups > 0) {
4302: my (%allgroups,%allroles);
4303: my ($start,$end,$role,$sec,$group);
4304: foreach my $envkey (%env) {
1.811 albertel 4305: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4306: my $cid = $2.'_'.$3;
4307: if ($1 eq 'gr') {
4308: $group = $4;
4309: $allgroups{$cid}{$group} = $env{$envkey};
4310: } else {
4311: if ($4 eq '') {
4312: $sec = 'none';
4313: } else {
4314: $sec = $4;
4315: }
4316: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4317: }
1.811 albertel 4318: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4319: my $cid = $2.'_'.$3;
4320: if ($4 eq '') {
4321: $sec = 'none';
4322: } else {
4323: $sec = $4;
4324: }
4325: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4326: }
4327: }
4328: if (keys(%allroles) == 0) {
4329: return;
4330: }
4331: foreach my $key (@courses_and_groups) {
4332: my %content = %{$$access_hash{$key}};
4333: my $cnum = $content{'number'};
4334: my $cdom = $content{'domain'};
4335: my $cid = $cdom.'_'.$cnum;
4336: if (!exists($allroles{$cid})) {
4337: next;
4338: }
4339: foreach my $role_id (keys(%{$content{'roles'}})) {
4340: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4341: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4342: my @status = @{$content{'roles'}{$role_id}{'access'}};
4343: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4344: foreach my $role (keys(%{$allroles{$cid}})) {
4345: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4346: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4347: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4348: if (grep/^all$/,@sections) {
4349: return 'ok';
4350: } else {
4351: if (grep/^$sec$/,@sections) {
4352: return 'ok';
4353: }
4354: }
4355: }
4356: }
4357: if (keys(%{$allgroups{$cid}}) == 0) {
4358: if (grep/^none$/,@groups) {
4359: return 'ok';
4360: }
4361: } else {
4362: if (grep/^all$/,@groups) {
4363: return 'ok';
4364: }
4365: foreach my $group (keys(%{$allgroups{$cid}})) {
4366: if (grep/^$group$/,@groups) {
4367: return 'ok';
4368: }
4369: }
4370: }
4371: }
4372: }
4373: }
4374: }
4375: }
4376: if ($guest) {
4377: return $guest;
4378: }
4379: }
4380: }
4381: return;
4382: }
4383:
4384: sub course_group_datechecker {
4385: my ($dates,$now,$status) = @_;
4386: my ($start,$end) = split(/\./,$dates);
4387: if (!$start && !$end) {
4388: return 'ok';
4389: }
4390: if (grep/^active$/,@{$status}) {
4391: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4392: return 'ok';
4393: }
4394: }
4395: if (grep/^previous$/,@{$status}) {
4396: if ($end > $now ) {
4397: return 'ok';
4398: }
4399: }
4400: if (grep/^future$/,@{$status}) {
4401: if ($start > $now) {
4402: return 'ok';
4403: }
4404: }
4405: return;
4406: }
4407:
4408: sub parse_portfolio_url {
4409: my ($url) = @_;
4410:
4411: my ($type,$udom,$unum,$group,$file_name);
4412:
1.823 albertel 4413: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4414: $type = 1;
4415: $udom = $1;
4416: $unum = $2;
4417: $file_name = $3;
1.823 albertel 4418: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4419: $type = 2;
4420: $udom = $1;
4421: $unum = $2;
4422: $group = $3;
4423: $file_name = $3.'/'.$4;
4424: }
4425: if (wantarray) {
4426: return ($type,$udom,$unum,$file_name,$group);
4427: }
4428: return $type;
4429: }
4430:
4431: sub is_portfolio_url {
4432: my ($url) = @_;
4433: return scalar(&parse_portfolio_url($url));
4434: }
4435:
1.798 raeburn 4436: sub is_portfolio_file {
4437: my ($file) = @_;
1.820 raeburn 4438: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4439: return 1;
4440: }
4441: return;
4442: }
4443:
1.976 raeburn 4444: sub usertools_access {
1.976.2.1 raeburn 4445: my ($uname,$udom,$tool,$action) = @_;
1.976 raeburn 4446: my $access;
4447: my %tools = (
4448: aboutme => 1,
4449: blog => 1,
4450: portfolio => 1,
4451: );
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.976.2.1 raeburn 4459: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4460: if ($action ne 'reload') {
4461: return $env{'environment.availabletools.'.$tool};
4462: }
1.976 raeburn 4463: }
4464:
4465: my ($toolstatus,$inststatus);
4466:
4467: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4468: $toolstatus = $env{'environment.tools.'.$tool};
4469: $inststatus = $env{'environment.inststatus'};
4470: } else {
4471: my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
4472: $toolstatus = $userenv{'tools.'.$tool};
4473: $inststatus = $userenv{'inststatus'};
4474: }
4475:
4476: if ($toolstatus ne '') {
4477: if ($toolstatus) {
4478: $access = 1;
4479: } else {
4480: $access = 0;
4481: }
4482: return $access;
4483: }
4484:
4485: my $is_adv = &is_advanced_user($udom,$uname);
4486: my %domdef = &get_domain_defaults($udom);
4487: if (ref($domdef{$tool}) eq 'HASH') {
4488: if ($is_adv) {
4489: if ($domdef{$tool}{'_LC_adv'} ne '') {
4490: if ($domdef{$tool}{'_LC_adv'}) {
4491: $access = 1;
4492: } else {
4493: $access = 0;
4494: }
4495: return $access;
4496: }
4497: }
4498: if ($inststatus ne '') {
4499: my ($hasaccess,$hasnoaccess);
4500: foreach my $affiliation (split(/:/,$inststatus)) {
4501: if ($domdef{$tool}{$affiliation} ne '') {
4502: if ($domdef{$tool}{$affiliation}) {
4503: $hasaccess = 1;
4504: } else {
4505: $hasnoaccess = 1;
4506: }
4507: }
4508: }
4509: if ($hasaccess || $hasnoaccess) {
4510: if ($hasaccess) {
4511: $access = 1;
4512: } elsif ($hasnoaccess) {
4513: $access = 0;
4514: }
4515: return $access;
4516: }
4517: } else {
4518: if ($domdef{$tool}{'default'} ne '') {
4519: if ($domdef{$tool}{'default'}) {
4520: $access = 1;
4521: } elsif ($domdef{$tool}{'default'} == 0) {
4522: $access = 0;
4523: }
4524: return $access;
4525: }
4526: }
4527: } else {
4528: $access = 1;
4529: return $access;
4530: }
4531: }
4532:
4533: sub is_advanced_user {
4534: my ($udom,$uname) = @_;
4535: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4536: my %allroles;
4537: my $is_adv;
4538: foreach my $role (keys(%roleshash)) {
4539: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4540: my $area = '/'.$tdomain.'/'.$trest;
4541: if ($sec ne '') {
4542: $area .= '/'.$sec;
4543: }
4544: if (($area ne '') && ($trole ne '')) {
4545: my $spec=$trole.'.'.$area;
4546: if ($trole =~ /^cr\//) {
4547: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4548: } elsif ($trole ne 'gr') {
4549: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4550: }
4551: }
4552: }
4553: foreach my $role (keys(%allroles)) {
4554: last if ($is_adv);
4555: foreach my $item (split(/:/,$allroles{$role})) {
4556: if ($item ne '') {
4557: my ($privilege,$restrictions)=split(/&/,$item);
4558: if ($privilege eq 'adv') {
4559: $is_adv = 1;
4560: last;
4561: }
4562: }
4563: }
4564: }
4565: return $is_adv;
4566: }
1.798 raeburn 4567:
1.341 www 4568: # ---------------------------------------------- Custom access rule evaluation
4569:
4570: sub customaccess {
4571: my ($priv,$uri)=@_;
1.807 albertel 4572: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4573: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4574: $udom = &LONCAPA::clean_domain($udom);
4575: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4576: my $access=0;
1.800 albertel 4577: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4578: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4579: if ($type eq 'user') {
4580: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4581: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4582: if ($tdom) {
4583: if ($tdom ne $env{'user.domain'}) { next; }
4584: }
1.896 albertel 4585: if ($tuname) {
4586: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4587: }
4588: $access=($effect eq 'allow');
4589: last;
4590: }
4591: } else {
4592: if ($role) {
4593: if ($role ne $urole) { next; }
4594: }
4595: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4596: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4597: if ($tdom) {
4598: if ($tdom ne $udom) { next; }
4599: }
4600: if ($tcrs) {
4601: if ($tcrs ne $ucrs) { next; }
4602: }
4603: if ($tsec) {
4604: if ($tsec ne $usec) { next; }
4605: }
4606: $access=($effect eq 'allow');
4607: last;
4608: }
4609: if ($realm eq '' && $role eq '') {
4610: $access=($effect eq 'allow');
4611: }
1.402 bowersj2 4612: }
1.341 www 4613: }
4614: return $access;
4615: }
4616:
1.103 harris41 4617: # ------------------------------------------------- Check for a user privilege
1.12 www 4618:
4619: sub allowed {
1.810 raeburn 4620: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4621: my $ver_orguri=$uri;
1.439 www 4622: $uri=&deversion($uri);
1.152 www 4623: my $orguri=$uri;
1.52 www 4624: $uri=&declutter($uri);
1.809 raeburn 4625:
1.810 raeburn 4626: if ($priv eq 'evb') {
4627: # Evade communication block restrictions for specified role in a course
4628: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4629: return $1;
4630: } else {
4631: return;
4632: }
4633: }
4634:
1.620 albertel 4635: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4636: # Free bre access to adm and meta resources
1.775 albertel 4637: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4638: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4639: && ($priv eq 'bre')) {
1.14 www 4640: return 'F';
1.159 www 4641: }
4642:
1.545 banghart 4643: # Free bre access to user's own portfolio contents
1.714 raeburn 4644: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4645: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4646: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4647: my %setters;
4648: my ($startblock,$endblock) =
4649: &Apache::loncommon::blockcheck(\%setters,'port');
4650: if ($startblock && $endblock) {
4651: return 'B';
4652: } else {
4653: return 'F';
4654: }
1.545 banghart 4655: }
4656:
1.762 raeburn 4657: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4658: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4659: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4660: if (exists($env{'request.course.id'})) {
4661: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4662: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4663: if (($domain eq $cdom) && ($name eq $cnum)) {
4664: my $courseprivid=$env{'request.course.id'};
4665: $courseprivid=~s/\_/\//;
4666: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4667: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4668: return $1;
1.762 raeburn 4669: } else {
4670: if ($env{'request.course.sec'}) {
4671: $courseprivid.='/'.$env{'request.course.sec'};
4672: }
4673: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4674: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4675: return $2;
4676: }
1.714 raeburn 4677: }
4678: }
4679: }
4680: }
4681:
1.159 www 4682: # Free bre to public access
4683:
4684: if ($priv eq 'bre') {
1.238 www 4685: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4686: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4687: return 'F';
4688: }
1.238 www 4689: if ($copyright eq 'priv') {
4690: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4691: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4692: return '';
4693: }
4694: }
4695: if ($copyright eq 'domain') {
4696: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4697: unless (($env{'user.domain'} eq $1) ||
4698: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4699: return '';
4700: }
1.262 matthew 4701: }
1.620 albertel 4702: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4703: # Library role, so allow browsing of resources in this domain.
4704: return 'F';
1.238 www 4705: }
1.341 www 4706: if ($copyright eq 'custom') {
4707: unless (&customaccess($priv,$uri)) { return ''; }
4708: }
1.14 www 4709: }
1.264 matthew 4710: # Domain coordinator is trying to create a course
1.620 albertel 4711: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4712: # uri is the requested domain in this case.
4713: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4714: # a role of dc for the domain in question.
1.620 albertel 4715: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4716: }
1.29 www 4717:
1.52 www 4718: my $thisallowed='';
4719: my $statecond=0;
4720: my $courseprivid='';
4721:
4722: # Course
4723:
1.620 albertel 4724: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4725: $thisallowed.=$1;
4726: }
1.29 www 4727:
1.52 www 4728: # Domain
4729:
1.620 albertel 4730: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4731: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4732: $thisallowed.=$1;
4733: }
1.52 www 4734:
4735: # Course: uri itself is a course
1.66 www 4736: my $courseuri=$uri;
4737: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4738: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4739:
1.620 albertel 4740: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4741: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4742: $thisallowed.=$1;
4743: }
1.29 www 4744:
1.665 albertel 4745: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4746: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4747: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4748: $thisallowed='';
1.671 raeburn 4749: my ($match)=&is_on_map($uri);
4750: if ($match) {
4751: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4752: =~/\Q$priv\E\&([^\:]*)/) {
4753: $thisallowed.=$1;
4754: }
4755: } else {
1.705 albertel 4756: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4757: if ($refuri) {
4758: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4759: $thisallowed='F';
1.671 raeburn 4760: } else {
4761: $refuri=&declutter($refuri);
4762: my ($match) = &is_on_map($refuri);
4763: if ($match) {
4764: $thisallowed='F';
4765: }
1.669 raeburn 4766: }
1.671 raeburn 4767: }
4768: }
1.314 www 4769: }
1.492 albertel 4770:
1.766 albertel 4771: if ($priv eq 'bre'
4772: && $thisallowed ne 'F'
4773: && $thisallowed ne '2'
4774: && &is_portfolio_url($uri)) {
4775: $thisallowed = &portfolio_access($uri);
4776: }
4777:
1.52 www 4778: # Full access at system, domain or course-wide level? Exit.
1.29 www 4779: if ($thisallowed=~/F/) {
4780: return 'F';
4781: }
4782:
1.52 www 4783: # If this is generating or modifying users, exit with special codes
1.29 www 4784:
1.643 www 4785: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4786: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4787: my ($audom,$auname)=split('/',$uri);
1.643 www 4788: # no author name given, so this just checks on the general right to make a co-author in this domain
4789: unless ($auname) { return $thisallowed; }
4790: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4791: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4792: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4793: ($audom ne $env{'request.role.domain'}))) { return ''; }
4794: }
1.52 www 4795: return $thisallowed;
4796: }
4797: #
1.103 harris41 4798: # Gathered so far: system, domain and course wide privileges
1.52 www 4799: #
4800: # Course: See if uri or referer is an individual resource that is part of
4801: # the course
4802:
1.620 albertel 4803: if ($env{'request.course.id'}) {
1.232 www 4804:
1.620 albertel 4805: $courseprivid=$env{'request.course.id'};
4806: if ($env{'request.course.sec'}) {
4807: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4808: }
4809: $courseprivid=~s/\_/\//;
4810: my $checkreferer=1;
1.232 www 4811: my ($match,$cond)=&is_on_map($uri);
4812: if ($match) {
4813: $statecond=$cond;
1.620 albertel 4814: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4815: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4816: $thisallowed.=$1;
4817: $checkreferer=0;
4818: }
1.29 www 4819: }
1.83 www 4820:
1.148 www 4821: if ($checkreferer) {
1.620 albertel 4822: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4823: unless ($refuri) {
1.800 albertel 4824: foreach my $key (keys(%env)) {
4825: if ($key=~/^httpref\..*\*/) {
4826: my $pattern=$key;
1.156 www 4827: $pattern=~s/^httpref\.\/res\///;
1.148 www 4828: $pattern=~s/\*/\[\^\/\]\+/g;
4829: $pattern=~s/\//\\\//g;
1.152 www 4830: if ($orguri=~/$pattern/) {
1.800 albertel 4831: $refuri=$env{$key};
1.148 www 4832: }
4833: }
1.191 harris41 4834: }
1.148 www 4835: }
1.232 www 4836:
1.148 www 4837: if ($refuri) {
1.152 www 4838: $refuri=&declutter($refuri);
1.232 www 4839: my ($match,$cond)=&is_on_map($refuri);
4840: if ($match) {
4841: my $refstatecond=$cond;
1.620 albertel 4842: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4843: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4844: $thisallowed.=$1;
1.53 www 4845: $uri=$refuri;
4846: $statecond=$refstatecond;
1.52 www 4847: }
4848: }
1.148 www 4849: }
1.29 www 4850: }
1.52 www 4851: }
1.29 www 4852:
1.52 www 4853: #
1.103 harris41 4854: # Gathered now: all privileges that could apply, and condition number
1.52 www 4855: #
4856: #
4857: # Full or no access?
4858: #
1.29 www 4859:
1.52 www 4860: if ($thisallowed=~/F/) {
4861: return 'F';
4862: }
1.29 www 4863:
1.52 www 4864: unless ($thisallowed) {
4865: return '';
4866: }
1.29 www 4867:
1.52 www 4868: # Restrictions exist, deal with them
4869: #
4870: # C:according to course preferences
4871: # R:according to resource settings
4872: # L:unless locked
4873: # X:according to user session state
4874: #
4875:
4876: # Possibly locked functionality, check all courses
1.54 www 4877: # Locks might take effect only after 10 minutes cache expiration for other
4878: # courses, and 2 minutes for current course
1.52 www 4879:
4880: my $envkey;
4881: if ($thisallowed=~/L/) {
1.620 albertel 4882: foreach $envkey (keys %env) {
1.54 www 4883: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4884: my $courseid=$2;
4885: my $roleid=$1.'.'.$2;
1.92 www 4886: $courseid=~s/^\///;
1.54 www 4887: my $expiretime=600;
1.620 albertel 4888: if ($env{'request.role'} eq $roleid) {
1.54 www 4889: $expiretime=120;
4890: }
4891: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4892: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4893: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4894: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4895: }
1.620 albertel 4896: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4897: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4898: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4899: &log($env{'user.domain'},$env{'user.name'},
4900: $env{'user.home'},
1.57 www 4901: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4902: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4903: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4904: return '';
4905: }
4906: }
1.620 albertel 4907: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4908: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4909: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4910: &log($env{'user.domain'},$env{'user.name'},
4911: $env{'user.home'},
1.57 www 4912: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4913: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4914: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4915: return '';
4916: }
4917: }
4918: }
1.29 www 4919: }
1.52 www 4920: }
4921:
4922: #
4923: # Rest of the restrictions depend on selected course
4924: #
4925:
1.620 albertel 4926: unless ($env{'request.course.id'}) {
1.766 albertel 4927: if ($thisallowed eq 'A') {
4928: return 'A';
1.814 raeburn 4929: } elsif ($thisallowed eq 'B') {
4930: return 'B';
1.766 albertel 4931: } else {
4932: return '1';
4933: }
1.52 www 4934: }
1.29 www 4935:
1.52 www 4936: #
4937: # Now user is definitely in a course
4938: #
1.53 www 4939:
4940:
4941: # Course preferences
4942:
4943: if ($thisallowed=~/C/) {
1.620 albertel 4944: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4945: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4946: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4947: =~/\Q$rolecode\E/) {
1.689 albertel 4948: if ($priv ne 'pch') {
4949: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4950: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4951: $env{'request.course.id'});
4952: }
1.237 www 4953: return '';
4954: }
4955:
1.620 albertel 4956: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4957: =~/\Q$unamedom\E/) {
1.689 albertel 4958: if ($priv ne 'pch') {
4959: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4960: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4961: $env{'request.course.id'});
4962: }
1.54 www 4963: return '';
4964: }
1.53 www 4965: }
4966:
4967: # Resource preferences
4968:
4969: if ($thisallowed=~/R/) {
1.620 albertel 4970: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4971: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4972: if ($priv ne 'pch') {
4973: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4974: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4975: }
4976: return '';
1.54 www 4977: }
1.53 www 4978: }
1.30 www 4979:
1.246 www 4980: # Restricted by state or randomout?
1.30 www 4981:
1.52 www 4982: if ($thisallowed=~/X/) {
1.620 albertel 4983: if ($env{'acc.randomout'}) {
1.579 albertel 4984: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4985: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4986: return '';
4987: }
1.247 www 4988: }
4989: if (&condval($statecond)) {
1.52 www 4990: return '2';
4991: } else {
4992: return '';
4993: }
4994: }
1.30 www 4995:
1.766 albertel 4996: if ($thisallowed eq 'A') {
4997: return 'A';
1.814 raeburn 4998: } elsif ($thisallowed eq 'B') {
4999: return 'B';
1.766 albertel 5000: }
1.52 www 5001: return 'F';
1.232 www 5002: }
5003:
1.710 albertel 5004: sub split_uri_for_cond {
5005: my $uri=&deversion(&declutter(shift));
5006: my @uriparts=split(/\//,$uri);
5007: my $filename=pop(@uriparts);
5008: my $pathname=join('/',@uriparts);
5009: return ($pathname,$filename);
5010: }
1.232 www 5011: # --------------------------------------------------- Is a resource on the map?
5012:
5013: sub is_on_map {
1.710 albertel 5014: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5015: #Trying to find the conditional for the file
1.620 albertel 5016: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5017: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5018: if ($match) {
1.289 bowersj2 5019: return (1,$1);
5020: } else {
1.434 www 5021: return (0,0);
1.289 bowersj2 5022: }
1.12 www 5023: }
5024:
1.427 www 5025: # --------------------------------------------------------- Get symb from alias
5026:
5027: sub get_symb_from_alias {
5028: my $symb=shift;
5029: my ($map,$resid,$url)=&decode_symb($symb);
5030: # Already is a symb
5031: if ($url) { return $symb; }
5032: # Must be an alias
5033: my $aliassymb='';
5034: my %bighash;
1.620 albertel 5035: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5036: &GDBM_READER(),0640)) {
5037: my $rid=$bighash{'mapalias_'.$symb};
5038: if ($rid) {
5039: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5040: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5041: $resid,$bighash{'src_'.$rid});
1.427 www 5042: }
5043: untie %bighash;
5044: }
5045: return $aliassymb;
5046: }
5047:
1.12 www 5048: # ----------------------------------------------------------------- Define Role
5049:
5050: sub definerole {
5051: if (allowed('mcr','/')) {
5052: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5053: foreach my $role (split(':',$sysrole)) {
5054: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5055: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5056: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5057: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5058: return "refused:s:$crole&$cqual";
5059: }
5060: }
1.191 harris41 5061: }
1.800 albertel 5062: foreach my $role (split(':',$domrole)) {
5063: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5064: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5065: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5066: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5067: return "refused:d:$crole&$cqual";
5068: }
5069: }
1.191 harris41 5070: }
1.800 albertel 5071: foreach my $role (split(':',$courole)) {
5072: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5073: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5074: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5075: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5076: return "refused:c:$crole&$cqual";
5077: }
5078: }
1.191 harris41 5079: }
1.620 albertel 5080: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5081: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5082: "rolesdef_$rolename=".
5083: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5084: return reply($command,$env{'user.home'});
1.12 www 5085: } else {
5086: return 'refused';
5087: }
1.105 harris41 5088: }
5089:
5090: # ---------------- Make a metadata query against the network of library servers
5091:
5092: sub metadata_query {
1.244 matthew 5093: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5094: my %rhash;
1.845 albertel 5095: my %libserv = &all_library();
1.244 matthew 5096: my @server_list = (defined($server_array) ? @$server_array
5097: : keys(%libserv) );
5098: for my $server (@server_list) {
1.118 harris41 5099: unless ($custom or $customshow) {
5100: my $reply=&reply("querysend:".&escape($query),$server);
5101: $rhash{$server}=$reply;
5102: }
5103: else {
5104: my $reply=&reply("querysend:".&escape($query).':'.
5105: &escape($custom).':'.&escape($customshow),
5106: $server);
5107: $rhash{$server}=$reply;
5108: }
1.112 harris41 5109: }
1.118 harris41 5110: return \%rhash;
1.240 www 5111: }
5112:
5113: # ----------------------------------------- Send log queries and wait for reply
5114:
5115: sub log_query {
5116: my ($uname,$udom,$query,%filters)=@_;
5117: my $uhome=&homeserver($uname,$udom);
5118: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5119: my $uhost=&hostname($uhome);
1.800 albertel 5120: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5121: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5122: $uhome);
1.479 albertel 5123: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5124: return get_query_reply($queryid);
5125: }
5126:
1.818 raeburn 5127: # -------------------------- Update MySQL table for portfolio file
5128:
5129: sub update_portfolio_table {
1.821 raeburn 5130: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5131: if ($group ne '') {
5132: $file_name =~s /^\Q$group\E//;
5133: }
1.818 raeburn 5134: my $homeserver = &homeserver($uname,$udom);
5135: my $queryid=
1.821 raeburn 5136: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5137: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5138: my $reply = &get_query_reply($queryid);
5139: return $reply;
5140: }
5141:
1.899 raeburn 5142: # -------------------------- Update MySQL allusers table
5143:
5144: sub update_allusers_table {
5145: my ($uname,$udom,$names) = @_;
5146: my $homeserver = &homeserver($uname,$udom);
5147: my $queryid=
5148: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5149: 'lastname='.&escape($names->{'lastname'}).'%%'.
5150: 'firstname='.&escape($names->{'firstname'}).'%%'.
5151: 'middlename='.&escape($names->{'middlename'}).'%%'.
5152: 'generation='.&escape($names->{'generation'}).'%%'.
5153: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5154: 'id='.&escape($names->{'id'}),$homeserver);
1.976.2.11! raeburn 5155: return;
1.899 raeburn 5156: }
5157:
1.508 raeburn 5158: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5159:
5160: sub fetch_enrollment_query {
1.511 raeburn 5161: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5162: my $homeserver;
1.547 raeburn 5163: my $maxtries = 1;
1.508 raeburn 5164: if ($context eq 'automated') {
5165: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5166: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5167: } else {
5168: $homeserver = &homeserver($cnum,$dom);
5169: }
1.838 albertel 5170: my $host=&hostname($homeserver);
1.506 raeburn 5171: my $cmd = '';
1.800 albertel 5172: foreach my $affiliate (keys %{$affiliatesref}) {
5173: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5174: }
5175: $cmd =~ s/%%$//;
5176: $cmd = &escape($cmd);
5177: my $query = 'fetchenrollment';
1.620 albertel 5178: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5179: unless ($queryid=~/^\Q$host\E\_/) {
5180: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5181: return 'error: '.$queryid;
5182: }
1.506 raeburn 5183: my $reply = &get_query_reply($queryid);
1.547 raeburn 5184: my $tries = 1;
5185: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5186: $reply = &get_query_reply($queryid);
5187: $tries ++;
5188: }
1.526 raeburn 5189: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5190: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5191: } else {
1.901 albertel 5192: my @responses = split(/:/,$reply);
1.515 raeburn 5193: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5194: foreach my $line (@responses) {
5195: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5196: $$replyref{$key} = $value;
5197: }
5198: } else {
1.506 raeburn 5199: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5200: foreach my $line (@responses) {
5201: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5202: $$replyref{$key} = $value;
5203: if ($value > 0) {
1.800 albertel 5204: foreach my $item (@{$$affiliatesref{$key}}) {
5205: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5206: my $destname = $pathname.'/'.$filename;
5207: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5208: if ($xml_classlist =~ /^error/) {
5209: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5210: } else {
1.506 raeburn 5211: if ( open(FILE,">$destname") ) {
5212: print FILE &unescape($xml_classlist);
5213: close(FILE);
1.526 raeburn 5214: } else {
5215: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5216: }
5217: }
5218: }
5219: }
5220: }
5221: }
5222: return 'ok';
5223: }
5224: return 'error';
5225: }
5226:
1.242 www 5227: sub get_query_reply {
5228: my $queryid=shift;
1.240 www 5229: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5230: my $reply='';
5231: for (1..100) {
5232: sleep 2;
5233: if (-e $replyfile.'.end') {
1.448 albertel 5234: if (open(my $fh,$replyfile)) {
1.904 albertel 5235: $reply = join('',<$fh>);
5236: close($fh);
1.240 www 5237: } else { return 'error: reply_file_error'; }
1.242 www 5238: return &unescape($reply);
5239: }
1.240 www 5240: }
1.242 www 5241: return 'timeout:'.$queryid;
1.240 www 5242: }
5243:
5244: sub courselog_query {
1.241 www 5245: #
5246: # possible filters:
5247: # url: url or symb
5248: # username
5249: # domain
5250: # action: view, submit, grade
5251: # start: timestamp
5252: # end: timestamp
5253: #
1.240 www 5254: my (%filters)=@_;
1.620 albertel 5255: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5256: if ($filters{'url'}) {
5257: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5258: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5259: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5260: }
1.620 albertel 5261: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5262: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5263: return &log_query($cname,$cdom,'courselog',%filters);
5264: }
5265:
5266: sub userlog_query {
1.858 raeburn 5267: #
5268: # possible filters:
5269: # action: log check role
5270: # start: timestamp
5271: # end: timestamp
5272: #
1.240 www 5273: my ($uname,$udom,%filters)=@_;
5274: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5275: }
5276:
1.506 raeburn 5277: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5278:
5279: sub auto_run {
1.508 raeburn 5280: my ($cnum,$cdom) = @_;
1.876 raeburn 5281: my $response = 0;
5282: my $settings;
5283: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5284: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5285: $settings = $domconfig{'autoenroll'};
5286: if ($settings->{'run'} eq '1') {
5287: $response = 1;
5288: }
5289: } else {
1.934 raeburn 5290: my $homeserver;
5291: if (&is_course($cdom,$cnum)) {
5292: $homeserver = &homeserver($cnum,$cdom);
5293: } else {
5294: $homeserver = &domain($cdom,'primary');
5295: }
5296: if ($homeserver ne 'no_host') {
5297: $response = &reply('autorun:'.$cdom,$homeserver);
5298: }
1.876 raeburn 5299: }
1.506 raeburn 5300: return $response;
5301: }
1.776 albertel 5302:
1.506 raeburn 5303: sub auto_get_sections {
1.508 raeburn 5304: my ($cnum,$cdom,$inst_coursecode) = @_;
5305: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5306: my @secs = ();
1.511 raeburn 5307: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5308: unless ($response eq 'refused') {
1.901 albertel 5309: @secs = split(/:/,$response);
1.506 raeburn 5310: }
5311: return @secs;
5312: }
1.776 albertel 5313:
1.506 raeburn 5314: sub auto_new_course {
1.508 raeburn 5315: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5316: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5317: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5318: return $response;
5319: }
1.776 albertel 5320:
1.506 raeburn 5321: sub auto_validate_courseID {
1.508 raeburn 5322: my ($cnum,$cdom,$inst_course_id) = @_;
5323: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5324: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5325: return $response;
5326: }
1.776 albertel 5327:
1.506 raeburn 5328: sub auto_create_password {
1.873 raeburn 5329: my ($cnum,$cdom,$authparam,$udom) = @_;
5330: my ($homeserver,$response);
1.506 raeburn 5331: my $create_passwd = 0;
5332: my $authchk = '';
1.873 raeburn 5333: if ($udom =~ /^$match_domain$/) {
5334: $homeserver = &domain($udom,'primary');
5335: }
5336: if ($homeserver eq '') {
5337: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5338: $homeserver = &homeserver($cnum,$cdom);
5339: }
5340: }
5341: if ($homeserver eq '') {
5342: $authchk = 'nodomain';
1.506 raeburn 5343: } else {
1.873 raeburn 5344: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5345: if ($response eq 'refused') {
5346: $authchk = 'refused';
5347: } else {
1.901 albertel 5348: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5349: }
1.506 raeburn 5350: }
5351: return ($authparam,$create_passwd,$authchk);
5352: }
5353:
1.706 raeburn 5354: sub auto_photo_permission {
5355: my ($cnum,$cdom,$students) = @_;
5356: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5357: my ($outcome,$perm_reqd,$conditions) =
5358: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5359: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5360: return (undef,undef);
5361: }
1.706 raeburn 5362: return ($outcome,$perm_reqd,$conditions);
5363: }
5364:
5365: sub auto_checkphotos {
5366: my ($uname,$udom,$pid) = @_;
5367: my $homeserver = &homeserver($uname,$udom);
5368: my ($result,$resulttype);
5369: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5370: &escape($uname).':'.&escape($pid),
5371: $homeserver));
1.709 albertel 5372: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5373: return (undef,undef);
5374: }
1.706 raeburn 5375: if ($outcome) {
5376: ($result,$resulttype) = split(/:/,$outcome);
5377: }
5378: return ($result,$resulttype);
5379: }
5380:
5381: sub auto_photochoice {
5382: my ($cnum,$cdom) = @_;
5383: my $homeserver = &homeserver($cnum,$cdom);
5384: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5385: &escape($cdom),
5386: $homeserver)));
1.709 albertel 5387: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5388: return (undef,undef);
5389: }
1.706 raeburn 5390: return ($update,$comment);
5391: }
5392:
5393: sub auto_photoupdate {
5394: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5395: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5396: my $host=&hostname($homeserver);
1.706 raeburn 5397: my $cmd = '';
5398: my $maxtries = 1;
1.800 albertel 5399: foreach my $affiliate (keys(%{$affiliatesref})) {
5400: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5401: }
5402: $cmd =~ s/%%$//;
5403: $cmd = &escape($cmd);
5404: my $query = 'institutionalphotos';
5405: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5406: unless ($queryid=~/^\Q$host\E\_/) {
5407: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5408: return 'error: '.$queryid;
5409: }
5410: my $reply = &get_query_reply($queryid);
5411: my $tries = 1;
5412: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5413: $reply = &get_query_reply($queryid);
5414: $tries ++;
5415: }
5416: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5417: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5418: } else {
5419: my @responses = split(/:/,$reply);
5420: my $outcome = shift(@responses);
5421: foreach my $item (@responses) {
5422: my ($key,$value) = split(/=/,$item);
5423: $$photo{$key} = $value;
5424: }
5425: return $outcome;
5426: }
5427: return 'error';
5428: }
5429:
1.521 raeburn 5430: sub auto_instcode_format {
1.793 albertel 5431: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5432: $cat_order) = @_;
1.521 raeburn 5433: my $courses = '';
1.772 raeburn 5434: my @homeservers;
1.521 raeburn 5435: if ($caller eq 'global') {
1.841 albertel 5436: my %servers = &get_servers($codedom,'library');
5437: foreach my $tryserver (keys(%servers)) {
5438: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5439: push(@homeservers,$tryserver);
5440: }
1.584 raeburn 5441: }
1.521 raeburn 5442: } else {
1.772 raeburn 5443: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5444: }
1.793 albertel 5445: foreach my $code (keys(%{$instcodes})) {
5446: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5447: }
5448: chop($courses);
1.772 raeburn 5449: my $ok_response = 0;
5450: my $response;
5451: while (@homeservers > 0 && $ok_response == 0) {
5452: my $server = shift(@homeservers);
5453: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5454: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5455: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5456: split(/:/,$response);
1.772 raeburn 5457: %{$codes} = (%{$codes},&str2hash($codes_str));
5458: push(@{$codetitles},&str2array($codetitles_str));
5459: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5460: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5461: $ok_response = 1;
5462: }
5463: }
5464: if ($ok_response) {
1.521 raeburn 5465: return 'ok';
1.772 raeburn 5466: } else {
5467: return $response;
1.521 raeburn 5468: }
5469: }
5470:
1.792 raeburn 5471: sub auto_instcode_defaults {
5472: my ($domain,$returnhash,$code_order) = @_;
5473: my @homeservers;
1.841 albertel 5474:
5475: my %servers = &get_servers($domain,'library');
5476: foreach my $tryserver (keys(%servers)) {
5477: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5478: push(@homeservers,$tryserver);
5479: }
1.792 raeburn 5480: }
1.841 albertel 5481:
1.792 raeburn 5482: my $response;
1.841 albertel 5483: foreach my $server (@homeservers) {
1.792 raeburn 5484: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5485: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5486:
5487: foreach my $pair (split(/\&/,$response)) {
5488: my ($name,$value)=split(/\=/,$pair);
5489: if ($name eq 'code_order') {
5490: @{$code_order} = split(/\&/,&unescape($value));
5491: } else {
5492: $returnhash->{&unescape($name)}=&unescape($value);
5493: }
5494: }
5495: return 'ok';
1.792 raeburn 5496: }
1.841 albertel 5497:
5498: return $response;
1.792 raeburn 5499: }
5500:
1.777 albertel 5501: sub auto_validate_class_sec {
1.918 raeburn 5502: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5503: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5504: my $ownerlist;
5505: if (ref($owners) eq 'ARRAY') {
5506: $ownerlist = join(',',@{$owners});
5507: } else {
5508: $ownerlist = $owners;
5509: }
1.773 raeburn 5510: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5511: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5512: return $response;
5513: }
5514:
1.679 raeburn 5515: # ------------------------------------------------------- Course Group routines
5516:
5517: sub get_coursegroups {
1.809 raeburn 5518: my ($cdom,$cnum,$group,$namespace) = @_;
5519: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5520: }
5521:
1.679 raeburn 5522: sub modify_coursegroup {
5523: my ($cdom,$cnum,$groupsettings) = @_;
5524: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5525: }
5526:
1.809 raeburn 5527: sub toggle_coursegroup_status {
5528: my ($cdom,$cnum,$group,$action) = @_;
5529: my ($from_namespace,$to_namespace);
5530: if ($action eq 'delete') {
5531: $from_namespace = 'coursegroups';
5532: $to_namespace = 'deleted_groups';
5533: } else {
5534: $from_namespace = 'deleted_groups';
5535: $to_namespace = 'coursegroups';
5536: }
5537: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5538: if (my $tmp = &error(%curr_group)) {
5539: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5540: return ('read error',$tmp);
5541: } else {
5542: my %savedsettings = %curr_group;
1.809 raeburn 5543: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5544: my $deloutcome;
5545: if ($result eq 'ok') {
1.809 raeburn 5546: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5547: } else {
5548: return ('write error',$result);
5549: }
5550: if ($deloutcome eq 'ok') {
5551: return 'ok';
5552: } else {
5553: return ('delete error',$deloutcome);
5554: }
5555: }
5556: }
5557:
1.679 raeburn 5558: sub modify_group_roles {
1.957 raeburn 5559: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5560: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5561: my $role = 'gr/'.&escape($userprivs);
5562: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5563: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5564: if ($result eq 'ok') {
5565: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5566: }
1.679 raeburn 5567: return $result;
5568: }
5569:
5570: sub modify_coursegroup_membership {
5571: my ($cdom,$cnum,$membership) = @_;
5572: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5573: return $result;
5574: }
5575:
1.682 raeburn 5576: sub get_active_groups {
5577: my ($udom,$uname,$cdom,$cnum) = @_;
5578: my $now = time;
5579: my %groups = ();
5580: foreach my $key (keys(%env)) {
1.811 albertel 5581: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5582: my ($start,$end) = split(/\./,$env{$key});
5583: if (($end!=0) && ($end<$now)) { next; }
5584: if (($start!=0) && ($start>$now)) { next; }
5585: if ($1 eq $cdom && $2 eq $cnum) {
5586: $groups{$3} = $env{$key} ;
5587: }
5588: }
5589: }
5590: return %groups;
5591: }
5592:
1.683 raeburn 5593: sub get_group_membership {
5594: my ($cdom,$cnum,$group) = @_;
5595: return(&dump('groupmembership',$cdom,$cnum,$group));
5596: }
5597:
5598: sub get_users_groups {
5599: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5600: my @usersgroups;
1.683 raeburn 5601: my $cachetime=1800;
5602:
5603: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5604: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5605: if (defined($cached)) {
1.734 albertel 5606: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5607: } else {
5608: $grouplist = '';
1.816 raeburn 5609: my $courseurl = &courseid_to_courseurl($courseid);
5610: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5611: my $access_end = $env{'course.'.$courseid.
5612: '.default_enrollment_end_date'};
5613: my $now = time;
5614: foreach my $key (keys(%roleshash)) {
5615: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5616: my $group = $1;
5617: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5618: my $start = $2;
5619: my $end = $1;
5620: if ($start == -1) { next; } # deleted from group
5621: if (($start!=0) && ($start>$now)) { next; }
5622: if (($end!=0) && ($end<$now)) {
5623: if ($access_end && $access_end < $now) {
5624: if ($access_end - $end < 86400) {
5625: push(@usersgroups,$group);
1.733 raeburn 5626: }
5627: }
1.817 raeburn 5628: next;
1.733 raeburn 5629: }
1.817 raeburn 5630: push(@usersgroups,$group);
1.683 raeburn 5631: }
5632: }
5633: }
1.817 raeburn 5634: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5635: $grouplist = join(':',@usersgroups);
5636: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5637: }
1.733 raeburn 5638: return @usersgroups;
1.683 raeburn 5639: }
5640:
5641: sub devalidate_getgroups_cache {
5642: my ($udom,$uname,$cdom,$cnum)=@_;
5643: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5644:
1.683 raeburn 5645: my $hashid="$udom:$uname:$courseid";
5646: &devalidate_cache_new('getgroups',$hashid);
5647: }
5648:
1.12 www 5649: # ------------------------------------------------------------------ Plain Text
5650:
5651: sub plaintext {
1.742 raeburn 5652: my ($short,$type,$cid) = @_;
1.758 albertel 5653: if ($short =~ /^cr/) {
5654: return (split('/',$short))[-1];
5655: }
1.742 raeburn 5656: if (!defined($cid)) {
5657: $cid = $env{'request.course.id'};
5658: }
5659: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5660: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5661: '.plaintext'});
5662: }
5663: my %rolenames = (
5664: Course => 'std',
5665: Group => 'alt1',
5666: );
5667: if (defined($type) &&
5668: defined($rolenames{$type}) &&
5669: defined($prp{$short}{$rolenames{$type}})) {
5670: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5671: } else {
5672: return &Apache::lonlocal::mt($prp{$short}{'std'});
5673: }
1.12 www 5674: }
5675:
5676: # ----------------------------------------------------------------- Assign Role
5677:
5678: sub assignrole {
1.957 raeburn 5679: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5680: $context)=@_;
1.21 www 5681: my $mrole;
5682: if ($role =~ /^cr\//) {
1.393 www 5683: my $cwosec=$url;
1.811 albertel 5684: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5685: unless (&allowed('ccr',$cwosec)) {
1.104 www 5686: &logthis('Refused custom assignrole: '.
5687: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5688: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5689: return 'refused';
5690: }
1.21 www 5691: $mrole='cr';
1.678 raeburn 5692: } elsif ($role =~ /^gr\//) {
5693: my $cwogrp=$url;
1.811 albertel 5694: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5695: unless (&allowed('mdg',$cwogrp)) {
5696: &logthis('Refused group assignrole: '.
5697: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5698: $env{'user.name'}.' at '.$env{'user.domain'});
5699: return 'refused';
5700: }
5701: $mrole='gr';
1.21 www 5702: } else {
1.82 www 5703: my $cwosec=$url;
1.811 albertel 5704: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5705: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5706: my $refused;
5707: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5708: if (!(&allowed('c'.$role,$url))) {
5709: $refused = 1;
5710: }
5711: } else {
5712: $refused = 1;
5713: }
1.947 raeburn 5714: if ($refused) {
5715: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5716: $refused = '';
5717: } else {
5718: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5719: ' '.$role.' '.$end.' '.$start.' by '.
5720: $env{'user.name'}.' at '.$env{'user.domain'});
5721: return 'refused';
5722: }
1.932 raeburn 5723: }
1.104 www 5724: }
1.21 www 5725: $mrole=$role;
5726: }
1.620 albertel 5727: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5728: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5729: if ($end) { $command.='_'.$end; }
1.21 www 5730: if ($start) {
5731: if ($end) {
1.81 www 5732: $command.='_'.$start;
1.21 www 5733: } else {
1.81 www 5734: $command.='_0_'.$start;
1.21 www 5735: }
5736: }
1.739 raeburn 5737: my $origstart = $start;
5738: my $origend = $end;
1.957 raeburn 5739: my $delflag;
1.357 www 5740: # actually delete
5741: if ($deleteflag) {
1.373 www 5742: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5743: # modify command to delete the role
1.620 albertel 5744: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5745: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5746: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5747: # set start and finish to negative values for userrolelog
5748: $start=-1;
5749: $end=-1;
1.957 raeburn 5750: $delflag = 1;
1.357 www 5751: }
5752: }
5753: # send command
1.349 www 5754: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5755: # log new user role if status is ok
1.349 www 5756: if ($answer eq 'ok') {
1.663 raeburn 5757: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5758: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5759: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5760: unless ($role =~ /^gr/) {
5761: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5762: $origstart,$selfenroll,$context);
1.739 raeburn 5763: }
1.349 www 5764: }
5765: return $answer;
1.169 harris41 5766: }
5767:
5768: # -------------------------------------------------- Modify user authentication
1.197 www 5769: # Overrides without validation
5770:
1.169 harris41 5771: sub modifyuserauth {
5772: my ($udom,$uname,$umode,$upass)=@_;
5773: my $uhome=&homeserver($uname,$udom);
1.197 www 5774: unless (&allowed('mau',$udom)) { return 'refused'; }
5775: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5776: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5777: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5778: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5779: &escape($upass),$uhome);
1.620 albertel 5780: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5781: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5782: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5783: &log($udom,,$uname,$uhome,
1.620 albertel 5784: 'Authentication changed by '.$env{'user.domain'}.', '.
5785: $env{'user.name'}.', '.$umode.
1.197 www 5786: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5787: unless ($reply eq 'ok') {
1.197 www 5788: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5789: return 'error: '.$reply;
5790: }
1.170 harris41 5791: return 'ok';
1.80 www 5792: }
5793:
1.81 www 5794: # --------------------------------------------------------------- Modify a user
1.80 www 5795:
1.81 www 5796: sub modifyuser {
1.206 matthew 5797: my ($udom, $uname, $uid,
5798: $umode, $upass, $first,
5799: $middle, $last, $gene,
1.963 raeburn 5800: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 5801: $udom= &LONCAPA::clean_domain($udom);
5802: $uname=&LONCAPA::clean_username($uname);
1.81 www 5803: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5804: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5805: $last.', '.$gene.'(forceid: '.$forceid.')'.
5806: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5807: ' desiredhome not specified').
1.620 albertel 5808: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5809: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5810: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5811: # ----------------------------------------------------------------- Create User
1.406 albertel 5812: if (($uhome eq 'no_host') &&
5813: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5814: my $unhome='';
1.844 albertel 5815: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5816: $unhome = $desiredhome;
1.620 albertel 5817: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5818: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5819: } else { # load balancing routine for determining $unhome
1.81 www 5820: my $loadm=10000000;
1.841 albertel 5821: my %servers = &get_servers($udom,'library');
5822: foreach my $tryserver (keys(%servers)) {
5823: my $answer=reply('load',$tryserver);
5824: if (($answer=~/\d+/) && ($answer<$loadm)) {
5825: $loadm=$answer;
5826: $unhome=$tryserver;
5827: }
1.80 www 5828: }
5829: }
5830: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5831: return 'error: unable to find a home server for '.$uname.
5832: ' in domain '.$udom;
1.80 www 5833: }
5834: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5835: &escape($upass),$unhome);
5836: unless ($reply eq 'ok') {
5837: return 'error: '.$reply;
5838: }
1.230 stredwic 5839: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5840: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5841: return 'error: unable verify users home machine.';
1.80 www 5842: }
1.209 matthew 5843: } # End of creation of new user
1.80 www 5844: # ---------------------------------------------------------------------- Add ID
5845: if ($uid) {
5846: $uid=~tr/A-Z/a-z/;
5847: my %uidhash=&idrget($udom,$uname);
1.196 www 5848: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5849: && (!$forceid)) {
1.80 www 5850: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5851: return 'error: user id "'.$uid.'" does not match '.
5852: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5853: }
5854: } else {
5855: &idput($udom,($uname => $uid));
5856: }
5857: }
5858: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5859: my @tmp=&get('environment',
1.899 raeburn 5860: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 5861: 'permanentemail','inststatus'],
1.134 albertel 5862: $udom,$uname);
1.313 matthew 5863: my %names;
5864: if ($tmp[0] =~ m/^error:.*/) {
5865: %names=();
5866: } else {
5867: %names = @tmp;
5868: }
1.388 www 5869: #
5870: # Make sure to not trash student environment if instructor does not bother
5871: # to supply name and email information
5872: #
5873: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5874: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5875: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5876: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5877: if ($email) {
5878: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 5879: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 5880: }
1.899 raeburn 5881: if ($uid) { $names{'id'} = $uid; }
1.963 raeburn 5882: if (defined($inststatus)) { $names{'inststatus'} = $inststatus; }
1.134 albertel 5883: my $reply = &put('environment', \%names, $udom,$uname);
5884: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5885: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5886: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 5887: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5888: $umode.', '.$first.', '.$middle.', '.
5889: $last.', '.$gene.', '.$email.', '.$inststatus;
5890: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
5891: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
5892: } else {
5893: $logmsg .= ' during self creation';
5894: }
5895: &logthis($logmsg);
1.134 albertel 5896: return 'ok';
1.80 www 5897: }
5898:
1.81 www 5899: # -------------------------------------------------------------- Modify student
1.80 www 5900:
1.81 www 5901: sub modifystudent {
5902: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 5903: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5904: $selfenroll,$context)=@_;
1.455 albertel 5905: if (!$cid) {
1.620 albertel 5906: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5907: return 'not_in_class';
5908: }
1.80 www 5909: }
5910: # --------------------------------------------------------------- Make the user
1.81 www 5911: my $reply=&modifyuser
1.209 matthew 5912: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5913: $desiredhome,$email);
1.80 www 5914: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5915: # This will cause &modify_student_enrollment to get the uid from the
5916: # students environment
5917: $uid = undef if (!$forceid);
1.455 albertel 5918: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 5919: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 5920: return $reply;
5921: }
5922:
5923: sub modify_student_enrollment {
1.957 raeburn 5924: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 5925: my ($cdom,$cnum,$chome);
5926: if (!$cid) {
1.620 albertel 5927: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5928: return 'not_in_class';
5929: }
1.620 albertel 5930: $cdom=$env{'course.'.$cid.'.domain'};
5931: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5932: } else {
5933: ($cdom,$cnum)=split(/_/,$cid);
5934: }
1.620 albertel 5935: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5936: if (!$chome) {
1.457 raeburn 5937: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5938: }
1.455 albertel 5939: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5940: # Make sure the user exists
1.81 www 5941: my $uhome=&homeserver($uname,$udom);
5942: if (($uhome eq '') || ($uhome eq 'no_host')) {
5943: return 'error: no such user';
5944: }
1.297 matthew 5945: # Get student data if we were not given enough information
5946: if (!defined($first) || $first eq '' ||
5947: !defined($last) || $last eq '' ||
5948: !defined($uid) || $uid eq '' ||
5949: !defined($middle) || $middle eq '' ||
5950: !defined($gene) || $gene eq '') {
1.294 matthew 5951: # They did not supply us with enough data to enroll the student, so
5952: # we need to pick up more information.
1.297 matthew 5953: my %tmp = &get('environment',
1.294 matthew 5954: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5955: ,$udom,$uname);
5956:
1.800 albertel 5957: #foreach my $key (keys(%tmp)) {
5958: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5959: #}
1.294 matthew 5960: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5961: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5962: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5963: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5964: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5965: }
1.556 albertel 5966: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5967: my $reply=cput('classlist',
5968: {"$uname:$udom" =>
1.515 raeburn 5969: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5970: $cdom,$cnum);
1.81 www 5971: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5972: return 'error: '.$reply;
1.652 albertel 5973: } else {
5974: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5975: }
1.297 matthew 5976: # Add student role to user
1.83 www 5977: my $uurl='/'.$cid;
1.81 www 5978: $uurl=~s/\_/\//g;
5979: if ($usec) {
5980: $uurl.='/'.$usec;
5981: }
1.957 raeburn 5982: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 5983: }
5984:
1.556 albertel 5985: sub format_name {
5986: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5987: my $name;
5988: if ($first ne 'lastname') {
5989: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5990: } else {
5991: if ($lastname=~/\S/) {
5992: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5993: $name=~s/\s+,/,/;
5994: } else {
5995: $name.= $firstname.' '.$middlename.' '.$generation;
5996: }
5997: }
5998: $name=~s/^\s+//;
5999: $name=~s/\s+$//;
6000: $name=~s/\s+/ /g;
6001: return $name;
6002: }
6003:
1.84 www 6004: # ------------------------------------------------- Write to course preferences
6005:
6006: sub writecoursepref {
6007: my ($courseid,%prefs)=@_;
6008: $courseid=~s/^\///;
6009: $courseid=~s/\_/\//g;
6010: my ($cdomain,$cnum)=split(/\//,$courseid);
6011: my $chome=homeserver($cnum,$cdomain);
6012: if (($chome eq '') || ($chome eq 'no_host')) {
6013: return 'error: no such course';
6014: }
6015: my $cstring='';
1.800 albertel 6016: foreach my $pref (keys(%prefs)) {
6017: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6018: }
1.84 www 6019: $cstring=~s/\&$//;
6020: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6021: }
6022:
6023: # ---------------------------------------------------------- Make/modify course
6024:
6025: sub createcourse {
1.741 raeburn 6026: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6027: $course_owner,$crstype)=@_;
1.84 www 6028: $url=&declutter($url);
6029: my $cid='';
1.264 matthew 6030: unless (&allowed('ccc',$udom)) {
1.84 www 6031: return 'refused';
6032: }
6033: # ------------------------------------------------------------------- Create ID
1.674 www 6034: my $uname=int(1+rand(9)).
6035: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6036: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 6037: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6038: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 6039: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6040: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6041: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
6042: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 6043: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6044: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6045: return 'error: unable to generate unique course-ID';
6046: }
6047: }
1.264 matthew 6048: # ------------------------------------------------ Check supplied server name
1.620 albertel 6049: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 6050: if (! &is_library($course_server)) {
1.264 matthew 6051: return 'error:bad server name '.$course_server;
6052: }
1.84 www 6053: # ------------------------------------------------------------- Make the course
6054: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6055: $course_server);
1.84 www 6056: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 6057: $uhome=&homeserver($uname,$udom,'true');
1.84 www 6058: if (($uhome eq '') || ($uhome eq 'no_host')) {
6059: return 'error: no such course';
6060: }
1.271 www 6061: # ----------------------------------------------------------------- Course made
1.516 raeburn 6062: # log existence
1.918 raeburn 6063: my $newcourse = {
6064: $udom.'_'.$uname => {
1.921 raeburn 6065: description => $description,
6066: inst_code => $inst_code,
6067: owner => $course_owner,
6068: type => $crstype,
1.918 raeburn 6069: },
6070: };
1.921 raeburn 6071: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6072: # set toplevel url
1.271 www 6073: my $topurl=$url;
6074: unless ($nonstandard) {
6075: # ------------------------------------------ For standard courses, make top url
6076: my $mapurl=&clutter($url);
1.278 www 6077: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6078: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6079: <map>
6080: <resource id="1" type="start"></resource>
6081: <resource id="2" src="$mapurl"></resource>
6082: <resource id="3" type="finish"></resource>
6083: <link index="1" from="1" to="2"></link>
6084: <link index="2" from="2" to="3"></link>
6085: </map>
6086: ENDINITMAP
6087: $topurl=&declutter(
1.638 albertel 6088: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6089: );
6090: }
6091: # ----------------------------------------------------------- Write preferences
1.84 www 6092: &writecoursepref($udom.'_'.$uname,
6093: ('description' => $description,
1.271 www 6094: 'url' => $topurl));
1.84 www 6095: return '/'.$udom.'/'.$uname;
6096: }
6097:
1.813 albertel 6098: sub is_course {
6099: my ($cdom,$cnum) = @_;
6100: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 6101: undef,'.');
1.813 albertel 6102: if (exists($courses{$cdom.'_'.$cnum})) {
6103: return 1;
6104: }
6105: return 0;
6106: }
6107:
1.21 www 6108: # ---------------------------------------------------------- Assign Custom Role
6109:
6110: sub assigncustomrole {
1.957 raeburn 6111: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6112: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 6113: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 6114: }
6115:
6116: # ----------------------------------------------------------------- Revoke Role
6117:
6118: sub revokerole {
1.957 raeburn 6119: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6120: my $now=time;
1.965 raeburn 6121: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 6122: }
6123:
6124: # ---------------------------------------------------------- Revoke Custom Role
6125:
6126: sub revokecustomrole {
1.957 raeburn 6127: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 6128: my $now=time;
1.357 www 6129: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 6130: $deleteflag,$selfenroll,$context);
1.17 www 6131: }
6132:
1.533 banghart 6133: # ------------------------------------------------------------ Disk usage
1.535 albertel 6134: sub diskusage {
1.955 raeburn 6135: my ($udom,$uname,$directorypath,$getpropath)=@_;
6136: $directorypath =~ s/\/$//;
6137: my $listing=&reply('du2:'.&escape($directorypath).':'
6138: .&escape($getpropath).':'.&escape($uname).':'
6139: .&escape($udom),homeserver($uname,$udom));
6140: if ($listing eq 'unknown_cmd') {
6141: if ($getpropath) {
6142: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6143: }
6144: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6145: }
1.514 albertel 6146: return $listing;
1.512 banghart 6147: }
6148:
1.566 banghart 6149: sub is_locked {
6150: my ($file_name, $domain, $user) = @_;
6151: my @check;
6152: my $is_locked;
6153: push @check, $file_name;
1.613 albertel 6154: my %locked = &get('file_permissions',\@check,
1.620 albertel 6155: $env{'user.domain'},$env{'user.name'});
1.615 albertel 6156: my ($tmp)=keys(%locked);
6157: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 6158:
1.566 banghart 6159: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 6160: $is_locked = 'false';
6161: foreach my $entry (@{$locked{$file_name}}) {
6162: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 6163: $is_locked = 'true';
6164: last;
1.745 raeburn 6165: }
6166: }
1.566 banghart 6167: } else {
6168: $is_locked = 'false';
6169: }
6170: }
6171:
1.759 albertel 6172: sub declutter_portfile {
6173: my ($file) = @_;
1.833 albertel 6174: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 6175: return $file;
6176: }
6177:
1.559 banghart 6178: # ------------------------------------------------------------- Mark as Read Only
6179:
6180: sub mark_as_readonly {
6181: my ($domain,$user,$files,$what) = @_;
1.613 albertel 6182: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6183: my ($tmp)=keys(%current_permissions);
6184: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 6185: foreach my $file (@{$files}) {
1.759 albertel 6186: $file = &declutter_portfile($file);
1.561 banghart 6187: push(@{$current_permissions{$file}},$what);
1.559 banghart 6188: }
1.613 albertel 6189: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6190: return;
6191: }
6192:
1.572 banghart 6193: # ------------------------------------------------------------Save Selected Files
6194:
6195: sub save_selected_files {
6196: my ($user, $path, @files) = @_;
6197: my $filename = $user."savedfiles";
1.573 banghart 6198: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 6199: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 6200: foreach my $file (@files) {
1.620 albertel 6201: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 6202: }
6203: foreach my $file (@other_files) {
1.574 banghart 6204: print (OUT $file."\n");
1.572 banghart 6205: }
1.574 banghart 6206: close (OUT);
1.572 banghart 6207: return 'ok';
6208: }
6209:
1.574 banghart 6210: sub clear_selected_files {
6211: my ($user) = @_;
6212: my $filename = $user."savedfiles";
6213: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6214: print (OUT undef);
6215: close (OUT);
6216: return ("ok");
6217: }
6218:
1.572 banghart 6219: sub files_in_path {
6220: my ($user, $path) = @_;
6221: my $filename = $user."savedfiles";
6222: my %return_files;
1.574 banghart 6223: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 6224: while (my $line_in = <IN>) {
1.574 banghart 6225: chomp ($line_in);
6226: my @paths_and_file = split (m!/!, $line_in);
6227: my $file_part = pop (@paths_and_file);
6228: my $path_part = join ('/', @paths_and_file);
1.573 banghart 6229: $path_part.='/';
6230: my $path_and_file = $path_part.$file_part;
6231: if ($path_part eq $path) {
6232: $return_files{$file_part}= 'selected';
6233: }
6234: }
1.574 banghart 6235: close (IN);
6236: return (\%return_files);
1.572 banghart 6237: }
6238:
6239: # called in portfolio select mode, to show files selected NOT in current directory
6240: sub files_not_in_path {
6241: my ($user, $path) = @_;
6242: my $filename = $user."savedfiles";
6243: my @return_files;
6244: my $path_part;
1.800 albertel 6245: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6246: while (my $line = <IN>) {
1.572 banghart 6247: #ok, I know it's clunky, but I want it to work
1.800 albertel 6248: my @paths_and_file = split(m|/|, $line);
6249: my $file_part = pop(@paths_and_file);
6250: chomp($file_part);
6251: my $path_part = join('/', @paths_and_file);
1.572 banghart 6252: $path_part .= '/';
6253: my $path_and_file = $path_part.$file_part;
6254: if ($path_part ne $path) {
1.800 albertel 6255: push(@return_files, ($path_and_file));
1.572 banghart 6256: }
6257: }
1.800 albertel 6258: close(OUT);
1.574 banghart 6259: return (@return_files);
1.572 banghart 6260: }
6261:
1.745 raeburn 6262: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6263:
1.745 raeburn 6264: sub get_portfile_permissions {
6265: my ($domain,$user) = @_;
1.613 albertel 6266: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6267: my ($tmp)=keys(%current_permissions);
6268: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6269: return \%current_permissions;
6270: }
6271:
6272: #---------------------------------------------Get portfolio file access controls
6273:
1.749 raeburn 6274: sub get_access_controls {
1.745 raeburn 6275: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6276: my %access;
6277: my $real_file = $file;
6278: $file =~ s/\.meta$//;
1.745 raeburn 6279: if (defined($file)) {
1.749 raeburn 6280: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6281: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6282: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6283: }
6284: }
1.745 raeburn 6285: } else {
1.749 raeburn 6286: foreach my $key (keys(%{$current_permissions})) {
6287: if ($key =~ /\0accesscontrol$/) {
6288: if (defined($group)) {
6289: if ($key !~ m-^\Q$group\E/-) {
6290: next;
6291: }
6292: }
6293: my ($fullpath) = split(/\0/,$key);
6294: if (ref($$current_permissions{$key}) eq 'HASH') {
6295: foreach my $control (keys(%{$$current_permissions{$key}})) {
6296: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6297: }
6298: }
6299: }
6300: }
6301: }
6302: return %access;
6303: }
6304:
6305: sub modify_access_controls {
6306: my ($file_name,$changes,$domain,$user)=@_;
6307: my ($outcome,$deloutcome);
6308: my %store_permissions;
6309: my %new_values;
6310: my %new_control;
6311: my %translation;
6312: my @deletions = ();
6313: my $now = time;
6314: if (exists($$changes{'activate'})) {
6315: if (ref($$changes{'activate'}) eq 'HASH') {
6316: my @newitems = sort(keys(%{$$changes{'activate'}}));
6317: my $numnew = scalar(@newitems);
6318: for (my $i=0; $i<$numnew; $i++) {
6319: my $newkey = $newitems[$i];
6320: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6321: if ($newkey =~ /^\d+:/) {
6322: $newkey =~ s/^(\d+)/$newid/;
6323: $translation{$1} = $newid;
6324: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6325: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6326: $translation{$1} = $newid;
6327: }
1.749 raeburn 6328: $new_values{$file_name."\0".$newkey} =
6329: $$changes{'activate'}{$newitems[$i]};
6330: $new_control{$newkey} = $now;
6331: }
6332: }
6333: }
6334: my %todelete;
6335: my %changed_items;
6336: foreach my $action ('delete','update') {
6337: if (exists($$changes{$action})) {
6338: if (ref($$changes{$action}) eq 'HASH') {
6339: foreach my $key (keys(%{$$changes{$action}})) {
6340: my ($itemnum) = ($key =~ /^([^:]+):/);
6341: if ($action eq 'delete') {
6342: $todelete{$itemnum} = 1;
6343: } else {
6344: $changed_items{$itemnum} = $key;
6345: }
6346: }
1.745 raeburn 6347: }
6348: }
1.749 raeburn 6349: }
6350: # get lock on access controls for file.
6351: my $lockhash = {
6352: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6353: ':'.$env{'user.domain'},
6354: };
6355: my $tries = 0;
6356: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6357:
6358: while (($gotlock ne 'ok') && $tries <3) {
6359: $tries ++;
6360: sleep 1;
6361: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6362: }
6363: if ($gotlock eq 'ok') {
6364: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6365: my ($tmp)=keys(%curr_permissions);
6366: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6367: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6368: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6369: if (ref($curr_controls) eq 'HASH') {
6370: foreach my $control_item (keys(%{$curr_controls})) {
6371: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6372: if (defined($todelete{$itemnum})) {
6373: push(@deletions,$file_name."\0".$control_item);
6374: } else {
6375: if (defined($changed_items{$itemnum})) {
6376: $new_control{$changed_items{$itemnum}} = $now;
6377: push(@deletions,$file_name."\0".$control_item);
6378: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6379: } else {
6380: $new_control{$control_item} = $$curr_controls{$control_item};
6381: }
6382: }
1.745 raeburn 6383: }
6384: }
6385: }
1.970 raeburn 6386: my ($group);
6387: if (&is_course($domain,$user)) {
6388: ($group,my $file) = split(/\//,$file_name,2);
6389: }
1.749 raeburn 6390: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6391: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6392: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6393: # remove lock
6394: my @del_lock = ($file_name."\0".'locked_access_records');
6395: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6396: my $sqlresult =
1.970 raeburn 6397: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6398: $group);
1.749 raeburn 6399: } else {
6400: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6401: }
1.749 raeburn 6402: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6403: }
6404:
1.827 raeburn 6405: sub make_public_indefinitely {
6406: my ($requrl) = @_;
6407: my $now = time;
6408: my $action = 'activate';
6409: my $aclnum = 0;
6410: if (&is_portfolio_url($requrl)) {
6411: my (undef,$udom,$unum,$file_name,$group) =
6412: &parse_portfolio_url($requrl);
6413: my $current_perms = &get_portfile_permissions($udom,$unum);
6414: my %access_controls = &get_access_controls($current_perms,
6415: $group,$file_name);
6416: foreach my $key (keys(%{$access_controls{$file_name}})) {
6417: my ($num,$scope,$end,$start) =
6418: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6419: if ($scope eq 'public') {
6420: if ($start <= $now && $end == 0) {
6421: $action = 'none';
6422: } else {
6423: $action = 'update';
6424: $aclnum = $num;
6425: }
6426: last;
6427: }
6428: }
6429: if ($action eq 'none') {
6430: return 'ok';
6431: } else {
6432: my %changes;
6433: my $newend = 0;
6434: my $newstart = $now;
6435: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6436: $changes{$action}{$newkey} = {
6437: type => 'public',
6438: time => {
6439: start => $newstart,
6440: end => $newend,
6441: },
6442: };
6443: my ($outcome,$deloutcome,$new_values,$translation) =
6444: &modify_access_controls($file_name,\%changes,$udom,$unum);
6445: return $outcome;
6446: }
6447: } else {
6448: return 'invalid';
6449: }
6450: }
6451:
1.745 raeburn 6452: #------------------------------------------------------Get Marked as Read Only
6453:
6454: sub get_marked_as_readonly {
6455: my ($domain,$user,$what,$group) = @_;
6456: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6457: my @readonly_files;
1.629 banghart 6458: my $cmp1=$what;
6459: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6460: while (my ($file_name,$value) = each(%{$current_permissions})) {
6461: if (defined($group)) {
6462: if ($file_name !~ m-^\Q$group\E/-) {
6463: next;
6464: }
6465: }
1.561 banghart 6466: if (ref($value) eq "ARRAY"){
6467: foreach my $stored_what (@{$value}) {
1.629 banghart 6468: my $cmp2=$stored_what;
1.759 albertel 6469: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6470: $cmp2=join('',@{$stored_what});
1.745 raeburn 6471: }
1.629 banghart 6472: if ($cmp1 eq $cmp2) {
1.561 banghart 6473: push(@readonly_files, $file_name);
1.745 raeburn 6474: last;
1.563 banghart 6475: } elsif (!defined($what)) {
6476: push(@readonly_files, $file_name);
1.745 raeburn 6477: last;
1.561 banghart 6478: }
6479: }
1.745 raeburn 6480: }
1.561 banghart 6481: }
6482: return @readonly_files;
6483: }
1.577 banghart 6484: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6485:
1.577 banghart 6486: sub get_marked_as_readonly_hash {
1.745 raeburn 6487: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6488: my %readonly_files;
1.745 raeburn 6489: while (my ($file_name,$value) = each(%{$current_permissions})) {
6490: if (defined($group)) {
6491: if ($file_name !~ m-^\Q$group\E/-) {
6492: next;
6493: }
6494: }
1.577 banghart 6495: if (ref($value) eq "ARRAY"){
6496: foreach my $stored_what (@{$value}) {
1.745 raeburn 6497: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6498: foreach my $lock_descriptor(@{$stored_what}) {
6499: if ($lock_descriptor eq 'graded') {
6500: $readonly_files{$file_name} = 'graded';
6501: } elsif ($lock_descriptor eq 'handback') {
6502: $readonly_files{$file_name} = 'handback';
6503: } else {
6504: if (!exists($readonly_files{$file_name})) {
6505: $readonly_files{$file_name} = 'locked';
6506: }
6507: }
1.745 raeburn 6508: }
1.750 banghart 6509: }
1.577 banghart 6510: }
6511: }
6512: }
6513: return %readonly_files;
6514: }
1.559 banghart 6515: # ------------------------------------------------------------ Unmark as Read Only
6516:
6517: sub unmark_as_readonly {
1.629 banghart 6518: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6519: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6520: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6521: $file_name = &declutter_portfile($file_name);
1.634 albertel 6522: my $symb_crs = $what;
6523: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6524: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6525: my ($tmp)=keys(%current_permissions);
6526: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6527: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6528: foreach my $file (@readonly_files) {
1.759 albertel 6529: my $clean_file = &declutter_portfile($file);
6530: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6531: my $current_locks = $current_permissions{$file};
1.563 banghart 6532: my @new_locks;
6533: my @del_keys;
6534: if (ref($current_locks) eq "ARRAY"){
6535: foreach my $locker (@{$current_locks}) {
1.632 albertel 6536: my $compare=$locker;
1.749 raeburn 6537: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6538: $compare=join('',@{$locker});
1.746 raeburn 6539: if ($compare ne $symb_crs) {
6540: push(@new_locks, $locker);
6541: }
1.563 banghart 6542: }
6543: }
1.650 albertel 6544: if (scalar(@new_locks) > 0) {
1.563 banghart 6545: $current_permissions{$file} = \@new_locks;
6546: } else {
6547: push(@del_keys, $file);
1.613 albertel 6548: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6549: delete($current_permissions{$file});
1.563 banghart 6550: }
6551: }
1.561 banghart 6552: }
1.613 albertel 6553: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6554: return;
6555: }
1.512 banghart 6556:
1.17 www 6557: # ------------------------------------------------------------ Directory lister
6558:
6559: sub dirlist {
1.955 raeburn 6560: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6561: $uri=~s/^\///;
6562: $uri=~s/\/$//;
1.253 stredwic 6563: my ($udom, $uname);
1.955 raeburn 6564: if ($getuserdir) {
1.253 stredwic 6565: $udom = $userdomain;
6566: $uname = $username;
1.955 raeburn 6567: } else {
6568: (undef,$udom,$uname)=split(/\//,$uri);
6569: if(defined($userdomain)) {
6570: $udom = $userdomain;
6571: }
6572: if(defined($username)) {
6573: $uname = $username;
6574: }
1.253 stredwic 6575: }
1.955 raeburn 6576: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6577:
1.955 raeburn 6578: $dirRoot = $perlvar{'lonDocRoot'};
6579: if (defined($getpropath)) {
6580: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6581: $dirRoot =~ s/\/$//;
1.955 raeburn 6582: } elsif (defined($getuserdir)) {
6583: my $subdir=$uname.'__';
6584: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6585: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6586: ."/$udom/$subdir/$uname";
6587: } elsif (defined($alternateRoot)) {
6588: $dirRoot = $alternateRoot;
1.751 banghart 6589: }
1.253 stredwic 6590:
6591: if($udom) {
6592: if($uname) {
1.955 raeburn 6593: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6594: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6595: .':'.&escape($uname).':'.&escape($udom),
6596: &homeserver($uname,$udom));
6597: if ($listing eq 'unknown_cmd') {
6598: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6599: &homeserver($uname,$udom));
6600: } else {
6601: @listing_results = map { &unescape($_); } split(/:/,$listing);
6602: }
1.605 matthew 6603: if ($listing eq 'unknown_cmd') {
1.800 albertel 6604: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6605: &homeserver($uname,$udom));
1.605 matthew 6606: @listing_results = split(/:/,$listing);
6607: } else {
6608: @listing_results = map { &unescape($_); } split(/:/,$listing);
6609: }
6610: return @listing_results;
1.955 raeburn 6611: } elsif(!$alternateRoot) {
1.800 albertel 6612: my %allusers;
1.841 albertel 6613: my %servers = &get_servers($udom,'library');
1.955 raeburn 6614: foreach my $tryserver (keys(%servers)) {
6615: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6616: &escape($udom),$tryserver);
6617: if ($listing eq 'unknown_cmd') {
6618: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6619: $udom, $tryserver);
6620: } else {
6621: @listing_results = map { &unescape($_); } split(/:/,$listing);
6622: }
1.841 albertel 6623: if ($listing eq 'unknown_cmd') {
6624: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6625: $udom, $tryserver);
6626: @listing_results = split(/:/,$listing);
6627: } else {
6628: @listing_results =
6629: map { &unescape($_); } split(/:/,$listing);
6630: }
6631: if ($listing_results[0] ne 'no_such_dir' &&
6632: $listing_results[0] ne 'empty' &&
6633: $listing_results[0] ne 'con_lost') {
6634: foreach my $line (@listing_results) {
6635: my ($entry) = split(/&/,$line,2);
6636: $allusers{$entry} = 1;
6637: }
6638: }
1.253 stredwic 6639: }
6640: my $alluserstr='';
1.800 albertel 6641: foreach my $user (sort(keys(%allusers))) {
6642: $alluserstr.=$user.'&user:';
1.253 stredwic 6643: }
6644: $alluserstr=~s/:$//;
6645: return split(/:/,$alluserstr);
6646: } else {
1.800 albertel 6647: return ('missing user name');
1.253 stredwic 6648: }
1.955 raeburn 6649: } elsif(!defined($getpropath)) {
1.841 albertel 6650: my @all_domains = sort(&all_domains());
1.955 raeburn 6651: foreach my $domain (@all_domains) {
6652: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6653: }
6654: return @all_domains;
6655: } else {
1.800 albertel 6656: return ('missing domain');
1.275 stredwic 6657: }
6658: }
6659:
6660: # --------------------------------------------- GetFileTimestamp
6661: # This function utilizes dirlist and returns the date stamp for
6662: # when it was last modified. It will also return an error of -1
6663: # if an error occurs
6664:
6665: sub GetFileTimestamp {
1.955 raeburn 6666: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6667: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6668: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6669: my ($fileStat) =
6670: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6671: undef,$getuserdir);
1.275 stredwic 6672: my @stats = split('&', $fileStat);
6673: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6674: # @stats contains first the filename, then the stat output
6675: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6676: } else {
6677: return -1;
1.253 stredwic 6678: }
1.26 www 6679: }
6680:
1.712 albertel 6681: sub stat_file {
6682: my ($uri) = @_;
1.787 albertel 6683: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6684:
1.955 raeburn 6685: my ($udom,$uname,$file);
1.712 albertel 6686: if ($uri =~ m-^/(uploaded|editupload)/-) {
6687: ($udom,$uname,$file) =
1.811 albertel 6688: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6689: $file = 'userfiles/'.$file;
6690: }
6691: if ($uri =~ m-^/res/-) {
6692: ($udom,$uname) =
1.807 albertel 6693: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6694: $file = $uri;
6695: }
6696:
6697: if (!$udom || !$uname || !$file) {
6698: # unable to handle the uri
6699: return ();
6700: }
1.956 raeburn 6701: my $getpropath;
6702: if ($file =~ /^userfiles\//) {
6703: $getpropath = 1;
6704: }
1.955 raeburn 6705: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6706: my @stats = split('&', $result);
1.721 banghart 6707:
1.712 albertel 6708: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6709: shift(@stats); #filename is first
6710: return @stats;
6711: }
6712: return ();
6713: }
6714:
1.26 www 6715: # -------------------------------------------------------- Value of a Condition
6716:
1.713 albertel 6717: # gets the value of a specific preevaluated condition
6718: # stored in the string $env{user.state.<cid>}
6719: # or looks up a condition reference in the bighash and if if hasn't
6720: # already been evaluated recurses into docondval to get the value of
6721: # the condition, then memoizing it to
6722: # $env{user.state.<cid>.<condition>}
1.40 www 6723: sub directcondval {
6724: my $number=shift;
1.620 albertel 6725: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6726: &Apache::lonuserstate::evalstate();
6727: }
1.713 albertel 6728: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6729: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6730: } elsif ($number =~ /^_/) {
6731: my $sub_condition;
6732: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6733: &GDBM_READER(),0640)) {
6734: $sub_condition=$bighash{'conditions'.$number};
6735: untie(%bighash);
6736: }
6737: my $value = &docondval($sub_condition);
1.949 raeburn 6738: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6739: return $value;
6740: }
1.620 albertel 6741: if ($env{'user.state.'.$env{'request.course.id'}}) {
6742: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6743: } else {
6744: return 2;
6745: }
6746: }
6747:
1.713 albertel 6748: # get the collection of conditions for this resource
1.26 www 6749: sub condval {
6750: my $condidx=shift;
1.54 www 6751: my $allpathcond='';
1.713 albertel 6752: foreach my $cond (split(/\|/,$condidx)) {
6753: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6754: $allpathcond.=
6755: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6756: }
1.191 harris41 6757: }
1.54 www 6758: $allpathcond=~s/\|$//;
1.713 albertel 6759: return &docondval($allpathcond);
6760: }
6761:
6762: #evaluates an expression of conditions
6763: sub docondval {
6764: my ($allpathcond) = @_;
6765: my $result=0;
6766: if ($env{'request.course.id'}
6767: && defined($allpathcond)) {
6768: my $operand='|';
6769: my @stack;
6770: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6771: if ($chunk eq '(') {
6772: push @stack,($operand,$result);
6773: } elsif ($chunk eq ')') {
6774: my $before=pop @stack;
6775: if (pop @stack eq '&') {
6776: $result=$result>$before?$before:$result;
6777: } else {
6778: $result=$result>$before?$result:$before;
6779: }
6780: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6781: $operand=$chunk;
6782: } else {
6783: my $new=directcondval($chunk);
6784: if ($operand eq '&') {
6785: $result=$result>$new?$new:$result;
6786: } else {
6787: $result=$result>$new?$result:$new;
6788: }
6789: }
6790: }
1.26 www 6791: }
6792: return $result;
1.421 albertel 6793: }
6794:
6795: # ---------------------------------------------------- Devalidate courseresdata
6796:
6797: sub devalidatecourseresdata {
6798: my ($coursenum,$coursedomain)=@_;
6799: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6800: &devalidate_cache_new('courseres',$hashid);
1.28 www 6801: }
6802:
1.763 www 6803:
1.200 www 6804: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6805: #
6806: # Parameters:
6807: # $coursenum - Number of the course.
6808: # $coursedomain - Domain at which the course was created.
6809: # Returns:
6810: # A hash of the course parameters along (I think) with timestamps
6811: # and version info.
1.877 foxr 6812:
1.624 albertel 6813: sub get_courseresdata {
6814: my ($coursenum,$coursedomain)=@_;
1.200 www 6815: my $coursehom=&homeserver($coursenum,$coursedomain);
6816: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6817: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6818: my %dumpreply;
1.417 albertel 6819: unless (defined($cached)) {
1.624 albertel 6820: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6821: $result=\%dumpreply;
1.251 albertel 6822: my ($tmp) = keys(%dumpreply);
6823: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6824: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6825: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6826: return $tmp;
1.416 albertel 6827: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6828: $result=undef;
1.599 albertel 6829: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6830: }
6831: }
1.624 albertel 6832: return $result;
6833: }
6834:
1.633 albertel 6835: sub devalidateuserresdata {
6836: my ($uname,$udom)=@_;
6837: my $hashid="$udom:$uname";
6838: &devalidate_cache_new('userres',$hashid);
6839: }
6840:
1.624 albertel 6841: sub get_userresdata {
6842: my ($uname,$udom)=@_;
6843: #most student don\'t have any data set, check if there is some data
6844: if (&EXT_cache_status($udom,$uname)) { return undef; }
6845:
6846: my $hashid="$udom:$uname";
6847: my ($result,$cached)=&is_cached_new('userres',$hashid);
6848: if (!defined($cached)) {
6849: my %resourcedata=&dump('resourcedata',$udom,$uname);
6850: $result=\%resourcedata;
6851: &do_cache_new('userres',$hashid,$result,600);
6852: }
6853: my ($tmp)=keys(%$result);
6854: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6855: return $result;
6856: }
6857: #error 2 occurs when the .db doesn't exist
6858: if ($tmp!~/error: 2 /) {
1.672 albertel 6859: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6860: " Trying to get resource data for ".
6861: $uname." at ".$udom.": ".
6862: $tmp."</font>");
6863: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6864: #&EXT_cache_set($udom,$uname);
6865: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6866: undef($tmp); # not really an error so don't send it back
1.624 albertel 6867: }
6868: return $tmp;
6869: }
1.879 foxr 6870: #----------------------------------------------- resdata - return resource data
6871: # Purpose:
6872: # Return resource data for either users or for a course.
6873: # Parameters:
6874: # $name - Course/user name.
6875: # $domain - Name of the domain the user/course is registered on.
6876: # $type - Type of thing $name is (must be 'course' or 'user'
6877: # @which - Array of names of resources desired.
6878: # Returns:
6879: # The value of the first reasource in @which that is found in the
6880: # resource hash.
6881: # Exceptional Conditions:
6882: # If the $type passed in is not valid (not the string 'course' or
6883: # 'user', an undefined reference is returned.
6884: # If none of the resources are found, an undef is returned
1.624 albertel 6885: sub resdata {
6886: my ($name,$domain,$type,@which)=@_;
6887: my $result;
6888: if ($type eq 'course') {
6889: $result=&get_courseresdata($name,$domain);
6890: } elsif ($type eq 'user') {
6891: $result=&get_userresdata($name,$domain);
6892: }
6893: if (!ref($result)) { return $result; }
1.251 albertel 6894: foreach my $item (@which) {
1.927 albertel 6895: if (defined($result->{$item->[0]})) {
6896: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6897: }
1.250 albertel 6898: }
1.291 albertel 6899: return undef;
1.200 www 6900: }
6901:
1.379 matthew 6902: #
6903: # EXT resource caching routines
6904: #
6905:
6906: sub clear_EXT_cache_status {
1.383 albertel 6907: &delenv('cache.EXT.');
1.379 matthew 6908: }
6909:
6910: sub EXT_cache_status {
6911: my ($target_domain,$target_user) = @_;
1.383 albertel 6912: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6913: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6914: # We know already the user has no data
6915: return 1;
6916: } else {
6917: return 0;
6918: }
6919: }
6920:
6921: sub EXT_cache_set {
6922: my ($target_domain,$target_user) = @_;
1.383 albertel 6923: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 6924: #&appenv({$cachename => time});
1.379 matthew 6925: }
6926:
1.28 www 6927: # --------------------------------------------------------- Value of a Variable
1.58 www 6928: sub EXT {
1.715 albertel 6929:
1.395 albertel 6930: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6931: unless ($varname) { return ''; }
1.218 albertel 6932: #get real user name/domain, courseid and symb
6933: my $courseid;
1.359 albertel 6934: my $publicuser;
1.427 www 6935: if ($symbparm) {
6936: $symbparm=&get_symb_from_alias($symbparm);
6937: }
1.218 albertel 6938: if (!($uname && $udom)) {
1.790 albertel 6939: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6940: if (!$symbparm) { $symbparm=$cursymb; }
6941: } else {
1.620 albertel 6942: $courseid=$env{'request.course.id'};
1.218 albertel 6943: }
1.48 www 6944: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6945: my $rest;
1.320 albertel 6946: if (defined($therest[0])) {
1.48 www 6947: $rest=join('.',@therest);
6948: } else {
6949: $rest='';
6950: }
1.320 albertel 6951:
1.57 www 6952: my $qualifierrest=$qualifier;
6953: if ($rest) { $qualifierrest.='.'.$rest; }
6954: my $spacequalifierrest=$space;
6955: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6956: if ($realm eq 'user') {
1.48 www 6957: # --------------------------------------------------------------- user.resource
6958: if ($space eq 'resource') {
1.651 albertel 6959: if ( (defined($Apache::lonhomework::parsing_a_problem)
6960: || defined($Apache::lonhomework::parsing_a_task))
6961: &&
1.744 albertel 6962: ($symbparm eq &symbread()) ) {
6963: # if we are in the middle of processing the resource the
6964: # get the value we are planning on committing
6965: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6966: return $Apache::lonhomework::results{$qualifierrest};
6967: } else {
6968: return $Apache::lonhomework::history{$qualifierrest};
6969: }
1.335 albertel 6970: } else {
1.359 albertel 6971: my %restored;
1.620 albertel 6972: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6973: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6974: } else {
6975: %restored=&restore($symbparm,$courseid,$udom,$uname);
6976: }
1.335 albertel 6977: return $restored{$qualifierrest};
6978: }
1.48 www 6979: # ----------------------------------------------------------------- user.access
6980: } elsif ($space eq 'access') {
1.218 albertel 6981: # FIXME - not supporting calls for a specific user
1.48 www 6982: return &allowed($qualifier,$rest);
6983: # ------------------------------------------ user.preferences, user.environment
6984: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6985: if (($uname eq $env{'user.name'}) &&
6986: ($udom eq $env{'user.domain'})) {
6987: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6988: } else {
1.359 albertel 6989: my %returnhash;
6990: if (!$publicuser) {
6991: %returnhash=&userenvironment($udom,$uname,
6992: $qualifierrest);
6993: }
1.218 albertel 6994: return $returnhash{$qualifierrest};
6995: }
1.48 www 6996: # ----------------------------------------------------------------- user.course
6997: } elsif ($space eq 'course') {
1.218 albertel 6998: # FIXME - not supporting calls for a specific user
1.620 albertel 6999: return $env{join('.',('request.course',$qualifier))};
1.48 www 7000: # ------------------------------------------------------------------- user.role
7001: } elsif ($space eq 'role') {
1.218 albertel 7002: # FIXME - not supporting calls for a specific user
1.620 albertel 7003: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7004: if ($qualifier eq 'value') {
7005: return $role;
7006: } elsif ($qualifier eq 'extent') {
7007: return $where;
7008: }
7009: # ----------------------------------------------------------------- user.domain
7010: } elsif ($space eq 'domain') {
1.218 albertel 7011: return $udom;
1.48 www 7012: # ------------------------------------------------------------------- user.name
7013: } elsif ($space eq 'name') {
1.218 albertel 7014: return $uname;
1.48 www 7015: # ---------------------------------------------------- Any other user namespace
1.29 www 7016: } else {
1.359 albertel 7017: my %reply;
7018: if (!$publicuser) {
7019: %reply=&get($space,[$qualifierrest],$udom,$uname);
7020: }
7021: return $reply{$qualifierrest};
1.48 www 7022: }
1.236 www 7023: } elsif ($realm eq 'query') {
7024: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7025: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7026: [$spacequalifierrest]);
1.620 albertel 7027: return $env{'form.'.$spacequalifierrest};
1.236 www 7028: } elsif ($realm eq 'request') {
1.48 www 7029: # ------------------------------------------------------------- request.browser
7030: if ($space eq 'browser') {
1.430 www 7031: if ($qualifier eq 'textremote') {
1.676 albertel 7032: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7033: return 1;
7034: } else {
7035: return 0;
7036: }
7037: } else {
1.620 albertel 7038: return $env{'browser.'.$qualifier};
1.430 www 7039: }
1.57 www 7040: # ------------------------------------------------------------ request.filename
7041: } else {
1.620 albertel 7042: return $env{'request.'.$spacequalifierrest};
1.29 www 7043: }
1.28 www 7044: } elsif ($realm eq 'course') {
1.48 www 7045: # ---------------------------------------------------------- course.description
1.620 albertel 7046: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 7047: } elsif ($realm eq 'resource') {
1.165 www 7048:
1.620 albertel 7049: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 7050: if (!$symbparm) { $symbparm=&symbread(); }
7051: }
1.693 albertel 7052:
7053: if ($space eq 'title') {
7054: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7055: return &gettitle($symbparm);
7056: }
7057:
7058: if ($space eq 'map') {
7059: my ($map) = &decode_symb($symbparm);
7060: return &symbread($map);
7061: }
1.905 albertel 7062: if ($space eq 'filename') {
7063: if ($symbparm) {
7064: return &clutter((&decode_symb($symbparm))[2]);
7065: }
7066: return &hreflocation('',$env{'request.filename'});
7067: }
1.693 albertel 7068:
7069: my ($section, $group, @groups);
1.593 albertel 7070: my ($courselevelm,$courselevel);
1.539 albertel 7071: if ($symbparm && defined($courseid) &&
1.620 albertel 7072: $courseid eq $env{'request.course.id'}) {
1.165 www 7073:
1.218 albertel 7074: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 7075:
1.60 www 7076: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 7077: my $symbp=$symbparm;
1.735 albertel 7078: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 7079:
7080: my $symbparm=$symbp.'.'.$spacequalifierrest;
7081: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7082:
1.620 albertel 7083: if (($env{'user.name'} eq $uname) &&
7084: ($env{'user.domain'} eq $udom)) {
7085: $section=$env{'request.course.sec'};
1.733 raeburn 7086: @groups = split(/:/,$env{'request.course.groups'});
7087: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 7088: } else {
1.539 albertel 7089: if (! defined($usection)) {
1.551 albertel 7090: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 7091: } else {
7092: $section = $usection;
7093: }
1.733 raeburn 7094: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 7095: }
7096:
7097: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7098: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7099: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7100:
1.593 albertel 7101: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 7102: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 7103: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 7104:
1.60 www 7105: # ----------------------------------------------------------- first, check user
1.624 albertel 7106:
7107: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 7108: ([$courselevelr,'resource'],
7109: [$courselevelm,'map' ],
7110: [$courselevel, 'course' ]));
1.931 albertel 7111: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 7112:
1.594 albertel 7113: # ------------------------------------------------ second, check some of course
1.684 raeburn 7114: my $coursereply;
1.691 raeburn 7115: if (@groups > 0) {
7116: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7117: $mapparm,$spacequalifierrest);
1.927 albertel 7118: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 7119: }
1.96 www 7120:
1.684 raeburn 7121: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 7122: $env{'course.'.$courseid.'.domain'},
7123: 'course',
7124: ([$seclevelr, 'resource'],
7125: [$seclevelm, 'map' ],
7126: [$seclevel, 'course' ],
7127: [$courselevelr,'resource']));
7128: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 7129:
1.60 www 7130: # ------------------------------------------------------ third, check map parms
1.218 albertel 7131: my %parmhash=();
7132: my $thisparm='';
7133: if (tie(%parmhash,'GDBM_File',
1.620 albertel 7134: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 7135: &GDBM_READER(),0640)) {
1.218 albertel 7136: $thisparm=$parmhash{$symbparm};
7137: untie(%parmhash);
7138: }
1.927 albertel 7139: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 7140: }
1.594 albertel 7141: # ------------------------------------------ fourth, look in resource metadata
1.71 www 7142:
1.218 albertel 7143: $spacequalifierrest=~s/\./\_/;
1.282 albertel 7144: my $filename;
7145: if (!$symbparm) { $symbparm=&symbread(); }
7146: if ($symbparm) {
1.409 www 7147: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 7148: } else {
1.620 albertel 7149: $filename=$env{'request.filename'};
1.282 albertel 7150: }
7151: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 7152: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 7153: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 7154: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 7155:
1.927 albertel 7156: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 7157: if ($symbparm && defined($courseid) &&
1.620 albertel 7158: $courseid eq $env{'request.course.id'}) {
1.624 albertel 7159: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7160: $env{'course.'.$courseid.'.domain'},
7161: 'course',
1.927 albertel 7162: ([$courselevelm,'map' ],
7163: [$courselevel, 'course']));
7164: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 7165: }
1.145 www 7166: # ------------------------------------------------------------------ Cascade up
1.218 albertel 7167: unless ($space eq '0') {
1.336 albertel 7168: my @parts=split(/_/,$space);
7169: my $id=pop(@parts);
7170: my $part=join('_',@parts);
7171: if ($part eq '') { $part='0'; }
1.927 albertel 7172: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 7173: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 7174: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 7175: }
1.395 albertel 7176: if ($recurse) { return undef; }
7177: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 7178: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 7179: # ---------------------------------------------------- Any other user namespace
7180: } elsif ($realm eq 'environment') {
7181: # ----------------------------------------------------------------- environment
1.620 albertel 7182: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7183: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 7184: } else {
1.770 albertel 7185: if ($uname eq 'anonymous' && $udom eq '') {
7186: return '';
7187: }
1.219 albertel 7188: my %returnhash=&userenvironment($udom,$uname,
7189: $spacequalifierrest);
7190: return $returnhash{$spacequalifierrest};
7191: }
1.28 www 7192: } elsif ($realm eq 'system') {
1.48 www 7193: # ----------------------------------------------------------------- system.time
7194: if ($space eq 'time') {
7195: return time;
7196: }
1.696 albertel 7197: } elsif ($realm eq 'server') {
7198: # ----------------------------------------------------------------- system.time
7199: if ($space eq 'name') {
7200: return $ENV{'SERVER_NAME'};
7201: }
1.28 www 7202: }
1.48 www 7203: return '';
1.61 www 7204: }
7205:
1.927 albertel 7206: sub get_reply {
7207: my ($reply_value) = @_;
1.940 raeburn 7208: if (ref($reply_value) eq 'ARRAY') {
7209: if (wantarray) {
7210: return @$reply_value;
7211: }
7212: return $reply_value->[0];
7213: } else {
7214: return $reply_value;
1.927 albertel 7215: }
7216: }
7217:
1.691 raeburn 7218: sub check_group_parms {
7219: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7220: my @groupitems = ();
7221: my $resultitem;
1.927 albertel 7222: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 7223: foreach my $group (@{$groups}) {
7224: foreach my $level (@levels) {
1.927 albertel 7225: my $item = $courseid.'.['.$group.'].'.$level->[0];
7226: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 7227: }
7228: }
7229: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7230: $env{'course.'.$courseid.'.domain'},
7231: 'course',@groupitems);
7232: return $coursereply;
7233: }
7234:
7235: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7236: my ($courseid,@groups) = @_;
7237: @groups = sort(@groups);
1.691 raeburn 7238: return @groups;
7239: }
7240:
1.395 albertel 7241: sub packages_tab_default {
7242: my ($uri,$varname)=@_;
7243: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7244:
7245: my (@extension,@specifics,$do_default);
7246: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7247: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7248: if ($pack_type eq 'default') {
7249: $do_default=1;
7250: } elsif ($pack_type eq 'extension') {
7251: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7252: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7253: # only look at packages defaults for packages that this id is
1.738 albertel 7254: push(@specifics,[$package,$pack_type,$pack_part]);
7255: }
7256: }
7257: # first look for a package that matches the requested part id
7258: foreach my $package (@specifics) {
7259: my (undef,$pack_type,$pack_part)=@{$package};
7260: next if ($pack_part ne $part);
7261: if (defined($packagetab{"$pack_type&$name&default"})) {
7262: return $packagetab{"$pack_type&$name&default"};
7263: }
7264: }
7265: # look for any possible matching non extension_ package
7266: foreach my $package (@specifics) {
7267: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7268: if (defined($packagetab{"$pack_type&$name&default"})) {
7269: return $packagetab{"$pack_type&$name&default"};
7270: }
1.585 albertel 7271: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7272: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7273: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7274: }
7275: }
1.738 albertel 7276: # look for any posible extension_ match
7277: foreach my $package (@extension) {
7278: my ($package,$pack_type)=@{$package};
7279: if (defined($packagetab{"$pack_type&$name&default"})) {
7280: return $packagetab{"$pack_type&$name&default"};
7281: }
7282: if (defined($packagetab{$package."&$name&default"})) {
7283: return $packagetab{$package."&$name&default"};
7284: }
7285: }
7286: # look for a global default setting
7287: if ($do_default && defined($packagetab{"default&$name&default"})) {
7288: return $packagetab{"default&$name&default"};
7289: }
1.395 albertel 7290: return undef;
7291: }
7292:
1.334 albertel 7293: sub add_prefix_and_part {
7294: my ($prefix,$part)=@_;
7295: my $keyroot;
7296: if (defined($prefix) && $prefix !~ /^__/) {
7297: # prefix that has a part already
7298: $keyroot=$prefix;
7299: } elsif (defined($prefix)) {
7300: # prefix that is missing a part
7301: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7302: } else {
7303: # no prefix at all
7304: if (defined($part)) { $keyroot='_'.$part; }
7305: }
7306: return $keyroot;
7307: }
7308:
1.71 www 7309: # ---------------------------------------------------------------- Get metadata
7310:
1.599 albertel 7311: my %metaentry;
1.71 www 7312: sub metadata {
1.176 www 7313: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7314: $uri=&declutter($uri);
1.288 albertel 7315: # if it is a non metadata possible uri return quickly
1.529 albertel 7316: if (($uri eq '') ||
7317: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7318: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7319: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7320: return undef;
7321: }
7322: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7323: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7324: return undef;
1.288 albertel 7325: }
1.73 www 7326: my $filename=$uri;
7327: $uri=~s/\.meta$//;
1.172 www 7328: #
7329: # Is the metadata already cached?
1.177 www 7330: # Look at timestamp of caching
1.172 www 7331: # Everything is cached by the main uri, libraries are never directly cached
7332: #
1.428 albertel 7333: if (!defined($liburi)) {
1.599 albertel 7334: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7335: if (defined($cached)) { return $result->{':'.$what}; }
7336: }
7337: {
1.172 www 7338: #
7339: # Is this a recursive call for a library?
7340: #
1.599 albertel 7341: # if (! exists($metacache{$uri})) {
7342: # $metacache{$uri}={};
7343: # }
1.924 albertel 7344: my $cachetime = 60*60;
1.171 www 7345: if ($liburi) {
7346: $liburi=&declutter($liburi);
7347: $filename=$liburi;
1.401 bowersj2 7348: } else {
1.599 albertel 7349: &devalidate_cache_new('meta',$uri);
7350: undef(%metaentry);
1.401 bowersj2 7351: }
1.140 www 7352: my %metathesekeys=();
1.73 www 7353: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7354: my $metastring;
1.924 albertel 7355: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7356: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7357: $metastring =
1.929 albertel 7358: &Apache::lonnet::ssi_body($which,
1.924 albertel 7359: ('grade_target' => 'meta'));
7360: $cachetime = 1; # only want this cached in the child not long term
7361: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7362: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7363: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7364: $metastring=&getfile($file);
1.489 albertel 7365: }
1.208 albertel 7366: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7367: my $token;
1.140 www 7368: undef %metathesekeys;
1.71 www 7369: while ($token=$parser->get_token) {
1.339 albertel 7370: if ($token->[0] eq 'S') {
7371: if (defined($token->[2]->{'package'})) {
1.172 www 7372: #
7373: # This is a package - get package info
7374: #
1.339 albertel 7375: my $package=$token->[2]->{'package'};
7376: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7377: if (defined($token->[2]->{'id'})) {
7378: $keyroot.='_'.$token->[2]->{'id'};
7379: }
1.599 albertel 7380: if ($metaentry{':packages'}) {
7381: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7382: } else {
1.599 albertel 7383: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7384: }
1.736 albertel 7385: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7386: my $part=$keyroot;
7387: $part=~s/^\_//;
1.736 albertel 7388: if ($pack_entry=~/^\Q$package\E\&/ ||
7389: $pack_entry=~/^\Q$package\E_0\&/) {
7390: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7391: # ignore package.tab specified default values
7392: # here &package_tab_default() will fetch those
7393: if ($subp eq 'default') { next; }
1.736 albertel 7394: my $value=$packagetab{$pack_entry};
1.432 albertel 7395: my $unikey;
7396: if ($pack =~ /_0$/) {
7397: $unikey='parameter_0_'.$name;
7398: $part=0;
7399: } else {
7400: $unikey='parameter'.$keyroot.'_'.$name;
7401: }
1.339 albertel 7402: if ($subp eq 'display') {
7403: $value.=' [Part: '.$part.']';
7404: }
1.599 albertel 7405: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7406: $metathesekeys{$unikey}=1;
1.599 albertel 7407: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7408: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7409: }
1.599 albertel 7410: if (defined($metaentry{':'.$unikey.'.default'})) {
7411: $metaentry{':'.$unikey}=
7412: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7413: }
1.339 albertel 7414: }
7415: }
7416: } else {
1.172 www 7417: #
7418: # This is not a package - some other kind of start tag
1.339 albertel 7419: #
7420: my $entry=$token->[1];
7421: my $unikey;
7422: if ($entry eq 'import') {
7423: $unikey='';
7424: } else {
7425: $unikey=$entry;
7426: }
7427: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7428:
7429: if (defined($token->[2]->{'id'})) {
7430: $unikey.='_'.$token->[2]->{'id'};
7431: }
1.175 www 7432:
1.339 albertel 7433: if ($entry eq 'import') {
1.175 www 7434: #
7435: # Importing a library here
1.339 albertel 7436: #
7437: if ($depthcount<20) {
7438: my $location=$parser->get_text('/import');
7439: my $dir=$filename;
7440: $dir=~s|[^/]*$||;
7441: $location=&filelocation($dir,$location);
1.736 albertel 7442: my $metadata =
7443: &metadata($uri,'keys', $location,$unikey,
7444: $depthcount+1);
7445: foreach my $meta (split(',',$metadata)) {
7446: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7447: $metathesekeys{$meta}=1;
1.339 albertel 7448: }
7449: }
7450: } else {
7451:
7452: if (defined($token->[2]->{'name'})) {
7453: $unikey.='_'.$token->[2]->{'name'};
7454: }
7455: $metathesekeys{$unikey}=1;
1.736 albertel 7456: foreach my $param (@{$token->[3]}) {
7457: $metaentry{':'.$unikey.'.'.$param} =
7458: $token->[2]->{$param};
1.339 albertel 7459: }
7460: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7461: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7462: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7463: # only ws inside the tag, and not in default, so use default
7464: # as value
1.599 albertel 7465: $metaentry{':'.$unikey}=$default;
1.908 albertel 7466: } elsif ( $internaltext =~ /\S/ ) {
7467: # something interesting inside the tag
7468: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7469: } else {
1.908 albertel 7470: # no interesting values, don't set a default
1.339 albertel 7471: }
1.172 www 7472: # end of not-a-package not-a-library import
1.339 albertel 7473: }
1.172 www 7474: # end of not-a-package start tag
1.339 albertel 7475: }
1.172 www 7476: # the next is the end of "start tag"
1.339 albertel 7477: }
7478: }
1.483 albertel 7479: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7480: $extension = lc($extension);
7481: if ($extension eq 'htm') { $extension='html'; }
7482:
1.737 albertel 7483: foreach my $key (keys(%packagetab)) {
1.483 albertel 7484: #no specific packages #how's our extension
7485: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7486: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7487: \%metathesekeys);
7488: }
1.883 albertel 7489:
7490: if (!exists($metaentry{':packages'})
7491: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7492: foreach my $key (keys(%packagetab)) {
1.483 albertel 7493: #no specific packages well let's get default then
7494: if ($key!~/^default&/) { next; }
1.488 albertel 7495: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7496: \%metathesekeys);
7497: }
7498: }
1.338 www 7499: # are there custom rights to evaluate
1.599 albertel 7500: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7501:
1.338 www 7502: #
7503: # Importing a rights file here
1.339 albertel 7504: #
7505: unless ($depthcount) {
1.599 albertel 7506: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7507: my $dir=$filename;
7508: $dir=~s|[^/]*$||;
7509: $location=&filelocation($dir,$location);
1.736 albertel 7510: my $rights_metadata =
7511: &metadata($uri,'keys',$location,'_rights',
7512: $depthcount+1);
7513: foreach my $rights (split(',',$rights_metadata)) {
7514: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7515: $metathesekeys{$rights}=1;
1.339 albertel 7516: }
7517: }
7518: }
1.737 albertel 7519: # uniqifiy package listing
7520: my %seen;
7521: my @uniq_packages =
7522: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7523: $metaentry{':packages'} = join(',',@uniq_packages);
7524:
7525: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7526: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7527: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7528: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7529: # this is the end of "was not already recently cached
1.71 www 7530: }
1.599 albertel 7531: return $metaentry{':'.$what};
1.261 albertel 7532: }
7533:
1.488 albertel 7534: sub metadata_create_package_def {
1.483 albertel 7535: my ($uri,$key,$package,$metathesekeys)=@_;
7536: my ($pack,$name,$subp)=split(/\&/,$key);
7537: if ($subp eq 'default') { next; }
7538:
1.599 albertel 7539: if (defined($metaentry{':packages'})) {
7540: $metaentry{':packages'}.=','.$package;
1.483 albertel 7541: } else {
1.599 albertel 7542: $metaentry{':packages'}=$package;
1.483 albertel 7543: }
7544: my $value=$packagetab{$key};
7545: my $unikey;
7546: $unikey='parameter_0_'.$name;
1.599 albertel 7547: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7548: $$metathesekeys{$unikey}=1;
1.599 albertel 7549: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7550: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7551: }
1.599 albertel 7552: if (defined($metaentry{':'.$unikey.'.default'})) {
7553: $metaentry{':'.$unikey}=
7554: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7555: }
7556: }
7557:
1.261 albertel 7558: sub metadata_generate_part0 {
7559: my ($metadata,$metacache,$uri) = @_;
7560: my %allnames;
1.737 albertel 7561: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7562: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7563: my $part=$$metacache{':'.$metakey.'.part'};
7564: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7565: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7566: $allnames{$name}=$part;
7567: }
7568: }
7569: }
7570: foreach my $name (keys(%allnames)) {
7571: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7572: my $key=":parameter_0_$name";
1.261 albertel 7573: $$metacache{"$key.part"}='0';
7574: $$metacache{"$key.name"}=$name;
1.428 albertel 7575: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7576: $allnames{$name}.'_'.$name.
7577: '.type'};
1.428 albertel 7578: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7579: '.display'};
1.644 www 7580: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7581: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7582: $$metacache{"$key.display"}=$olddis;
7583: }
1.71 www 7584: }
7585:
1.764 albertel 7586: # ------------------------------------------------------ Devalidate title cache
7587:
7588: sub devalidate_title_cache {
7589: my ($url)=@_;
7590: if (!$env{'request.course.id'}) { return; }
7591: my $symb=&symbread($url);
7592: if (!$symb) { return; }
7593: my $key=$env{'request.course.id'}."\0".$symb;
7594: &devalidate_cache_new('title',$key);
7595: }
7596:
1.301 www 7597: # ------------------------------------------------- Get the title of a resource
7598:
7599: sub gettitle {
7600: my $urlsymb=shift;
7601: my $symb=&symbread($urlsymb);
1.534 albertel 7602: if ($symb) {
1.620 albertel 7603: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7604: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7605: if (defined($cached)) {
7606: return $result;
7607: }
1.534 albertel 7608: my ($map,$resid,$url)=&decode_symb($symb);
7609: my $title='';
1.907 albertel 7610: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7611: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7612: } else {
7613: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7614: &GDBM_READER(),0640)) {
7615: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7616: $title=$bighash{'title_'.$mapid.'.'.$resid};
7617: untie(%bighash);
7618: }
1.534 albertel 7619: }
7620: $title=~s/\&colon\;/\:/gs;
7621: if ($title) {
1.599 albertel 7622: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7623: }
7624: $urlsymb=$url;
7625: }
7626: my $title=&metadata($urlsymb,'title');
7627: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7628: return $title;
1.301 www 7629: }
1.613 albertel 7630:
1.614 albertel 7631: sub get_slot {
7632: my ($which,$cnum,$cdom)=@_;
7633: if (!$cnum || !$cdom) {
1.790 albertel 7634: (undef,my $courseid)=&whichuser();
1.620 albertel 7635: $cdom=$env{'course.'.$courseid.'.domain'};
7636: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7637: }
1.703 albertel 7638: my $key=join("\0",'slots',$cdom,$cnum,$which);
7639: my %slotinfo;
7640: if (exists($remembered{$key})) {
7641: $slotinfo{$which} = $remembered{$key};
7642: } else {
7643: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7644: &Apache::lonhomework::showhash(%slotinfo);
7645: my ($tmp)=keys(%slotinfo);
7646: if ($tmp=~/^error:/) { return (); }
7647: $remembered{$key} = $slotinfo{$which};
7648: }
1.616 albertel 7649: if (ref($slotinfo{$which}) eq 'HASH') {
7650: return %{$slotinfo{$which}};
7651: }
7652: return $slotinfo{$which};
1.614 albertel 7653: }
1.31 www 7654: # ------------------------------------------------- Update symbolic store links
7655:
7656: sub symblist {
7657: my ($mapname,%newhash)=@_;
1.438 www 7658: $mapname=&deversion(&declutter($mapname));
1.31 www 7659: my %hash;
1.620 albertel 7660: if (($env{'request.course.fn'}) && (%newhash)) {
7661: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7662: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7663: foreach my $url (keys %newhash) {
7664: next if ($url eq 'last_known'
7665: && $env{'form.no_update_last_known'});
7666: $hash{declutter($url)}=&encode_symb($mapname,
7667: $newhash{$url}->[1],
7668: $newhash{$url}->[0]);
1.191 harris41 7669: }
1.31 www 7670: if (untie(%hash)) {
7671: return 'ok';
7672: }
7673: }
7674: }
7675: return 'error';
1.212 www 7676: }
7677:
7678: # --------------------------------------------------------------- Verify a symb
7679:
7680: sub symbverify {
1.510 www 7681: my ($symb,$thisurl)=@_;
7682: my $thisfn=$thisurl;
1.439 www 7683: $thisfn=&declutter($thisfn);
1.215 www 7684: # direct jump to resource in page or to a sequence - will construct own symbs
7685: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7686: # check URL part
1.409 www 7687: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7688:
1.431 www 7689: unless ($url eq $thisfn) { return 0; }
1.213 www 7690:
1.216 www 7691: $symb=&symbclean($symb);
1.510 www 7692: $thisurl=&deversion($thisurl);
1.439 www 7693: $thisfn=&deversion($thisfn);
1.213 www 7694:
7695: my %bighash;
7696: my $okay=0;
1.431 www 7697:
1.620 albertel 7698: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7699: &GDBM_READER(),0640)) {
1.510 www 7700: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7701: unless ($ids) {
1.510 www 7702: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7703: }
7704: if ($ids) {
7705: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7706: foreach my $id (split(/\,/,$ids)) {
7707: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7708: if (
7709: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7710: eq $symb) {
1.620 albertel 7711: if (($env{'request.role.adv'}) ||
1.800 albertel 7712: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7713: $okay=1;
7714: }
7715: }
1.216 www 7716: }
7717: }
1.213 www 7718: untie(%bighash);
7719: }
7720: return $okay;
1.31 www 7721: }
7722:
1.210 www 7723: # --------------------------------------------------------------- Clean-up symb
7724:
7725: sub symbclean {
7726: my $symb=shift;
1.568 albertel 7727: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7728: # remove version from map
7729: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7730:
1.210 www 7731: # remove version from URL
7732: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7733:
1.507 www 7734: # remove wrapper
7735:
1.510 www 7736: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7737: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7738: return $symb;
1.409 www 7739: }
7740:
7741: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7742:
7743: sub encode_symb {
7744: my ($map,$resid,$url)=@_;
7745: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7746: }
1.409 www 7747:
7748: sub decode_symb {
1.568 albertel 7749: my $symb=shift;
7750: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7751: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7752: return (&fixversion($map),$resid,&fixversion($url));
7753: }
7754:
7755: sub fixversion {
7756: my $fn=shift;
1.609 banghart 7757: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7758: my %bighash;
7759: my $uri=&clutter($fn);
1.620 albertel 7760: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7761: # is this cached?
1.599 albertel 7762: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7763: if (defined($cached)) { return $result; }
7764: # unfortunately not cached, or expired
1.620 albertel 7765: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7766: &GDBM_READER(),0640)) {
7767: if ($bighash{'version_'.$uri}) {
7768: my $version=$bighash{'version_'.$uri};
1.444 www 7769: unless (($version eq 'mostrecent') ||
7770: ($version==&getversion($uri))) {
1.440 www 7771: $uri=~s/\.(\w+)$/\.$version\.$1/;
7772: }
7773: }
7774: untie %bighash;
1.413 www 7775: }
1.599 albertel 7776: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7777: }
7778:
7779: sub deversion {
7780: my $url=shift;
7781: $url=~s/\.\d+\.(\w+)$/\.$1/;
7782: return $url;
1.210 www 7783: }
7784:
1.31 www 7785: # ------------------------------------------------------ Return symb list entry
7786:
7787: sub symbread {
1.249 www 7788: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7789: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7790: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7791: # no filename provided? try from environment
1.44 www 7792: unless ($thisfn) {
1.620 albertel 7793: if ($env{'request.symb'}) {
7794: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7795: }
1.620 albertel 7796: $thisfn=$env{'request.filename'};
1.44 www 7797: }
1.569 albertel 7798: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7799: # is that filename actually a symb? Verify, clean, and return
7800: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7801: if (&symbverify($thisfn,$1)) {
1.620 albertel 7802: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7803: }
1.242 www 7804: }
1.44 www 7805: $thisfn=declutter($thisfn);
1.31 www 7806: my %hash;
1.37 www 7807: my %bighash;
7808: my $syval='';
1.620 albertel 7809: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7810: my $targetfn = $thisfn;
1.609 banghart 7811: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7812: $targetfn = 'adm/wrapper/'.$thisfn;
7813: }
1.687 albertel 7814: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7815: $targetfn=$1;
7816: }
1.620 albertel 7817: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7818: &GDBM_READER(),0640)) {
1.481 raeburn 7819: $syval=$hash{$targetfn};
1.37 www 7820: untie(%hash);
7821: }
7822: # ---------------------------------------------------------- There was an entry
7823: if ($syval) {
1.601 albertel 7824: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7825: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 7826: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7827: #return $env{$cache_str}='';
1.601 albertel 7828: #}
7829: #$syval.=$1;
7830: #}
1.37 www 7831: } else {
7832: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7833: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7834: &GDBM_READER(),0640)) {
1.37 www 7835: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7836: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7837: unless ($ids) {
7838: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7839: }
7840: unless ($ids) {
7841: # alias?
7842: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7843: }
1.37 www 7844: if ($ids) {
7845: # ------------------------------------------------------------------- Has ID(s)
7846: my @possibilities=split(/\,/,$ids);
1.39 www 7847: if ($#possibilities==0) {
7848: # ----------------------------------------------- There is only one possibility
1.37 www 7849: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7850: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7851: $resid,$thisfn);
1.249 www 7852: } elsif (!$donotrecurse) {
1.39 www 7853: # ------------------------------------------ There is more than one possibility
7854: my $realpossible=0;
1.800 albertel 7855: foreach my $id (@possibilities) {
7856: my $file=$bighash{'src_'.$id};
1.39 www 7857: if (&allowed('bre',$file)) {
1.800 albertel 7858: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7859: if ($bighash{'map_type_'.$mapid} ne 'page') {
7860: $realpossible++;
1.626 albertel 7861: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7862: $resid,$thisfn);
1.39 www 7863: }
7864: }
1.191 harris41 7865: }
1.39 www 7866: if ($realpossible!=1) { $syval=''; }
1.249 www 7867: } else {
7868: $syval='';
1.37 www 7869: }
7870: }
7871: untie(%bighash)
1.481 raeburn 7872: }
1.31 www 7873: }
1.62 www 7874: if ($syval) {
1.620 albertel 7875: return $env{$cache_str}=$syval;
1.62 www 7876: }
1.31 www 7877: }
1.949 raeburn 7878: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7879: return $env{$cache_str}='';
1.31 www 7880: }
7881:
7882: # ---------------------------------------------------------- Return random seed
7883:
1.32 www 7884: sub numval {
7885: my $txt=shift;
7886: $txt=~tr/A-J/0-9/;
7887: $txt=~tr/a-j/0-9/;
7888: $txt=~tr/K-T/0-9/;
7889: $txt=~tr/k-t/0-9/;
7890: $txt=~tr/U-Z/0-5/;
7891: $txt=~tr/u-z/0-5/;
7892: $txt=~s/\D//g;
1.564 albertel 7893: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7894: return int($txt);
1.368 albertel 7895: }
7896:
1.484 albertel 7897: sub numval2 {
7898: my $txt=shift;
7899: $txt=~tr/A-J/0-9/;
7900: $txt=~tr/a-j/0-9/;
7901: $txt=~tr/K-T/0-9/;
7902: $txt=~tr/k-t/0-9/;
7903: $txt=~tr/U-Z/0-5/;
7904: $txt=~tr/u-z/0-5/;
7905: $txt=~s/\D//g;
7906: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7907: my $total;
7908: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7909: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7910: return int($total);
7911: }
7912:
1.575 albertel 7913: sub numval3 {
7914: use integer;
7915: my $txt=shift;
7916: $txt=~tr/A-J/0-9/;
7917: $txt=~tr/a-j/0-9/;
7918: $txt=~tr/K-T/0-9/;
7919: $txt=~tr/k-t/0-9/;
7920: $txt=~tr/U-Z/0-5/;
7921: $txt=~tr/u-z/0-5/;
7922: $txt=~s/\D//g;
7923: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7924: my $total;
7925: foreach my $val (@txts) { $total+=$val; }
7926: if ($_64bit) { $total=(($total<<32)>>32); }
7927: return $total;
7928: }
7929:
1.675 albertel 7930: sub digest {
7931: my ($data)=@_;
7932: my $digest=&Digest::MD5::md5($data);
7933: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7934: my ($e,$f);
7935: {
7936: use integer;
7937: $e=($a+$b);
7938: $f=($c+$d);
7939: if ($_64bit) {
7940: $e=(($e<<32)>>32);
7941: $f=(($f<<32)>>32);
7942: }
7943: }
7944: if (wantarray) {
7945: return ($e,$f);
7946: } else {
7947: my $g;
7948: {
7949: use integer;
7950: $g=($e+$f);
7951: if ($_64bit) {
7952: $g=(($g<<32)>>32);
7953: }
7954: }
7955: return $g;
7956: }
7957: }
7958:
1.368 albertel 7959: sub latest_rnd_algorithm_id {
1.675 albertel 7960: return '64bit5';
1.366 albertel 7961: }
1.32 www 7962:
1.503 albertel 7963: sub get_rand_alg {
7964: my ($courseid)=@_;
1.790 albertel 7965: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7966: if ($courseid) {
1.620 albertel 7967: return $env{"course.$courseid.rndseed"};
1.503 albertel 7968: }
7969: return &latest_rnd_algorithm_id();
7970: }
7971:
1.562 albertel 7972: sub validCODE {
7973: my ($CODE)=@_;
7974: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7975: return 0;
7976: }
7977:
1.491 albertel 7978: sub getCODE {
1.620 albertel 7979: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7980: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7981: defined($Apache::lonhomework::parsing_a_task) ) &&
7982: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7983: return $Apache::lonhomework::history{'resource.CODE'};
7984: }
7985: return undef;
7986: }
7987:
1.31 www 7988: sub rndseed {
1.155 albertel 7989: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7990: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7991: if (!defined($symb)) {
1.366 albertel 7992: unless ($symb=$wsymb) { return time; }
7993: }
7994: if (!$courseid) { $courseid=$wcourseid; }
7995: if (!$domain) { $domain=$wdomain; }
7996: if (!$username) { $username=$wusername }
1.503 albertel 7997: my $which=&get_rand_alg();
1.803 albertel 7998:
1.491 albertel 7999: if (defined(&getCODE())) {
1.675 albertel 8000: if ($which eq '64bit5') {
8001: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8002: } elsif ($which eq '64bit4') {
1.575 albertel 8003: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8004: } else {
8005: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8006: }
1.675 albertel 8007: } elsif ($which eq '64bit5') {
8008: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8009: } elsif ($which eq '64bit4') {
8010: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8011: } elsif ($which eq '64bit3') {
8012: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8013: } elsif ($which eq '64bit2') {
8014: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8015: } elsif ($which eq '64bit') {
8016: return &rndseed_64bit($symb,$courseid,$domain,$username);
8017: }
8018: return &rndseed_32bit($symb,$courseid,$domain,$username);
8019: }
8020:
8021: sub rndseed_32bit {
8022: my ($symb,$courseid,$domain,$username)=@_;
8023: {
8024: use integer;
8025: my $symbchck=unpack("%32C*",$symb) << 27;
8026: my $symbseed=numval($symb) << 22;
8027: my $namechck=unpack("%32C*",$username) << 17;
8028: my $nameseed=numval($username) << 12;
8029: my $domainseed=unpack("%32C*",$domain) << 7;
8030: my $courseseed=unpack("%32C*",$courseid);
8031: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 8032: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8033: #&logthis("rndseed :$num:$symb");
1.564 albertel 8034: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 8035: return $num;
8036: }
8037: }
8038:
8039: sub rndseed_64bit {
8040: my ($symb,$courseid,$domain,$username)=@_;
8041: {
8042: use integer;
8043: my $symbchck=unpack("%32S*",$symb) << 21;
8044: my $symbseed=numval($symb) << 10;
8045: my $namechck=unpack("%32S*",$username);
8046:
8047: my $nameseed=numval($username) << 21;
8048: my $domainseed=unpack("%32S*",$domain) << 10;
8049: my $courseseed=unpack("%32S*",$courseid);
8050:
8051: my $num1=$symbchck+$symbseed+$namechck;
8052: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8053: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8054: #&logthis("rndseed :$num:$symb");
1.564 albertel 8055: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 8056: return "$num1,$num2";
1.155 albertel 8057: }
1.366 albertel 8058: }
8059:
1.443 albertel 8060: sub rndseed_64bit2 {
8061: my ($symb,$courseid,$domain,$username)=@_;
8062: {
8063: use integer;
8064: # strings need to be an even # of cahracters long, it it is odd the
8065: # last characters gets thrown away
8066: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8067: my $symbseed=numval($symb) << 10;
8068: my $namechck=unpack("%32S*",$username.' ');
8069:
8070: my $nameseed=numval($username) << 21;
1.501 albertel 8071: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8072: my $courseseed=unpack("%32S*",$courseid.' ');
8073:
8074: my $num1=$symbchck+$symbseed+$namechck;
8075: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8076: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8077: #&logthis("rndseed :$num:$symb");
1.803 albertel 8078: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 8079: return "$num1,$num2";
8080: }
8081: }
8082:
8083: sub rndseed_64bit3 {
8084: my ($symb,$courseid,$domain,$username)=@_;
8085: {
8086: use integer;
8087: # strings need to be an even # of cahracters long, it it is odd the
8088: # last characters gets thrown away
8089: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8090: my $symbseed=numval2($symb) << 10;
8091: my $namechck=unpack("%32S*",$username.' ');
8092:
8093: my $nameseed=numval2($username) << 21;
1.443 albertel 8094: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8095: my $courseseed=unpack("%32S*",$courseid.' ');
8096:
8097: my $num1=$symbchck+$symbseed+$namechck;
8098: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8100: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 8101: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8102:
1.503 albertel 8103: return "$num1:$num2";
1.443 albertel 8104: }
8105: }
8106:
1.575 albertel 8107: sub rndseed_64bit4 {
8108: my ($symb,$courseid,$domain,$username)=@_;
8109: {
8110: use integer;
8111: # strings need to be an even # of cahracters long, it it is odd the
8112: # last characters gets thrown away
8113: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8114: my $symbseed=numval3($symb) << 10;
8115: my $namechck=unpack("%32S*",$username.' ');
8116:
8117: my $nameseed=numval3($username) << 21;
8118: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8119: my $courseseed=unpack("%32S*",$courseid.' ');
8120:
8121: my $num1=$symbchck+$symbseed+$namechck;
8122: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 8123: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8124: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 8125: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8126:
8127: return "$num1:$num2";
8128: }
8129: }
8130:
1.675 albertel 8131: sub rndseed_64bit5 {
8132: my ($symb,$courseid,$domain,$username)=@_;
8133: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8134: return "$num1:$num2";
8135: }
8136:
1.366 albertel 8137: sub rndseed_CODE_64bit {
8138: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 8139: {
1.366 albertel 8140: use integer;
1.443 albertel 8141: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 8142: my $symbseed=numval2($symb);
1.491 albertel 8143: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8144: my $CODEseed=numval(&getCODE());
1.443 albertel 8145: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 8146: my $num1=$symbseed+$CODEchck;
8147: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8148: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8149: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 8150: if ($_64bit) { $num1=(($num1<<32)>>32); }
8151: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 8152: return "$num1:$num2";
1.366 albertel 8153: }
8154: }
8155:
1.575 albertel 8156: sub rndseed_CODE_64bit4 {
8157: my ($symb,$courseid,$domain,$username)=@_;
8158: {
8159: use integer;
8160: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8161: my $symbseed=numval3($symb);
8162: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8163: my $CODEseed=numval3(&getCODE());
8164: my $courseseed=unpack("%32S*",$courseid.' ');
8165: my $num1=$symbseed+$CODEchck;
8166: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 8167: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8168: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 8169: if ($_64bit) { $num1=(($num1<<32)>>32); }
8170: if ($_64bit) { $num2=(($num2<<32)>>32); }
8171: return "$num1:$num2";
8172: }
8173: }
8174:
1.675 albertel 8175: sub rndseed_CODE_64bit5 {
8176: my ($symb,$courseid,$domain,$username)=@_;
8177: my $code = &getCODE();
8178: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8179: return "$num1:$num2";
8180: }
8181:
1.366 albertel 8182: sub setup_random_from_rndseed {
8183: my ($rndseed)=@_;
1.503 albertel 8184: if ($rndseed =~/([,:])/) {
8185: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 8186: &Math::Random::random_set_seed(abs($num1),abs($num2));
8187: } else {
8188: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 8189: }
1.36 albertel 8190: }
8191:
1.474 albertel 8192: sub latest_receipt_algorithm_id {
1.835 albertel 8193: return 'receipt3';
1.474 albertel 8194: }
8195:
1.480 www 8196: sub recunique {
8197: my $fucourseid=shift;
8198: my $unique;
1.835 albertel 8199: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8200: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8201: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 8202: } else {
8203: $unique=$perlvar{'lonReceipt'};
8204: }
8205: return unpack("%32C*",$unique);
8206: }
8207:
8208: sub recprefix {
8209: my $fucourseid=shift;
8210: my $prefix;
1.835 albertel 8211: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8212: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 8213: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 8214: } else {
8215: $prefix=$perlvar{'lonHostID'};
8216: }
8217: return unpack("%32C*",$prefix);
8218: }
8219:
1.76 www 8220: sub ireceipt {
1.474 albertel 8221: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 8222:
8223: my $return =&recprefix($fucourseid).'-';
8224:
8225: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8226: $env{'request.state'} eq 'construct') {
8227: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8228: return $return;
8229: }
8230:
1.76 www 8231: my $cuname=unpack("%32C*",$funame);
8232: my $cudom=unpack("%32C*",$fudom);
8233: my $cucourseid=unpack("%32C*",$fucourseid);
8234: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8235: my $cunique=&recunique($fucourseid);
1.474 albertel 8236: my $cpart=unpack("%32S*",$part);
1.835 albertel 8237: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8238:
1.790 albertel 8239: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8240:
8241: $return.= ($cunique%$cuname+
8242: $cunique%$cudom+
8243: $cusymb%$cuname+
8244: $cusymb%$cudom+
8245: $cucourseid%$cuname+
8246: $cucourseid%$cudom+
8247: $cpart%$cuname+
8248: $cpart%$cudom);
8249: } else {
8250: $return.= ($cunique%$cuname+
8251: $cunique%$cudom+
8252: $cusymb%$cuname+
8253: $cusymb%$cudom+
8254: $cucourseid%$cuname+
8255: $cucourseid%$cudom);
8256: }
8257: return $return;
1.76 www 8258: }
8259:
8260: sub receipt {
1.474 albertel 8261: my ($part)=@_;
1.790 albertel 8262: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8263: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8264: }
1.260 ng 8265:
1.790 albertel 8266: sub whichuser {
8267: my ($passedsymb)=@_;
8268: my ($symb,$courseid,$domain,$name,$publicuser);
8269: if (defined($env{'form.grade_symb'})) {
8270: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8271: my $allowed=&allowed('vgr',$tmp_courseid);
8272: if (!$allowed &&
8273: exists($env{'request.course.sec'}) &&
8274: $env{'request.course.sec'} !~ /^\s*$/) {
8275: $allowed=&allowed('vgr',$tmp_courseid.
8276: '/'.$env{'request.course.sec'});
8277: }
8278: if ($allowed) {
8279: ($symb)=&get_env_multiple('form.grade_symb');
8280: $courseid=$tmp_courseid;
8281: ($domain)=&get_env_multiple('form.grade_domain');
8282: ($name)=&get_env_multiple('form.grade_username');
8283: return ($symb,$courseid,$domain,$name,$publicuser);
8284: }
8285: }
8286: if (!$passedsymb) {
8287: $symb=&symbread();
8288: } else {
8289: $symb=$passedsymb;
8290: }
8291: $courseid=$env{'request.course.id'};
8292: $domain=$env{'user.domain'};
8293: $name=$env{'user.name'};
8294: if ($name eq 'public' && $domain eq 'public') {
8295: if (!defined($env{'form.username'})) {
8296: $env{'form.username'}.=time.rand(10000000);
8297: }
8298: $name.=$env{'form.username'};
8299: }
8300: return ($symb,$courseid,$domain,$name,$publicuser);
8301:
8302: }
8303:
1.36 albertel 8304: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8305: # returns either the contents of the file or
8306: # -1 if the file doesn't exist
1.481 raeburn 8307: #
8308: # if the target is a file that was uploaded via DOCS,
8309: # a check will be made to see if a current copy exists on the local server,
8310: # if it does this will be served, otherwise a copy will be retrieved from
8311: # the home server for the course and stored in /home/httpd/html/userfiles on
8312: # the local server.
1.472 albertel 8313:
1.36 albertel 8314: sub getfile {
1.538 albertel 8315: my ($file) = @_;
1.609 banghart 8316: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8317: &repcopy($file);
8318: return &readfile($file);
8319: }
8320:
8321: sub repcopy_userfile {
8322: my ($file)=@_;
1.609 banghart 8323: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8324: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8325: my ($cdom,$cnum,$filename) =
1.811 albertel 8326: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8327: my $uri="/uploaded/$cdom/$cnum/$filename";
8328: if (-e "$file") {
1.828 www 8329: # we already have a local copy, check it out
1.538 albertel 8330: my @fileinfo = stat($file);
1.828 www 8331: my $rtncode;
8332: my $info;
1.538 albertel 8333: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8334: if ($lwpresp ne 'ok') {
1.828 www 8335: # there is no such file anymore, even though we had a local copy
1.482 albertel 8336: if ($rtncode eq '404') {
1.538 albertel 8337: unlink($file);
1.482 albertel 8338: }
8339: return -1;
8340: }
8341: if ($info < $fileinfo[9]) {
1.828 www 8342: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8343: return 'ok';
1.828 www 8344: } else {
8345: # the file is outdated, get rid of it
8346: unlink($file);
1.482 albertel 8347: }
1.828 www 8348: }
8349: # one way or the other, at this point, we don't have the file
8350: # construct the correct path for the file
8351: my @parts = ($cdom,$cnum);
8352: if ($filename =~ m|^(.+)/[^/]+$|) {
8353: push @parts, split(/\//,$1);
8354: }
8355: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8356: foreach my $part (@parts) {
8357: $path .= '/'.$part;
8358: if (!-e $path) {
8359: mkdir($path,0770);
1.482 albertel 8360: }
8361: }
1.828 www 8362: # now the path exists for sure
8363: # get a user agent
8364: my $ua=new LWP::UserAgent;
8365: my $transferfile=$file.'.in.transfer';
8366: # FIXME: this should flock
8367: if (-e $transferfile) { return 'ok'; }
8368: my $request;
8369: $uri=~s/^\///;
1.976.2.3 raeburn 8370: my $homeserver = &homeserver($cnum,$cdom);
8371: my $protocol = $protocol{$homeserver};
8372: $protocol = 'http' if ($protocol ne 'https');
8373: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 8374: my $response=$ua->request($request,$transferfile);
8375: # did it work?
8376: if ($response->is_error()) {
8377: unlink($transferfile);
8378: &logthis("Userfile repcopy failed for $uri");
8379: return -1;
8380: }
8381: # worked, rename the transfer file
8382: rename($transferfile,$file);
1.607 raeburn 8383: return 'ok';
1.481 raeburn 8384: }
8385:
1.517 albertel 8386: sub tokenwrapper {
8387: my $uri=shift;
1.976.2.3 raeburn 8388: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 8389: $uri=~s|^/||;
1.620 albertel 8390: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8391: my $token=$1;
1.552 albertel 8392: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8393: if ($udom && $uname && $file) {
8394: $file=~s|(\?\.*)*$||;
1.949 raeburn 8395: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.2.3 raeburn 8396: my $homeserver = &homeserver($uname,$udom);
8397: my $protocol = $protocol{$homeserver};
8398: $protocol = 'http' if ($protocol ne 'https');
8399: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 8400: (($uri=~/\?/)?'&':'?').'token='.$token.
8401: '&tokenissued='.$perlvar{'lonHostID'};
8402: } else {
8403: return '/adm/notfound.html';
8404: }
8405: }
8406:
1.828 www 8407: # call with reqtype HEAD: get last modification time
8408: # call with reqtype GET: get the file contents
8409: # Do not call this with reqtype GET for large files! It loads everything into memory
8410: #
1.481 raeburn 8411: sub getuploaded {
8412: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8413: $uri=~s/^\///;
1.976.2.3 raeburn 8414: my $homeserver = &homeserver($cnum,$cdom);
8415: my $protocol = $protocol{$homeserver};
8416: $protocol = 'http' if ($protocol ne 'https');
8417: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 8418: my $ua=new LWP::UserAgent;
8419: my $request=new HTTP::Request($reqtype,$uri);
8420: my $response=$ua->request($request);
8421: $$rtncode = $response->code;
1.482 albertel 8422: if (! $response->is_success()) {
8423: return 'failed';
8424: }
8425: if ($reqtype eq 'HEAD') {
1.486 www 8426: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8427: } elsif ($reqtype eq 'GET') {
8428: $$info = $response->content;
1.472 albertel 8429: }
1.482 albertel 8430: return 'ok';
1.36 albertel 8431: }
8432:
1.481 raeburn 8433: sub readfile {
8434: my $file = shift;
8435: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8436: my $fh;
8437: open($fh,"<$file");
8438: my $a='';
1.800 albertel 8439: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8440: return $a;
8441: }
8442:
1.36 albertel 8443: sub filelocation {
1.590 banghart 8444: my ($dir,$file) = @_;
8445: my $location;
8446: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8447:
8448: if ($file =~ m-^/adm/-) {
8449: $file=~s-^/adm/wrapper/-/-;
8450: $file=~s-^/adm/coursedocs/showdoc/-/-;
8451: }
1.882 albertel 8452:
1.590 banghart 8453: if ($file=~m:^/~:) { # is a contruction space reference
8454: $location = $file;
8455: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8456: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8457: # is a correct contruction space reference
8458: $location = $file;
1.956 raeburn 8459: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8460: $location = $file;
1.609 banghart 8461: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8462: my ($udom,$uname,$filename)=
1.811 albertel 8463: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8464: my $home=&homeserver($uname,$udom);
8465: my $is_me=0;
8466: my @ids=¤t_machine_ids();
8467: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8468: if ($is_me) {
1.955 raeburn 8469: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8470: } else {
8471: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8472: $udom.'/'.$uname.'/'.$filename;
8473: }
1.882 albertel 8474: } elsif ($file =~ m-^/adm/-) {
8475: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8476: } else {
8477: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8478: $file=~s:^/res/:/:;
8479: if ( !( $file =~ m:^/:) ) {
8480: $location = $dir. '/'.$file;
8481: } else {
8482: $location = '/home/httpd/html/res'.$file;
8483: }
1.59 albertel 8484: }
1.590 banghart 8485: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8486: while ($location=~m{/\.\./}) {
8487: if ($location =~ m{/[^/]+/\.\./}) {
8488: $location=~ s{/[^/]+/\.\./}{/}g;
8489: } else {
8490: $location=~ s{/\.\./}{/}g;
8491: }
8492: } #remove dir/..
1.590 banghart 8493: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8494: return $location;
1.46 www 8495: }
1.36 albertel 8496:
1.46 www 8497: sub hreflocation {
8498: my ($dir,$file)=@_;
1.976.2.3 raeburn 8499: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 8500: $file=filelocation($dir,$file);
1.700 albertel 8501: } elsif ($file=~m-^/adm/-) {
8502: $file=~s-^/adm/wrapper/-/-;
8503: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8504: }
8505: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8506: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8507: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8508: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8509: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8510: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8511: -/uploaded/$1/$2/-x;
1.46 www 8512: }
1.913 albertel 8513: if ($file=~ m{^/userfiles/}) {
8514: $file =~ s{^/userfiles/}{/uploaded/};
8515: }
1.462 albertel 8516: return $file;
1.465 albertel 8517: }
8518:
8519: sub current_machine_domains {
1.853 albertel 8520: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8521: }
8522:
8523: sub machine_domains {
8524: my ($hostname) = @_;
1.465 albertel 8525: my @domains;
1.838 albertel 8526: my %hostname = &all_hostnames();
1.465 albertel 8527: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8528: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8529: if ($hostname eq $name) {
1.844 albertel 8530: push(@domains,&host_domain($id));
1.465 albertel 8531: }
8532: }
8533: return @domains;
8534: }
8535:
8536: sub current_machine_ids {
1.853 albertel 8537: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8538: }
8539:
8540: sub machine_ids {
8541: my ($hostname) = @_;
8542: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8543: my @ids;
1.888 albertel 8544: my %name_to_host = &all_names();
1.889 albertel 8545: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8546: return @{ $name_to_host{$hostname} };
8547: }
8548: return;
1.31 www 8549: }
8550:
1.824 raeburn 8551: sub additional_machine_domains {
8552: my @domains;
8553: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8554: while( my $line = <$fh>) {
8555: $line =~ s/\s//g;
8556: push(@domains,$line);
8557: }
8558: return @domains;
8559: }
8560:
8561: sub default_login_domain {
8562: my $domain = $perlvar{'lonDefDomain'};
8563: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8564: foreach my $posdom (¤t_machine_domains(),
8565: &additional_machine_domains()) {
8566: if (lc($posdom) eq lc($testdomain)) {
8567: $domain=$posdom;
8568: last;
8569: }
8570: }
8571: return $domain;
8572: }
8573:
1.31 www 8574: # ------------------------------------------------------------- Declutters URLs
8575:
8576: sub declutter {
8577: my $thisfn=shift;
1.569 albertel 8578: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8579: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8580: $thisfn=~s/^\///;
1.697 albertel 8581: $thisfn=~s|^adm/wrapper/||;
8582: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8583: $thisfn=~s/^res\///;
1.235 www 8584: $thisfn=~s/\?.+$//;
1.268 www 8585: return $thisfn;
8586: }
8587:
8588: # ------------------------------------------------------------- Clutter up URLs
8589:
8590: sub clutter {
8591: my $thisfn='/'.&declutter(shift);
1.887 albertel 8592: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8593: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8594: $thisfn='/res'.$thisfn;
8595: }
1.694 albertel 8596: if ($thisfn !~m|/adm|) {
1.695 albertel 8597: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8598: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8599: } else {
8600: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8601: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8602: if ($embstyle eq 'ssi'
8603: || ($embstyle eq 'hdn')
8604: || ($embstyle eq 'rat')
8605: || ($embstyle eq 'prv')
8606: || ($embstyle eq 'ign')) {
8607: #do nothing with these
8608: } elsif (($embstyle eq 'img')
1.695 albertel 8609: || ($embstyle eq 'emb')
8610: || ($embstyle eq 'wrp')) {
8611: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8612: } elsif ($embstyle eq 'unk'
8613: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8614: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8615: } else {
1.718 www 8616: # &logthis("Got a blank emb style");
1.695 albertel 8617: }
1.694 albertel 8618: }
8619: }
1.31 www 8620: return $thisfn;
1.12 www 8621: }
8622:
1.787 albertel 8623: sub clutter_with_no_wrapper {
8624: my $uri = &clutter(shift);
8625: if ($uri =~ m-^/adm/-) {
8626: $uri =~ s-^/adm/wrapper/-/-;
8627: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8628: }
8629: return $uri;
8630: }
8631:
1.557 albertel 8632: sub freeze_escape {
8633: my ($value)=@_;
8634: if (ref($value)) {
8635: $value=&nfreeze($value);
8636: return '__FROZEN__'.&escape($value);
8637: }
8638: return &escape($value);
8639: }
8640:
1.11 www 8641:
1.557 albertel 8642: sub thaw_unescape {
8643: my ($value)=@_;
8644: if ($value =~ /^__FROZEN__/) {
8645: substr($value,0,10,undef);
8646: $value=&unescape($value);
8647: return &thaw($value);
8648: }
8649: return &unescape($value);
8650: }
8651:
1.436 albertel 8652: sub correct_line_ends {
8653: my ($result)=@_;
8654: $$result =~s/\r\n/\n/mg;
8655: $$result =~s/\r/\n/mg;
1.415 albertel 8656: }
1.1 albertel 8657: # ================================================================ Main Program
8658:
1.184 www 8659: sub goodbye {
1.204 albertel 8660: &logthis("Starting Shut down");
1.443 albertel 8661: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8662: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8663: #converted
1.599 albertel 8664: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8665: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8666: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8667: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8668: #1.1 only
1.870 albertel 8669: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8670: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8671: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8672: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8673: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8674: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8675: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8676: &flushcourselogs();
8677: &logthis("Shutting down");
8678: }
8679:
1.852 albertel 8680: sub get_dns {
1.869 albertel 8681: my ($url,$func,$ignore_cache) = @_;
8682: if (!$ignore_cache) {
8683: my ($content,$cached)=
8684: &Apache::lonnet::is_cached_new('dns',$url);
8685: if ($cached) {
8686: &$func($content);
8687: return;
8688: }
8689: }
8690:
8691: my %alldns;
1.852 albertel 8692: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8693: foreach my $dns (<$config>) {
8694: next if ($dns !~ /^\^(\S*)/x);
1.976.2.2 raeburn 8695: my $line = $1;
8696: my ($host,$protocol) = split(/:/,$line);
8697: if ($protocol ne 'https') {
8698: $protocol = 'http';
8699: }
8700: $alldns{$host} = $protocol;
1.869 albertel 8701: }
8702: while (%alldns) {
8703: my ($dns) = keys(%alldns);
1.852 albertel 8704: my $ua=new LWP::UserAgent;
1.976.2.2 raeburn 8705: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 8706: my $response=$ua->request($request);
1.976.2.2 raeburn 8707: delete($alldns{$dns});
1.852 albertel 8708: next if ($response->is_error());
8709: my @content = split("\n",$response->content);
1.869 albertel 8710: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8711: &$func(\@content);
1.869 albertel 8712: return;
1.852 albertel 8713: }
8714: close($config);
1.871 albertel 8715: my $which = (split('/',$url))[3];
8716: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8717: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8718: my @content = <$config>;
8719: &$func(\@content);
8720: return;
1.852 albertel 8721: }
1.327 albertel 8722: # ------------------------------------------------------------ Read domain file
8723: {
1.852 albertel 8724: my $loaded;
1.846 albertel 8725: my %domain;
8726:
1.852 albertel 8727: sub parse_domain_tab {
8728: my ($lines) = @_;
8729: foreach my $line (@$lines) {
8730: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8731:
1.846 albertel 8732: chomp($line);
1.852 albertel 8733: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8734: my %this_domain;
8735: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8736: 'lang_def', 'city', 'longi', 'lati',
8737: 'primary') {
8738: $this_domain{$field} = shift(@elements);
8739: }
8740: $domain{$name} = \%this_domain;
1.852 albertel 8741: }
8742: }
1.864 albertel 8743:
8744: sub reset_domain_info {
8745: undef($loaded);
8746: undef(%domain);
8747: }
8748:
1.852 albertel 8749: sub load_domain_tab {
1.869 albertel 8750: my ($ignore_cache) = @_;
8751: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8752: my $fh;
8753: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8754: my @lines = <$fh>;
8755: &parse_domain_tab(\@lines);
1.448 albertel 8756: }
1.852 albertel 8757: close($fh);
8758: $loaded = 1;
1.327 albertel 8759: }
1.846 albertel 8760:
8761: sub domain {
1.852 albertel 8762: &load_domain_tab() if (!$loaded);
8763:
1.846 albertel 8764: my ($name,$what) = @_;
8765: return if ( !exists($domain{$name}) );
8766:
8767: if (!$what) {
8768: return $domain{$name}{'description'};
8769: }
8770: return $domain{$name}{$what};
8771: }
1.974 raeburn 8772:
8773: sub domain_info {
8774: &load_domain_tab() if (!$loaded);
8775: return %domain;
8776: }
8777:
1.327 albertel 8778: }
8779:
8780:
1.1 albertel 8781: # ------------------------------------------------------------- Read hosts file
8782: {
1.838 albertel 8783: my %hostname;
1.844 albertel 8784: my %hostdom;
1.845 albertel 8785: my %libserv;
1.852 albertel 8786: my $loaded;
1.888 albertel 8787: my %name_to_host;
1.852 albertel 8788:
8789: sub parse_hosts_tab {
8790: my ($file) = @_;
8791: foreach my $configline (@$file) {
8792: next if ($configline =~ /^(\#|\s*$ )/x);
8793: next if ($configline =~ /^\^/);
8794: chomp($configline);
1.968 raeburn 8795: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 8796: $name=~s/\s//g;
8797: if ($id && $domain && $role && $name) {
8798: $hostname{$id}=$name;
1.888 albertel 8799: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8800: $hostdom{$id}=$domain;
8801: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 8802: if (defined($protocol)) {
8803: if ($protocol eq 'https') {
8804: $protocol{$id} = $protocol;
8805: } else {
8806: $protocol{$id} = 'http';
8807: }
1.968 raeburn 8808: } else {
1.969 raeburn 8809: $protocol{$id} = 'http';
1.968 raeburn 8810: }
1.852 albertel 8811: }
8812: }
8813: }
1.864 albertel 8814:
8815: sub reset_hosts_info {
1.897 albertel 8816: &purge_remembered();
1.864 albertel 8817: &reset_domain_info();
8818: &reset_hosts_ip_info();
1.892 albertel 8819: undef(%name_to_host);
1.864 albertel 8820: undef(%hostname);
8821: undef(%hostdom);
8822: undef(%libserv);
8823: undef($loaded);
8824: }
1.1 albertel 8825:
1.852 albertel 8826: sub load_hosts_tab {
1.869 albertel 8827: my ($ignore_cache) = @_;
8828: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8829: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8830: my @config = <$config>;
8831: &parse_hosts_tab(\@config);
8832: close($config);
8833: $loaded=1;
1.1 albertel 8834: }
1.852 albertel 8835:
1.838 albertel 8836: sub hostname {
1.852 albertel 8837: &load_hosts_tab() if (!$loaded);
8838:
1.838 albertel 8839: my ($lonid) = @_;
8840: return $hostname{$lonid};
8841: }
1.845 albertel 8842:
1.838 albertel 8843: sub all_hostnames {
1.852 albertel 8844: &load_hosts_tab() if (!$loaded);
8845:
1.838 albertel 8846: return %hostname;
8847: }
1.845 albertel 8848:
1.888 albertel 8849: sub all_names {
8850: &load_hosts_tab() if (!$loaded);
8851:
8852: return %name_to_host;
8853: }
8854:
1.974 raeburn 8855: sub all_host_domain {
8856: &load_hosts_tab() if (!$loaded);
8857: return %hostdom;
8858: }
8859:
1.845 albertel 8860: sub is_library {
1.852 albertel 8861: &load_hosts_tab() if (!$loaded);
8862:
1.845 albertel 8863: return exists($libserv{$_[0]});
8864: }
8865:
8866: sub all_library {
1.852 albertel 8867: &load_hosts_tab() if (!$loaded);
8868:
1.845 albertel 8869: return %libserv;
8870: }
8871:
1.841 albertel 8872: sub get_servers {
1.852 albertel 8873: &load_hosts_tab() if (!$loaded);
8874:
1.841 albertel 8875: my ($domain,$type) = @_;
8876: my %possible_hosts = ($type eq 'library') ? %libserv
8877: : %hostname;
8878: my %result;
1.842 albertel 8879: if (ref($domain) eq 'ARRAY') {
8880: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8881: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8882: $result{$host} = $hostname;
8883: }
8884: }
8885: } else {
8886: while ( my ($host,$hostname) = each(%possible_hosts)) {
8887: if ($hostdom{$host} eq $domain) {
8888: $result{$host} = $hostname;
8889: }
1.841 albertel 8890: }
8891: }
8892: return %result;
8893: }
1.845 albertel 8894:
1.844 albertel 8895: sub host_domain {
1.852 albertel 8896: &load_hosts_tab() if (!$loaded);
8897:
1.844 albertel 8898: my ($lonid) = @_;
8899: return $hostdom{$lonid};
8900: }
8901:
1.841 albertel 8902: sub all_domains {
1.852 albertel 8903: &load_hosts_tab() if (!$loaded);
8904:
1.841 albertel 8905: my %seen;
8906: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8907: return @uniq;
8908: }
1.1 albertel 8909: }
8910:
1.847 albertel 8911: {
8912: my %iphost;
1.856 albertel 8913: my %name_to_ip;
8914: my %lonid_to_ip;
1.869 albertel 8915:
1.847 albertel 8916: sub get_hosts_from_ip {
8917: my ($ip) = @_;
8918: my %iphosts = &get_iphost();
8919: if (ref($iphosts{$ip})) {
8920: return @{$iphosts{$ip}};
8921: }
8922: return;
1.839 albertel 8923: }
1.864 albertel 8924:
8925: sub reset_hosts_ip_info {
8926: undef(%iphost);
8927: undef(%name_to_ip);
8928: undef(%lonid_to_ip);
8929: }
1.856 albertel 8930:
8931: sub get_host_ip {
8932: my ($lonid) = @_;
8933: if (exists($lonid_to_ip{$lonid})) {
8934: return $lonid_to_ip{$lonid};
8935: }
8936: my $name=&hostname($lonid);
8937: my $ip = gethostbyname($name);
8938: return if (!$ip || length($ip) ne 4);
8939: $ip=inet_ntoa($ip);
8940: $name_to_ip{$name} = $ip;
8941: $lonid_to_ip{$lonid} = $ip;
8942: return $ip;
8943: }
1.847 albertel 8944:
8945: sub get_iphost {
1.869 albertel 8946: my ($ignore_cache) = @_;
1.894 albertel 8947:
1.869 albertel 8948: if (!$ignore_cache) {
8949: if (%iphost) {
8950: return %iphost;
8951: }
8952: my ($ip_info,$cached)=
8953: &Apache::lonnet::is_cached_new('iphost','iphost');
8954: if ($cached) {
8955: %iphost = %{$ip_info->[0]};
8956: %name_to_ip = %{$ip_info->[1]};
8957: %lonid_to_ip = %{$ip_info->[2]};
8958: return %iphost;
8959: }
8960: }
1.894 albertel 8961:
8962: # get yesterday's info for fallback
8963: my %old_name_to_ip;
8964: my ($ip_info,$cached)=
8965: &Apache::lonnet::is_cached_new('iphost','iphost');
8966: if ($cached) {
8967: %old_name_to_ip = %{$ip_info->[1]};
8968: }
8969:
1.888 albertel 8970: my %name_to_host = &all_names();
8971: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8972: my $ip;
8973: if (!exists($name_to_ip{$name})) {
8974: $ip = gethostbyname($name);
8975: if (!$ip || length($ip) ne 4) {
1.894 albertel 8976: if (defined($old_name_to_ip{$name})) {
8977: $ip = $old_name_to_ip{$name};
8978: &logthis("Can't find $name defaulting to old $ip");
8979: } else {
8980: &logthis("Name $name no IP found");
8981: next;
8982: }
8983: } else {
8984: $ip=inet_ntoa($ip);
1.847 albertel 8985: }
8986: $name_to_ip{$name} = $ip;
8987: } else {
8988: $ip = $name_to_ip{$name};
1.653 albertel 8989: }
1.888 albertel 8990: foreach my $id (@{ $name_to_host{$name} }) {
8991: $lonid_to_ip{$id} = $ip;
8992: }
8993: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8994: }
1.869 albertel 8995: &Apache::lonnet::do_cache_new('iphost','iphost',
8996: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8997: 48*60*60);
1.869 albertel 8998:
1.847 albertel 8999: return %iphost;
1.598 albertel 9000: }
9001: }
9002:
1.862 albertel 9003: BEGIN {
9004:
9005: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9006: unless ($readit) {
9007: {
9008: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9009: %perlvar = (%perlvar,%{$configvars});
9010: }
9011:
9012:
1.1 albertel 9013: # ------------------------------------------------------ Read spare server file
9014: {
1.448 albertel 9015: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 9016:
9017: while (my $configline=<$config>) {
9018: chomp($configline);
1.284 matthew 9019: if ($configline) {
1.784 albertel 9020: my ($host,$type) = split(':',$configline,2);
1.785 albertel 9021: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 9022: push(@{ $spareid{$type} }, $host);
1.1 albertel 9023: }
9024: }
1.448 albertel 9025: close($config);
1.1 albertel 9026: }
1.11 www 9027: # ------------------------------------------------------------ Read permissions
9028: {
1.448 albertel 9029: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 9030:
9031: while (my $configline=<$config>) {
1.448 albertel 9032: chomp($configline);
9033: if ($configline) {
9034: my ($role,$perm)=split(/ /,$configline);
9035: if ($perm ne '') { $pr{$role}=$perm; }
9036: }
1.11 www 9037: }
1.448 albertel 9038: close($config);
1.11 www 9039: }
9040:
9041: # -------------------------------------------- Read plain texts for permissions
9042: {
1.448 albertel 9043: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 9044:
9045: while (my $configline=<$config>) {
1.448 albertel 9046: chomp($configline);
9047: if ($configline) {
1.742 raeburn 9048: my ($short,@plain)=split(/:/,$configline);
9049: %{$prp{$short}} = ();
9050: if (@plain > 0) {
9051: $prp{$short}{'std'} = $plain[0];
9052: for (my $i=1; $i<@plain; $i++) {
9053: $prp{$short}{'alt'.$i} = $plain[$i];
9054: }
9055: }
1.448 albertel 9056: }
1.135 www 9057: }
1.448 albertel 9058: close($config);
1.135 www 9059: }
9060:
9061: # ---------------------------------------------------------- Read package table
9062: {
1.448 albertel 9063: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 9064:
9065: while (my $configline=<$config>) {
1.483 albertel 9066: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 9067: chomp($configline);
9068: my ($short,$plain)=split(/:/,$configline);
9069: my ($pack,$name)=split(/\&/,$short);
9070: if ($plain ne '') {
9071: $packagetab{$pack.'&'.$name.'&name'}=$name;
9072: $packagetab{$short}=$plain;
9073: }
1.11 www 9074: }
1.448 albertel 9075: close($config);
1.329 matthew 9076: }
9077:
9078: # ------------- set up temporary directory
9079: {
9080: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9081:
1.11 www 9082: }
9083:
1.794 albertel 9084: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9085: 'compress_threshold'=> 20_000,
9086: });
1.185 www 9087:
1.281 www 9088: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 9089: $dumpcount=0;
1.958 www 9090: $locknum=0;
1.22 www 9091:
1.163 harris41 9092: &logtouch();
1.672 albertel 9093: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 9094: $readit=1;
1.564 albertel 9095: {
9096: use integer;
9097: my $test=(2**32)+1;
1.568 albertel 9098: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 9099: &logthis(" Detected 64bit platform ($_64bit)");
9100: }
1.195 www 9101: }
1.1 albertel 9102: }
1.179 www 9103:
1.1 albertel 9104: 1;
1.191 harris41 9105: __END__
9106:
1.243 albertel 9107: =pod
9108:
1.191 harris41 9109: =head1 NAME
9110:
1.243 albertel 9111: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 9112:
9113: =head1 SYNOPSIS
9114:
1.243 albertel 9115: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 9116:
9117: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9118:
1.243 albertel 9119: Common parameters:
9120:
9121: =over 4
9122:
9123: =item *
9124:
9125: $uname : an internal username (if $cname expecting a course Id specifically)
9126:
9127: =item *
9128:
9129: $udom : a domain (if $cdom expecting a course's domain specifically)
9130:
9131: =item *
9132:
9133: $symb : a resource instance identifier
9134:
9135: =item *
9136:
9137: $namespace : the name of a .db file that contains the data needed or
9138: being set.
9139:
9140: =back
9141:
1.394 bowersj2 9142: =head1 OVERVIEW
1.191 harris41 9143:
1.394 bowersj2 9144: lonnet provides subroutines which interact with the
9145: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9146: about classes, users, and resources.
1.243 albertel 9147:
9148: For many of these objects you can also use this to store data about
9149: them or modify them in various ways.
1.191 harris41 9150:
1.394 bowersj2 9151: =head2 Symbs
1.191 harris41 9152:
1.394 bowersj2 9153: To identify a specific instance of a resource, LON-CAPA uses symbols
9154: or "symbs"X<symb>. These identifiers are built from the URL of the
9155: map, the resource number of the resource in the map, and the URL of
9156: the resource itself. The latter is somewhat redundant, but might help
9157: if maps change.
9158:
9159: An example is
9160:
9161: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9162:
9163: The respective map entry is
9164:
9165: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9166: title="Problem 2">
9167: </resource>
9168:
9169: Symbs are used by the random number generator, as well as to store and
9170: restore data specific to a certain instance of for example a problem.
9171:
9172: =head2 Storing And Retrieving Data
9173:
9174: X<store()>X<cstore()>X<restore()>Three of the most important functions
9175: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9176: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9177: is is the non-critical message twin of cstore. These functions are for
9178: handlers to store a perl hash to a user's permanent data space in an
9179: easy manner, and to retrieve it again on another call. It is expected
9180: that a handler would use this once at the beginning to retrieve data,
9181: and then again once at the end to send only the new data back.
9182:
9183: The data is stored in the user's data directory on the user's
9184: homeserver under the ID of the course.
9185:
9186: The hash that is returned by restore will have all of the previous
9187: value for all of the elements of the hash.
9188:
9189: Example:
9190:
9191: #creating a hash
9192: my %hash;
9193: $hash{'foo'}='bar';
9194:
9195: #storing it
9196: &Apache::lonnet::cstore(\%hash);
9197:
9198: #changing a value
9199: $hash{'foo'}='notbar';
9200:
9201: #adding a new value
9202: $hash{'bar'}='foo';
9203: &Apache::lonnet::cstore(\%hash);
9204:
9205: #retrieving the hash
9206: my %history=&Apache::lonnet::restore();
9207:
9208: #print the hash
9209: foreach my $key (sort(keys(%history))) {
9210: print("\%history{$key} = $history{$key}");
9211: }
9212:
9213: Will print out:
1.191 harris41 9214:
1.394 bowersj2 9215: %history{1:foo} = bar
9216: %history{1:keys} = foo:timestamp
9217: %history{1:timestamp} = 990455579
9218: %history{2:bar} = foo
9219: %history{2:foo} = notbar
9220: %history{2:keys} = foo:bar:timestamp
9221: %history{2:timestamp} = 990455580
9222: %history{bar} = foo
9223: %history{foo} = notbar
9224: %history{timestamp} = 990455580
9225: %history{version} = 2
9226:
9227: Note that the special hash entries C<keys>, C<version> and
9228: C<timestamp> were added to the hash. C<version> will be equal to the
9229: total number of versions of the data that have been stored. The
9230: C<timestamp> attribute will be the UNIX time the hash was
9231: stored. C<keys> is available in every historical section to list which
9232: keys were added or changed at a specific historical revision of a
9233: hash.
9234:
9235: B<Warning>: do not store the hash that restore returns directly. This
9236: will cause a mess since it will restore the historical keys as if the
9237: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 9238:
1.394 bowersj2 9239: Calling convention:
1.191 harris41 9240:
1.394 bowersj2 9241: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9242: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 9243:
1.394 bowersj2 9244: For more detailed information, see lonnet specific documentation.
1.191 harris41 9245:
1.394 bowersj2 9246: =head1 RETURN MESSAGES
1.191 harris41 9247:
1.394 bowersj2 9248: =over 4
1.191 harris41 9249:
1.394 bowersj2 9250: =item * B<con_lost>: unable to contact remote host
1.191 harris41 9251:
1.394 bowersj2 9252: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9253: when the connection is brought back up
1.191 harris41 9254:
1.394 bowersj2 9255: =item * B<con_failed>: unable to contact remote host and unable to save message
9256: for later delivery
1.191 harris41 9257:
1.967 bisitz 9258: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9259:
1.394 bowersj2 9260: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9261: that was requested
1.191 harris41 9262:
1.243 albertel 9263: =back
1.191 harris41 9264:
1.243 albertel 9265: =head1 PUBLIC SUBROUTINES
1.191 harris41 9266:
1.243 albertel 9267: =head2 Session Environment Functions
1.191 harris41 9268:
1.243 albertel 9269: =over 4
1.191 harris41 9270:
1.394 bowersj2 9271: =item *
9272: X<appenv()>
1.949 raeburn 9273: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9274: the user envirnoment file, and will be restored for each access this
1.620 albertel 9275: user makes during this session, also modifies the %env for the current
1.949 raeburn 9276: process. Optional rolesarrayref - if defined contains a reference to an array
9277: of roles which are exempt from the restriction on modifying user.role entries
9278: in the user's environment.db and in %env.
1.191 harris41 9279:
9280: =item *
1.394 bowersj2 9281: X<delenv()>
1.976.2.7 raeburn 9282: B<delenv($delthis,$regexp)>: removes all items from the session
9283: environment file that begin with $delthis. If the
9284: optional second arg - $regexp - is true, $delthis is treated as a
9285: regular expression, otherwise \Q$delthis\E is used.
9286: The values are also deleted from the current processes %env.
1.191 harris41 9287:
1.795 albertel 9288: =item * get_env_multiple($name)
9289:
9290: gets $name from the %env hash, it seemlessly handles the cases where multiple
9291: values may be defined and end up as an array ref.
9292:
9293: returns an array of values
9294:
1.243 albertel 9295: =back
9296:
9297: =head2 User Information
1.191 harris41 9298:
1.243 albertel 9299: =over 4
1.191 harris41 9300:
9301: =item *
1.394 bowersj2 9302: X<queryauthenticate()>
9303: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9304: authentication scheme
9305:
9306: =item *
1.394 bowersj2 9307: X<authenticate()>
9308: B<authenticate($uname,$upass,$udom)>: try to
9309: authenticate user from domain's lib servers (first use the current
9310: one). C<$upass> should be the users password.
1.191 harris41 9311:
9312: =item *
1.394 bowersj2 9313: X<homeserver()>
9314: B<homeserver($uname,$udom)>: find the server which has
9315: the user's directory and files (there must be only one), this caches
9316: the answer, and also caches if there is a borken connection.
1.191 harris41 9317:
9318: =item *
1.394 bowersj2 9319: X<idget()>
9320: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9321: (IDs are a unique resource in a domain, there must be only 1 ID per
9322: username, and only 1 username per ID in a specific domain) (returns
9323: hash: id=>name,id=>name)
1.191 harris41 9324:
9325: =item *
1.394 bowersj2 9326: X<idrget()>
9327: B<idrget($udom,@unames)>: find the IDs behind a list of
9328: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9329:
9330: =item *
1.394 bowersj2 9331: X<idput()>
9332: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9333:
9334: =item *
1.394 bowersj2 9335: X<rolesinit()>
9336: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9337:
9338: =item *
1.551 albertel 9339: X<getsection()>
9340: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9341: course $cname, return section name/number or '' for "not in course"
9342: and '-1' for "no section"
9343:
9344: =item *
1.394 bowersj2 9345: X<userenvironment()>
9346: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9347: passed in @what from the requested user's environment, returns a hash
9348:
1.858 raeburn 9349: =item *
9350: X<userlog_query()>
1.859 albertel 9351: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9352: activity.log file. %filters defines filters applied when parsing the
9353: log file. These can be start or end timestamps, or the type of action
9354: - log to look for Login or Logout events, check for Checkin or
9355: Checkout, role for role selection. The response is in the form
9356: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9357: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9358:
1.243 albertel 9359: =back
9360:
9361: =head2 User Roles
9362:
9363: =over 4
9364:
9365: =item *
9366:
1.810 raeburn 9367: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9368: F: full access
9369: U,I,K: authentication modes (cxx only)
9370: '': forbidden
9371: 1: user needs to choose course
9372: 2: browse allowed
1.766 albertel 9373: A: passphrase authentication needed
1.243 albertel 9374:
9375: =item *
9376:
9377: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9378: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9379: and course level
9380:
9381: =item *
9382:
9383: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
9384: explanation of a user role term
9385:
1.832 raeburn 9386: =item *
9387:
1.935 raeburn 9388: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9389: All arguments are optional. Returns a hash of a roles, either for
9390: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9391: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9392: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9393: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9394: For each key, value is set to colon-separated start and end times for
9395: the role. If no username and domain are specified, will default to
1.934 raeburn 9396: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9397: of role statuses (active, future or previous), roles
9398: (e.g., cc,in, st etc.) and domains of the roles which can be used
9399: to restrict the list of roles reported. If no array ref is
9400: provided for types, will default to return only active roles.
1.834 albertel 9401:
1.243 albertel 9402: =back
9403:
9404: =head2 User Modification
9405:
9406: =over 4
9407:
9408: =item *
9409:
1.957 raeburn 9410: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9411: user for the level given by URL. Optional start and end dates (leave empty
9412: string or zero for "no date")
1.191 harris41 9413:
9414: =item *
9415:
1.243 albertel 9416: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9417: change a users, password, possible return values are: ok,
9418: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9419: refused
1.191 harris41 9420:
9421: =item *
9422:
1.243 albertel 9423: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9424:
9425: =item *
9426:
1.963 raeburn 9427: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9428: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9429: modify user
1.191 harris41 9430:
9431: =item *
9432:
1.286 matthew 9433: modifystudent
9434:
1.957 raeburn 9435: modify a student's enrollment and identification information.
1.286 matthew 9436: The course id is resolved based on the current users environment.
9437: This means the envoking user must be a course coordinator or otherwise
9438: associated with a course.
9439:
1.297 matthew 9440: This call is essentially a wrapper for lonnet::modifyuser and
9441: lonnet::modify_student_enrollment
1.286 matthew 9442:
9443: Inputs:
9444:
9445: =over 4
9446:
1.957 raeburn 9447: =item B<$udom> Student's loncapa domain
1.286 matthew 9448:
1.957 raeburn 9449: =item B<$uname> Student's loncapa login name
1.286 matthew 9450:
1.964 bisitz 9451: =item B<$uid> Student/Employee ID
1.286 matthew 9452:
1.957 raeburn 9453: =item B<$umode> Student's authentication mode
1.286 matthew 9454:
1.957 raeburn 9455: =item B<$upass> Student's password
1.286 matthew 9456:
1.957 raeburn 9457: =item B<$first> Student's first name
1.286 matthew 9458:
1.957 raeburn 9459: =item B<$middle> Student's middle name
1.286 matthew 9460:
1.957 raeburn 9461: =item B<$last> Student's last name
1.286 matthew 9462:
1.957 raeburn 9463: =item B<$gene> Student's generation
1.286 matthew 9464:
1.957 raeburn 9465: =item B<$usec> Student's section in course
1.286 matthew 9466:
9467: =item B<$end> Unix time of the roles expiration
9468:
9469: =item B<$start> Unix time of the roles start date
9470:
9471: =item B<$forceid> If defined, allow $uid to be changed
9472:
9473: =item B<$desiredhome> server to use as home server for student
9474:
1.957 raeburn 9475: =item B<$email> Student's permanent e-mail address
9476:
9477: =item B<$type> Type of enrollment (auto or manual)
9478:
1.963 raeburn 9479: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9480:
9481: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9482:
1.963 raeburn 9483: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9484:
1.963 raeburn 9485: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9486:
1.963 raeburn 9487: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9488:
1.286 matthew 9489: =back
1.297 matthew 9490:
9491: =item *
9492:
9493: modify_student_enrollment
9494:
9495: Change a students enrollment status in a class. The environment variable
9496: 'role.request.course' must be defined for this function to proceed.
9497:
9498: Inputs:
9499:
9500: =over 4
9501:
9502: =item $udom, students domain
9503:
9504: =item $uname, students name
9505:
9506: =item $uid, students user id
9507:
9508: =item $first, students first name
9509:
9510: =item $middle
9511:
9512: =item $last
9513:
9514: =item $gene
9515:
9516: =item $usec
9517:
9518: =item $end
9519:
9520: =item $start
9521:
1.957 raeburn 9522: =item $type
9523:
9524: =item $locktype
9525:
9526: =item $cid
9527:
9528: =item $selfenroll
9529:
9530: =item $context
9531:
1.297 matthew 9532: =back
9533:
1.191 harris41 9534:
9535: =item *
9536:
1.243 albertel 9537: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9538: custom role; give a custom role to a user for the level given by URL. Specify
9539: name and domain of role author, and role name
1.191 harris41 9540:
9541: =item *
9542:
1.243 albertel 9543: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9544:
9545: =item *
9546:
1.243 albertel 9547: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9548:
9549: =back
9550:
9551: =head2 Course Infomation
9552:
9553: =over 4
1.191 harris41 9554:
9555: =item *
9556:
1.631 albertel 9557: coursedescription($courseid) : returns a hash of information about the
9558: specified course id, including all environment settings for the
9559: course, the description of the course will be in the hash under the
9560: key 'description'
1.191 harris41 9561:
9562: =item *
9563:
1.624 albertel 9564: resdata($name,$domain,$type,@which) : request for current parameter
9565: setting for a specific $type, where $type is either 'course' or 'user',
9566: @what should be a list of parameters to ask about. This routine caches
9567: answers for 5 minutes.
1.243 albertel 9568:
1.877 foxr 9569: =item *
9570:
9571: get_courseresdata($courseid, $domain) : dump the entire course resource
9572: data base, returning a hash that is keyed by the resource name and has
9573: values that are the resource value. I believe that the timestamps and
9574: versions are also returned.
9575:
9576:
1.243 albertel 9577: =back
9578:
9579: =head2 Course Modification
9580:
9581: =over 4
1.191 harris41 9582:
9583: =item *
9584:
1.243 albertel 9585: writecoursepref($courseid,%prefs) : write preferences (environment
9586: database) for a course
1.191 harris41 9587:
9588: =item *
9589:
1.243 albertel 9590: createcourse($udom,$description,$url) : make/modify course
9591:
9592: =back
9593:
9594: =head2 Resource Subroutines
9595:
9596: =over 4
1.191 harris41 9597:
9598: =item *
9599:
1.243 albertel 9600: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9601:
9602: =item *
9603:
1.243 albertel 9604: repcopy($filename) : subscribes to the requested file, and attempts to
9605: replicate from the owning library server, Might return
1.607 raeburn 9606: 'unavailable', 'not_found', 'forbidden', 'ok', or
9607: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9608: resource. Expects the local filesystem pathname
9609: (/home/httpd/html/res/....)
9610:
9611: =back
9612:
9613: =head2 Resource Information
9614:
9615: =over 4
1.191 harris41 9616:
9617: =item *
9618:
1.243 albertel 9619: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9620: a vairety of different possible values, $varname should be a request
9621: string, and the other parameters can be used to specify who and what
9622: one is asking about.
9623:
9624: Possible values for $varname are environment.lastname (or other item
9625: from the envirnment hash), user.name (or someother aspect about the
9626: user), resource.0.maxtries (or some other part and parameter of a
9627: resource)
1.204 albertel 9628:
9629: =item *
9630:
1.243 albertel 9631: directcondval($number) : get current value of a condition; reads from a state
9632: string
1.204 albertel 9633:
9634: =item *
9635:
1.243 albertel 9636: condval($condidx) : value of condition index based on state
1.204 albertel 9637:
9638: =item *
9639:
1.243 albertel 9640: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9641: resource's metadata, $what should be either a specific key, or either
9642: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9643: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9644:
9645: this function automatically caches all requests
1.191 harris41 9646:
9647: =item *
9648:
1.243 albertel 9649: metadata_query($query,$custom,$customshow) : make a metadata query against the
9650: network of library servers; returns file handle of where SQL and regex results
9651: will be stored for query
1.191 harris41 9652:
9653: =item *
9654:
1.243 albertel 9655: symbread($filename) : return symbolic list entry (filename argument optional);
9656: returns the data handle
1.191 harris41 9657:
9658: =item *
9659:
1.243 albertel 9660: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9661: a possible symb for the URL in $thisfn, and if is an encryypted
9662: resource that the user accessed using /enc/ returns a 1 on success, 0
9663: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9664: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9665:
1.191 harris41 9666:
9667: =item *
9668:
1.243 albertel 9669: symbclean($symb) : removes versions numbers from a symb, returns the
9670: cleaned symb
1.191 harris41 9671:
9672: =item *
9673:
1.243 albertel 9674: is_on_map($uri) : checks if the $uri is somewhere on the current
9675: course map, user must be in a course for it to work.
1.191 harris41 9676:
9677: =item *
9678:
1.243 albertel 9679: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9680:
9681: =item *
9682:
1.243 albertel 9683: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9684: a random seed, all arguments are optional, if they aren't sent it uses the
9685: environment to derive them. Note: if symb isn't sent and it can't get one
9686: from &symbread it will use the current time as its return value
1.191 harris41 9687:
9688: =item *
9689:
1.243 albertel 9690: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9691: unfakeable, receipt
1.191 harris41 9692:
9693: =item *
9694:
1.620 albertel 9695: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9696:
9697: =item *
9698:
1.243 albertel 9699: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9700:
9701: =item *
9702:
1.243 albertel 9703: 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 9704:
9705: =item *
9706:
1.243 albertel 9707: 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 9708:
9709: =item *
9710:
1.243 albertel 9711: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9712:
9713: =item *
9714:
1.243 albertel 9715: devalidate($symb) : devalidate temporary spreadsheet calculations,
9716: forcing spreadsheet to reevaluate the resource scores next time.
9717:
9718: =back
9719:
9720: =head2 Storing/Retreiving Data
9721:
9722: =over 4
1.191 harris41 9723:
9724: =item *
9725:
1.243 albertel 9726: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9727: for this url; hashref needs to be given and should be a \%hashname; the
9728: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9729: be derived from the env
1.191 harris41 9730:
9731: =item *
9732:
1.243 albertel 9733: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9734: uses critical subroutine
1.191 harris41 9735:
9736: =item *
9737:
1.243 albertel 9738: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9739: all args are optional
1.191 harris41 9740:
9741: =item *
9742:
1.717 albertel 9743: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9744: dumps the complete (or key matching regexp) namespace into a hash
9745: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9746: normally &store()ed into
9747:
9748: $range should be either an integer '100' (give me the first 100
9749: matching records)
9750: or be two integers sperated by a - with no spaces
9751: '30-50' (give me the 30th through the 50th matching
9752: records)
9753:
9754:
9755: =item *
9756:
9757: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9758: replaces a &store() version of data with a replacement set of data
9759: for a particular resource in a namespace passed in the $storehash hash
9760: reference
9761:
9762: =item *
9763:
1.243 albertel 9764: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9765: works very similar to store/cstore, but all data is stored in a
9766: temporary location and can be reset using tmpreset, $storehash should
9767: be a hash reference, returns nothing on success
1.191 harris41 9768:
9769: =item *
9770:
1.243 albertel 9771: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9772: similar to restore, but all data is stored in a temporary location and
9773: can be reset using tmpreset. Returns a hash of values on success,
9774: error string otherwise.
1.191 harris41 9775:
9776: =item *
9777:
1.243 albertel 9778: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9779: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9780:
9781: =item *
9782:
1.243 albertel 9783: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9784: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9785:
9786: =item *
9787:
1.243 albertel 9788: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9789: namesp ($udom and $uname are optional)
1.191 harris41 9790:
9791: =item *
9792:
1.702 albertel 9793: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9794: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9795: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9796:
1.702 albertel 9797: $range should be either an integer '100' (give me the first 100
9798: matching records)
9799: or be two integers sperated by a - with no spaces
9800: '30-50' (give me the 30th through the 50th matching
9801: records)
1.449 matthew 9802: =item *
9803:
9804: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9805: $store can be a scalar, an array reference, or if the amount to be
9806: incremented is > 1, a hash reference.
9807:
9808: ($udom and $uname are optional)
1.191 harris41 9809:
9810: =item *
9811:
1.243 albertel 9812: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9813: ($udom and $uname are optional)
1.191 harris41 9814:
9815: =item *
9816:
1.243 albertel 9817: cput($namespace,$storehash,$udom,$uname) : critical put
9818: ($udom and $uname are optional)
1.191 harris41 9819:
9820: =item *
9821:
1.748 albertel 9822: newput($namespace,$storehash,$udom,$uname) :
9823:
9824: Attempts to store the items in the $storehash, but only if they don't
9825: currently exist, if this succeeds you can be certain that you have
9826: successfully created a new key value pair in the $namespace db.
9827:
9828:
9829: Args:
9830: $namespace: name of database to store values to
9831: $storehash: hashref to store to the db
9832: $udom: (optional) domain of user containing the db
9833: $uname: (optional) name of user caontaining the db
9834:
9835: Returns:
9836: 'ok' -> succeeded in storing all keys of $storehash
9837: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9838: least <key> already existed in the db (other
9839: requested keys may also already exist)
1.967 bisitz 9840: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 9841: 'con_lost' -> unable to contact request server
9842: 'refused' -> action was not allowed by remote machine
9843:
9844:
9845: =item *
9846:
1.243 albertel 9847: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9848: reference filled in from namesp (encrypts the return communication)
9849: ($udom and $uname are optional)
1.191 harris41 9850:
9851: =item *
9852:
1.243 albertel 9853: log($udom,$name,$home,$message) : write to permanent log for user; use
9854: critical subroutine
9855:
1.806 raeburn 9856: =item *
9857:
1.860 raeburn 9858: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9859: array reference filled in from namespace found in domain level on either
9860: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9861:
9862: =item *
9863:
1.860 raeburn 9864: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9865: domain level either on specified domain server ($uhome) or primary domain
9866: server ($udom and $uhome are optional)
1.806 raeburn 9867:
1.943 raeburn 9868: =item *
9869:
9870: get_domain_defaults($target_domain) : returns hash with defaults for
9871: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9872: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9873: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9874: Values are retrieved from cache (if current), or from domain's configuration.db
9875: (if available), or lastly from values in lonTabs/dns_domain,tab,
9876: or lonTabs/domain.tab.
9877:
9878: %domdefaults = &get_auth_defaults($target_domain);
9879:
1.243 albertel 9880: =back
9881:
9882: =head2 Network Status Functions
9883:
9884: =over 4
1.191 harris41 9885:
9886: =item *
9887:
9888: dirlist($uri) : return directory list based on URI
9889:
9890: =item *
9891:
1.243 albertel 9892: spareserver() : find server with least workload from spare.tab
9893:
9894: =back
9895:
9896: =head2 Apache Request
9897:
9898: =over 4
1.191 harris41 9899:
9900: =item *
9901:
1.243 albertel 9902: ssi($url,%hash) : server side include, does a complete request cycle on url to
9903: localhost, posts hash
9904:
9905: =back
9906:
9907: =head2 Data to String to Data
9908:
9909: =over 4
1.191 harris41 9910:
9911: =item *
9912:
1.243 albertel 9913: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9914: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9915:
9916: =item *
9917:
1.243 albertel 9918: hashref2str($hashref) : convert a hashref into a string complete with
9919: escaping and '=' and '&' separators, supports elements that are
9920: arrayrefs and hashrefs
1.191 harris41 9921:
9922: =item *
9923:
1.243 albertel 9924: arrayref2str($arrayref) : convert an arrayref into a string complete
9925: with escaping and '&' separators, supports elements that are arrayrefs
9926: and hashrefs
1.191 harris41 9927:
9928: =item *
9929:
1.243 albertel 9930: str2hash($string) : convert string to hash using unescaping and
9931: splitting on '=' and '&', supports elements that are arrayrefs and
9932: hashrefs
1.191 harris41 9933:
9934: =item *
9935:
1.243 albertel 9936: str2array($string) : convert string to hash using unescaping and
9937: splitting on '&', supports elements that are arrayrefs and hashrefs
9938:
9939: =back
9940:
9941: =head2 Logging Routines
9942:
9943: =over 4
9944:
9945: These routines allow one to make log messages in the lonnet.log and
9946: lonnet.perm logfiles.
1.191 harris41 9947:
9948: =item *
9949:
1.243 albertel 9950: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9951:
9952: =item *
9953:
1.243 albertel 9954: logthis() : append message to the normal lonnet.log file, it gets
9955: preiodically rolled over and deleted.
1.191 harris41 9956:
9957: =item *
9958:
1.243 albertel 9959: logperm() : append a permanent message to lonnet.perm.log, this log
9960: file never gets deleted by any automated portion of the system, only
9961: messages of critical importance should go in here.
9962:
9963: =back
9964:
9965: =head2 General File Helper Routines
9966:
9967: =over 4
1.191 harris41 9968:
9969: =item *
9970:
1.481 raeburn 9971: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9972: (a) files in /uploaded
9973: (i) If a local copy of the file exists -
9974: compares modification date of local copy with last-modified date for
9975: definitive version stored on home server for course. If local copy is
9976: stale, requests a new version from the home server and stores it.
9977: If the original has been removed from the home server, then local copy
9978: is unlinked.
9979: (ii) If local copy does not exist -
9980: requests the file from the home server and stores it.
9981:
9982: If $caller is 'uploadrep':
9983: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9984: for request for files originally uploaded via DOCS.
9985: - returns 'ok' if fresh local copy now available, -1 otherwise.
9986:
9987: Otherwise:
9988: This indicates a call from the content generation phase of the request.
9989: - returns the entire contents of the file or -1.
9990:
9991: (b) files in /res
9992: - returns the entire contents of a file or -1;
9993: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9994:
1.712 albertel 9995:
9996: =item *
9997:
9998: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9999: reference
10000:
10001: returns either a stat() list of data about the file or an empty list
10002: if the file doesn't exist or couldn't find out about it (connection
10003: problems or user unknown)
10004:
1.191 harris41 10005: =item *
10006:
1.243 albertel 10007: filelocation($dir,$file) : returns file system location of a file
10008: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10009: directory that relative $file lookups are to looked in ($dir of /a/dir
10010: and a file of ../bob will become /a/bob)
1.191 harris41 10011:
10012: =item *
10013:
10014: hreflocation($dir,$file) : returns file system location or a URL; same as
10015: filelocation except for hrefs
10016:
10017: =item *
10018:
10019: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10020:
1.243 albertel 10021: =back
10022:
1.608 albertel 10023: =head2 Usererfile file routines (/uploaded*)
10024:
10025: =over 4
10026:
10027: =item *
10028:
10029: userfileupload(): main rotine for putting a file in a user or course's
10030: filespace, arguments are,
10031:
1.620 albertel 10032: formname - required - this is the name of the element in $env where the
1.608 albertel 10033: filename, and the contents of the file to create/modifed exist
1.620 albertel 10034: the filename is in $env{'form.'.$formname.'.filename'} and the
10035: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 10036: coursedoc - if true, store the file in the course of the active role
10037: of the current user
10038: subdir - required - subdirectory to put the file in under ../userfiles/
10039: if undefined, it will be placed in "unknown"
10040:
10041: (This routine calls clean_filename() to remove any dangerous
10042: characters from the filename, and then calls finuserfileupload() to
10043: complete the transaction)
10044:
10045: returns either the url of the uploaded file (/uploaded/....) if successful
10046: and /adm/notfound.html if unsuccessful
10047:
10048: =item *
10049:
10050: clean_filename(): routine for cleaing a filename up for storage in
10051: userfile space, argument is:
10052:
10053: filename - proposed filename
10054:
10055: returns: the new clean filename
10056:
10057: =item *
10058:
10059: finishuserfileupload(): routine that creaes and sends the file to
10060: userspace, probably shouldn't be called directly
10061:
10062: docuname: username or courseid of destination for the file
10063: docudom: domain of user/course of destination for the file
10064: formname: same as for userfileupload()
10065: fname: filename (inculding subdirectories) for the file
10066:
10067: returns either the url of the uploaded file (/uploaded/....) if successful
10068: and /adm/notfound.html if unsuccessful
10069:
10070: =item *
10071:
10072: renameuserfile(): renames an existing userfile to a new name
10073:
10074: Args:
10075: docuname: username or courseid of destination for the file
10076: docudom: domain of user/course of destination for the file
10077: old: current file name (including any subdirs under userfiles)
10078: new: desired file name (including any subdirs under userfiles)
10079:
10080: =item *
10081:
10082: mkdiruserfile(): creates a directory is a userfiles dir
10083:
10084: Args:
10085: docuname: username or courseid of destination for the file
10086: docudom: domain of user/course of destination for the file
10087: dir: dir to create (including any subdirs under userfiles)
10088:
10089: =item *
10090:
10091: removeuserfile(): removes a file that exists in userfiles
10092:
10093: Args:
10094: docuname: username or courseid of destination for the file
10095: docudom: domain of user/course of destination for the file
10096: fname: filname to delete (including any subdirs under userfiles)
10097:
10098: =item *
10099:
10100: removeuploadedurl(): convience function for removeuserfile()
10101:
10102: Args:
10103: url: a full /uploaded/... url to delete
10104:
1.747 albertel 10105: =item *
10106:
10107: get_portfile_permissions():
10108: Args:
10109: domain: domain of user or course contain the portfolio files
10110: user: name of user or num of course contain the portfolio files
10111: Returns:
10112: hashref of a dump of the proper file_permissions.db
10113:
10114:
10115: =item *
10116:
10117: get_access_controls():
10118:
10119: Args:
10120: current_permissions: the hash ref returned from get_portfile_permissions()
10121: group: (optional) the group you want the files associated with
10122: file: (optional) the file you want access info on
10123:
10124: Returns:
1.749 raeburn 10125: a hash (keys are file names) of hashes containing
10126: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10127: values are XML containing access control settings (see below)
1.747 albertel 10128:
10129: Internal notes:
10130:
1.749 raeburn 10131: access controls are stored in file_permissions.db as key=value pairs.
10132: key -> path to file/file_name\0uniqueID:scope_end_start
10133: where scope -> public,guest,course,group,domains or users.
10134: end -> UNIX time for end of access (0 -> no end date)
10135: start -> UNIX time for start of access
10136:
10137: value -> XML description of access control
10138: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10139: <start></start>
10140: <end></end>
10141:
10142: <password></password> for scope type = guest
10143:
10144: <domain></domain> for scope type = course or group
10145: <number></number>
10146: <roles id="">
10147: <role></role>
10148: <access></access>
10149: <section></section>
10150: <group></group>
10151: </roles>
10152:
10153: <dom></dom> for scope type = domains
10154:
10155: <users> for scope type = users
10156: <user>
10157: <uname></uname>
10158: <udom></udom>
10159: </user>
10160: </users>
10161: </scope>
10162:
10163: Access data is also aggregated for each file in an additional key=value pair:
10164: key -> path to file/file_name\0accesscontrol
10165: value -> reference to hash
10166: hash contains key = value pairs
10167: where key = uniqueID:scope_end_start
10168: value = UNIX time record was last updated
10169:
10170: Used to improve speed of look-ups of access controls for each file.
10171:
10172: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10173:
10174: modify_access_controls():
10175:
10176: Modifies access controls for a portfolio file
10177: Args
10178: 1. file name
10179: 2. reference to hash of required changes,
10180: 3. domain
10181: 4. username
10182: where domain,username are the domain of the portfolio owner
10183: (either a user or a course)
10184:
10185: Returns:
10186: 1. result of additions or updates ('ok' or 'error', with error message).
10187: 2. result of deletions ('ok' or 'error', with error message).
10188: 3. reference to hash of any new or updated access controls.
10189: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10190: key = integer (inbound ID)
10191: value = uniqueID
1.747 albertel 10192:
1.608 albertel 10193: =back
10194:
1.243 albertel 10195: =head2 HTTP Helper Routines
10196:
10197: =over 4
10198:
1.191 harris41 10199: =item *
10200:
10201: escape() : unpack non-word characters into CGI-compatible hex codes
10202:
10203: =item *
10204:
10205: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10206:
1.243 albertel 10207: =back
10208:
10209: =head1 PRIVATE SUBROUTINES
10210:
10211: =head2 Underlying communication routines (Shouldn't call)
10212:
10213: =over 4
10214:
10215: =item *
10216:
10217: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10218:
10219: =item *
10220:
10221: reply() : uses subreply to send a message to remote machine, logs all failures
10222:
10223: =item *
10224:
10225: critical() : passes a critical message to another server; if cannot
10226: get through then place message in connection buffer directory and
10227: returns con_delayed, if incapable of saving message, returns
10228: con_failed
10229:
10230: =item *
10231:
10232: reconlonc() : tries to reconnect lonc client processes.
10233:
10234: =back
10235:
10236: =head2 Resource Access Logging
10237:
10238: =over 4
10239:
10240: =item *
10241:
10242: flushcourselogs() : flush (save) buffer logs and access logs
10243:
10244: =item *
10245:
10246: courselog($what) : save message for course in hash
10247:
10248: =item *
10249:
10250: courseacclog($what) : save message for course using &courselog(). Perform
10251: special processing for specific resource types (problems, exams, quizzes, etc).
10252:
1.191 harris41 10253: =item *
10254:
10255: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10256: as a PerlChildExitHandler
1.243 albertel 10257:
10258: =back
10259:
10260: =head2 Other
10261:
10262: =over 4
10263:
10264: =item *
10265:
10266: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10267:
10268: =back
10269:
10270: =cut
1.877 foxr 10271:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>